{"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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall unsafe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\n--Reorder right now\nforeign import ccall unsafe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall unsafe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall unsafe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall unsafe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddturnOffCountDead :: DdManager -> IO ()\ncuddturnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall unsafe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall unsafe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall unsafe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\n","old_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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall unsafe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\n--Reorder right now\nforeign import ccall unsafe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall unsafe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n\n--Reordering stats\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall unsafe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall unsafe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddturnOffCountDead :: DdManager -> IO ()\ncuddturnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall unsafe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall unsafe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall unsafe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0392befb3e69eb94a3f815a394759a2a6fcd73c6","subject":"update to gathering of device properties","message":"update to gathering of device properties\n\nOld versions of the driver API gathered device properties via two separate means. This was changed in CUDA-5.0 to present a single interface, which we now use.\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Device.chs","new_file":"Foreign\/CUDA\/Driver\/Device.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n#ifdef USE_EMPTY_CASE\n{-# LANGUAGE EmptyCase #-}\n#endif\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device (\n\n -- * Device Management\n Device(..), -- should be exported abstractly\n DeviceProperties(..), DeviceAttribute(..), Compute(..), ComputeMode(..), InitFlag,\n initialise, capability, device, attribute, count, name, props, totalMem\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\nimport Control.Applicative\nimport Prelude\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Eq, Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as DeviceAttribute\n { underscoreToCase\n , MAX as CU_DEVICE_ATTRIBUTE_MAX } -- ignore\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> CUDevProp nocode #}\n\n\n#if CUDA_VERSION < 5000\n--\n-- Properties of the compute device (internal helper).\n-- Replaced by cuDeviceGetAttribute in CUDA-5.0 and later.\n--\ndata CUDevProp = CUDevProp\n {\n cuMaxThreadsPerBlock :: !Int, -- Maximum number of threads per block\n cuMaxBlockSize :: !(Int,Int,Int), -- Maximum size of each dimension of a block\n cuMaxGridSize :: !(Int,Int,Int), -- Maximum size of each dimension of a grid\n cuSharedMemPerBlock :: !Int64, -- Shared memory available per block in bytes\n cuTotalConstMem :: !Int64, -- Constant memory available on device in bytes\n cuWarpSize :: !Int, -- Warp size in threads (SIMD width)\n cuMemPitch :: !Int64, -- Maximum pitch in bytes allowed by memory copies\n cuRegsPerBlock :: !Int, -- 32-bit registers available per block\n cuClockRate :: !Int, -- Clock frequency in kilohertz\n cuTextureAlignment :: !Int64 -- Alignment requirement for textures\n }\n deriving (Show)\n\n\ninstance Storable CUDevProp where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"no instance for Foreign.Storable.poke DeviceProperties\"\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n [t1,t2,t3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxThreadsDim#} p\n [g1,g2,g3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxGridSize#} p\n\n return CUDevProp\n {\n cuMaxThreadsPerBlock = tb,\n cuMaxBlockSize = (t1,t2,t3),\n cuMaxGridSize = (g1,g2,g3),\n cuSharedMemPerBlock = sm,\n cuTotalConstMem = cm,\n cuWarpSize = ws,\n cuMemPitch = mp,\n cuRegsPerBlock = rb,\n cuClockRate = cl,\n cuTextureAlignment = ta\n }\n#endif\n\n\n-- |\n-- Possible option flags for CUDA initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata InitFlag\ninstance Enum InitFlag where\n#ifdef USE_EMPTY_CASE\n toEnum x = case x of {}\n fromEnum x = case x of {}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. This must be called before any other\n-- driver function.\n--\n-- \n--\n{-# INLINEABLE initialise #-}\ninitialise :: [InitFlag] -> IO ()\ninitialise !flags = nothingIfOk =<< cuInit flags\n\n{-# INLINE cuInit #-}\n{# fun unsafe cuInit\n { combineBitMasks `[InitFlag]' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\n{-# INLINEABLE capability #-}\ncapability :: Device -> IO Compute\n#if CUDA_VERSION >= 5000\ncapability !dev =\n Compute <$> attribute dev ComputeCapabilityMajor\n <*> attribute dev ComputeCapabilityMinor\n#else\n-- Deprecated as of CUDA-5.0\n--\ncapability !dev =\n (\\(!s,!a,!b) -> resultIfOk (s,Compute a b)) =<< cuDeviceComputeCapability dev\n\n{-# INLINE cuDeviceComputeCapability #-}\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return a handle to the compute device at the given ordinal.\n--\n-- \n--\n{-# INLINEABLE device #-}\ndevice :: Int -> IO Device\ndevice !d = resultIfOk =<< cuDeviceGet d\n\n{-# INLINE cuDeviceGet #-}\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peek\n\n\n-- |\n-- Return the selected attribute for the given device.\n--\n-- \n--\n{-# INLINEABLE attribute #-}\nattribute :: Device -> DeviceAttribute -> IO Int\nattribute !d !a = resultIfOk =<< cuDeviceGetAttribute a d\n\n{-# INLINE cuDeviceGetAttribute #-}\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `DeviceAttribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0.\n--\n-- \n--\n{-# INLINEABLE count #-}\ncount :: IO Int\ncount = resultIfOk =<< cuDeviceGetCount\n\n{-# INLINE cuDeviceGetCount #-}\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- The identifying name of the device.\n--\n-- \n--\n{-# INLINEABLE name #-}\nname :: Device -> IO String\nname !d = resultIfOk =<< cuDeviceGetName d\n\n{-# INLINE cuDeviceGetName #-}\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\n{-# INLINEABLE props #-}\nprops :: Device -> IO DeviceProperties\nprops !d = do\n\n#if CUDA_VERSION < 5000\n -- Old versions of the CUDA API used the separate cuDeviceGetProperties\n -- function to probe some properties, and cuDeviceGetAttribute for\n -- others. As of CUDA-5.0, the former was deprecated and its\n -- functionality subsumed by the latter, which we use below.\n --\n p <- resultIfOk =<< cuDeviceGetProperties d\n let cm = cuTotalConstMem p\n sm = cuSharedMemPerBlock p\n rb = cuRegsPerBlock p\n ws = cuWarpSize p\n tb = cuMaxThreadsPerBlock p\n bs = cuMaxBlockSize p\n gs = cuMaxGridSize p\n cl = cuClockRate p\n mp = cuMemPitch p\n ta = cuTextureAlignment p\n#else\n cm <- fromIntegral <$> attribute d TotalConstantMemory\n sm <- fromIntegral <$> attribute d SharedMemoryPerBlock\n mp <- fromIntegral <$> attribute d MaxPitch\n ta <- fromIntegral <$> attribute d TextureAlignment\n cl <- attribute d ClockRate\n ws <- attribute d WarpSize\n rb <- attribute d RegistersPerBlock\n tb <- attribute d MaxThreadsPerBlock\n bs <- (,,) <$> attribute d MaxBlockDimX\n <*> attribute d MaxBlockDimY\n <*> attribute d MaxBlockDimZ\n gs <- (,,) <$> attribute d MaxGridDimX\n <*> attribute d MaxGridDimY\n <*> attribute d MaxGridDimZ\n#endif\n\n -- The rest of the properties.\n --\n n <- name d\n cc <- capability d\n gm <- totalMem d\n pc <- attribute d MultiprocessorCount\n md <- toEnum `fmap` attribute d ComputeMode\n ov <- toBool `fmap` attribute d GpuOverlap\n ke <- toBool `fmap` attribute d KernelExecTimeout\n tg <- toBool `fmap` attribute d Integrated\n hm <- toBool `fmap` attribute d CanMapHostMemory\n#if CUDA_VERSION >= 3000\n ck <- toBool `fmap` attribute d ConcurrentKernels\n ee <- toBool `fmap` attribute d EccEnabled\n u1 <- attribute d MaximumTexture1dWidth\n u21 <- attribute d MaximumTexture2dWidth\n u22 <- attribute d MaximumTexture2dHeight\n u31 <- attribute d MaximumTexture3dWidth\n u32 <- attribute d MaximumTexture3dHeight\n u33 <- attribute d MaximumTexture3dDepth\n#endif\n#if CUDA_VERSION >= 4000\n ae <- attribute d AsyncEngineCount\n l2 <- attribute d L2CacheSize\n tm <- attribute d MaxThreadsPerMultiprocessor\n mw <- attribute d GlobalMemoryBusWidth\n mc <- attribute d MemoryClockRate\n pb <- attribute d PciBusId\n pd <- attribute d PciDeviceId\n pm <- attribute d PciDomainId\n ua <- toBool `fmap` attribute d UnifiedAddressing\n tcc <- toBool `fmap` attribute d TccDriver\n#endif\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = cc,\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxBlockSize = bs,\n maxGridSize = gs,\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n#if CUDA_VERSION >= 3000\n concurrentKernels = ck,\n eccEnabled = ee,\n maxTextureDim1D = u1,\n maxTextureDim2D = (u21,u22),\n maxTextureDim3D = (u31,u32,u33),\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount = ae,\n cacheMemL2 = l2,\n maxThreadsPerMultiProcessor = tm,\n memBusWidth = mw,\n memClockRate = mc,\n pciInfo = PCI pb pd pm,\n tccDriverEnabled = tcc,\n unifiedAddressing = ua,\n#endif\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n#if CUDA_VERSION < 5000\n-- Deprecated as of CUDA-5.0\n{-# INLINE cuDeviceGetProperties #-}\n{# fun unsafe cuDeviceGetProperties\n { alloca- `CUDevProp' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- The total memory available on the device (bytes).\n--\n-- \n--\n{-# INLINEABLE totalMem #-}\ntotalMem :: Device -> IO Int64\ntotalMem !d = resultIfOk =<< cuDeviceTotalMem d\n\n{-# INLINE cuDeviceTotalMem #-}\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int64' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n#ifdef USE_EMPTY_CASE\n{-# LANGUAGE EmptyCase #-}\n#endif\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device (\n\n -- * Device Management\n Device(..), -- should be exported abstractly\n DeviceProperties(..), DeviceAttribute(..), Compute(..), ComputeMode(..), InitFlag,\n initialise, capability, device, attribute, count, name, props, totalMem\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Eq, Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as DeviceAttribute\n { underscoreToCase\n , MAX as CU_DEVICE_ATTRIBUTE_MAX } -- ignore\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> CUDevProp nocode #}\n\n\n--\n-- Properties of the compute device (internal helper)\n--\ndata CUDevProp = CUDevProp\n {\n cuMaxThreadsPerBlock :: !Int, -- Maximum number of threads per block\n cuMaxBlockSize :: !(Int,Int,Int), -- Maximum size of each dimension of a block\n cuMaxGridSize :: !(Int,Int,Int), -- Maximum size of each dimension of a grid\n cuSharedMemPerBlock :: !Int64, -- Shared memory available per block in bytes\n cuTotalConstMem :: !Int64, -- Constant memory available on device in bytes\n cuWarpSize :: !Int, -- Warp size in threads (SIMD width)\n cuMemPitch :: !Int64, -- Maximum pitch in bytes allowed by memory copies\n cuRegsPerBlock :: !Int, -- 32-bit registers available per block\n cuClockRate :: !Int, -- Clock frequency in kilohertz\n cuTextureAlignment :: !Int64 -- Alignment requirement for textures\n }\n deriving (Show)\n\n\ninstance Storable CUDevProp where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"no instance for Foreign.Storable.poke DeviceProperties\"\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n [t1,t2,t3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxThreadsDim#} p\n [g1,g2,g3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxGridSize#} p\n\n return CUDevProp\n {\n cuMaxThreadsPerBlock = tb,\n cuMaxBlockSize = (t1,t2,t3),\n cuMaxGridSize = (g1,g2,g3),\n cuSharedMemPerBlock = sm,\n cuTotalConstMem = cm,\n cuWarpSize = ws,\n cuMemPitch = mp,\n cuRegsPerBlock = rb,\n cuClockRate = cl,\n cuTextureAlignment = ta\n }\n\n\n-- |\n-- Possible option flags for CUDA initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata InitFlag\ninstance Enum InitFlag where\n#ifdef USE_EMPTY_CASE\n toEnum x = case x of {}\n fromEnum x = case x of {}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. Must be called before any other driver\n-- function.\n--\n{-# INLINEABLE initialise #-}\ninitialise :: [InitFlag] -> IO ()\ninitialise !flags = nothingIfOk =<< cuInit flags\n\n{-# INLINE cuInit #-}\n{# fun unsafe cuInit\n { combineBitMasks `[InitFlag]' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\n{-# INLINEABLE capability #-}\ncapability :: Device -> IO Compute\ncapability !dev =\n (\\(!s,!a,!b) -> resultIfOk (s,Compute a b)) =<< cuDeviceComputeCapability dev\n\n{-# INLINE cuDeviceComputeCapability #-}\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a device handle\n--\n{-# INLINEABLE device #-}\ndevice :: Int -> IO Device\ndevice !d = resultIfOk =<< cuDeviceGet d\n\n{-# INLINE cuDeviceGet #-}\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peek\n\n\n-- |\n-- Return the selected attribute for the given device\n--\n{-# INLINEABLE attribute #-}\nattribute :: Device -> DeviceAttribute -> IO Int\nattribute !d !a = resultIfOk =<< cuDeviceGetAttribute a d\n\n{-# INLINE cuDeviceGetAttribute #-}\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `DeviceAttribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0\n--\n{-# INLINEABLE count #-}\ncount :: IO Int\ncount = resultIfOk =<< cuDeviceGetCount\n\n{-# INLINE cuDeviceGetCount #-}\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Name of the device\n--\n{-# INLINEABLE name #-}\nname :: Device -> IO String\nname !d = resultIfOk =<< cuDeviceGetName d\n\n{-# INLINE cuDeviceGetName #-}\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\n\n-- Annoyingly, the driver API requires several different functions to extract\n-- all device properties that are part of a single structure in the runtime API\n--\n{-# INLINEABLE props #-}\nprops :: Device -> IO DeviceProperties\nprops !d = do\n p <- resultIfOk =<< cuDeviceGetProperties d\n\n -- And the remaining properties\n --\n n <- name d\n cc <- capability d\n gm <- totalMem d\n pc <- attribute d MultiprocessorCount\n md <- toEnum `fmap` attribute d ComputeMode\n ov <- toBool `fmap` attribute d GpuOverlap\n ke <- toBool `fmap` attribute d KernelExecTimeout\n tg <- toBool `fmap` attribute d Integrated\n hm <- toBool `fmap` attribute d CanMapHostMemory\n#if CUDA_VERSION >= 3000\n ck <- toBool `fmap` attribute d ConcurrentKernels\n ee <- toBool `fmap` attribute d EccEnabled\n u1 <- attribute d MaximumTexture1dWidth\n u21 <- attribute d MaximumTexture2dWidth\n u22 <- attribute d MaximumTexture2dHeight\n u31 <- attribute d MaximumTexture3dWidth\n u32 <- attribute d MaximumTexture3dHeight\n u33 <- attribute d MaximumTexture3dDepth\n#endif\n#if CUDA_VERSION >= 4000\n ae <- attribute d AsyncEngineCount\n l2 <- attribute d L2CacheSize\n tm <- attribute d MaxThreadsPerMultiprocessor\n mw <- attribute d GlobalMemoryBusWidth\n mc <- attribute d MemoryClockRate\n pb <- attribute d PciBusId\n pd <- attribute d PciDeviceId\n pm <- attribute d PciDomainId\n ua <- toBool `fmap` attribute d UnifiedAddressing\n tcc <- toBool `fmap` attribute d TccDriver\n#endif\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = cc,\n totalGlobalMem = gm,\n totalConstMem = cuTotalConstMem p,\n sharedMemPerBlock = cuSharedMemPerBlock p,\n regsPerBlock = cuRegsPerBlock p,\n warpSize = cuWarpSize p,\n maxThreadsPerBlock = cuMaxThreadsPerBlock p,\n maxBlockSize = cuMaxBlockSize p,\n maxGridSize = cuMaxGridSize p,\n clockRate = cuClockRate p,\n multiProcessorCount = pc,\n memPitch = cuMemPitch p,\n textureAlignment = cuTextureAlignment p,\n computeMode = md,\n deviceOverlap = ov,\n#if CUDA_VERSION >= 3000\n concurrentKernels = ck,\n eccEnabled = ee,\n maxTextureDim1D = u1,\n maxTextureDim2D = (u21,u22),\n maxTextureDim3D = (u31,u32,u33),\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount = ae,\n cacheMemL2 = l2,\n maxThreadsPerMultiProcessor = tm,\n memBusWidth = mw,\n memClockRate = mc,\n pciInfo = PCI pb pd pm,\n tccDriverEnabled = tcc,\n unifiedAddressing = ua,\n#endif\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n{-# INLINE cuDeviceGetProperties #-}\n{# fun unsafe cuDeviceGetProperties\n { alloca- `CUDevProp' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Total memory available on the device (bytes)\n--\n{-# INLINEABLE totalMem #-}\ntotalMem :: Device -> IO Int64\ntotalMem !d = resultIfOk =<< cuDeviceTotalMem d\n\n{-# INLINE cuDeviceTotalMem #-}\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int64' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"24d9ed88ad4e86377cc57794c19adeeb0eb85148","subject":"wibble","message":"wibble\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"707ec5f8457c9bcfa1f03b1c78b1c72dbf661f94","subject":"slightly more descriptive error strings","message":"slightly more descriptive error strings\n\nIgnore-this: 8eb51c0bbc734e46fef577e25a476909\n\ndarcs-hash:20091208065102-9241b-ffc8cb9780e0c71fa610e5e35bd2026c0daf3fd2.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Error.chs","new_file":"Foreign\/CUDA\/Driver\/Error.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Error\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Error\n where\n\n\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cuda\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum CUresult as Status\n { underscoreToCase\n , CUDA_SUCCESS as Success }\n with prefix=\"CUDA_ERROR\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return a descriptive error string associated with a particular error code\n-- XXX: yes, not very descriptive...\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-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\nresultIfOk :: (Status, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (describe status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\nnothingIfOk :: Status -> Maybe String\nnothingIfOk = nothingIf (== Success) describe\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Error\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Error\n where\n\n\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cuda\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum CUresult as Status\n { underscoreToCase\n , CUDA_SUCCESS as Success }\n with prefix=\"CUDA_ERROR\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return a descriptive error string associated with a particular error code\n-- XXX: yes, not very descriptive...\n--\ndescribe :: Status -> String\ndescribe = show\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\nresultIfOk :: (Status, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (describe status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\nnothingIfOk :: Status -> Maybe String\nnothingIfOk = nothingIf (== Success) describe\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"01d7f494b245f2b87482c25eda0021b98ea947ae","subject":"Fix documenation to Editable.","message":"Fix documenation to Editable.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/Editable.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/Editable.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Interface Editable\n--\n-- Author : Axel Simon, Duncan Coutts\n--\n-- Created: 30 July 2004\n--\n-- Copyright (C) 1999-2005 Axel Simon, 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-- Interface for text-editing widgets\n--\nmodule Graphics.UI.Gtk.Entry.Editable (\n-- * Detail\n-- \n-- | The 'Editable' interface is an interface which should be implemented by\n-- text editing widgets, such as 'Entry'.\n-- It contains functions for generically manipulating an editable\n-- widget, a large number of action signals used for key bindings, and several\n-- signals that an application can connect to to modify the behavior of a\n-- widget.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | GInterface\n-- | +----Editable\n-- @\n\n-- * Types\n Editable,\n EditableClass,\n castToEditable, gTypeEditable,\n toEditable,\n\n-- * Methods\n editableSelectRegion,\n editableGetSelectionBounds,\n editableInsertText,\n editableDeleteText,\n editableGetChars,\n editableCutClipboard,\n editableCopyClipboard,\n editablePasteClipboard,\n editableDeleteSelection,\n editableSetEditable,\n editableGetEditable,\n editableSetPosition,\n editableGetPosition,\n\n-- * Attributes\n editablePosition,\n editableEditable,\n\n-- * Signals\n onEditableChanged,\n afterEditableChanged,\n onDeleteText,\n afterDeleteText,\n stopDeleteText,\n onInsertText,\n afterInsertText,\n stopInsertText\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Selects a region of text. The characters that are selected are those\n-- characters at positions from @startPos@ up to, but not including @endPos@.\n-- If @endPos@ is negative, then the the characters selected will be those\n-- characters from @startPos@ to the end of the text.\n--\n-- Calling this function with @start@=1 and @end@=4 it will mark \\\"ask\\\" in\n-- the string \\\"Haskell\\\".\n--\neditableSelectRegion :: EditableClass self => self\n -> Int -- ^ @start@ - the starting position.\n -> Int -- ^ @end@ - the end position.\n -> IO ()\neditableSelectRegion self start end =\n {# call editable_select_region #}\n (toEditable self)\n (fromIntegral start)\n (fromIntegral end)\n\n-- | Gets the current selection bounds, if there is a selection.\n--\neditableGetSelectionBounds :: EditableClass self => self\n -> IO (Int,Int) -- ^ @(start, end)@ - the starting and end positions. This\n -- pair is not ordered. The @end@ index represents the\n -- position of the cursor. The @start@ index is the other end\n -- of the selection. If both numbers are equal there is in\n -- fact no selection.\neditableGetSelectionBounds self =\n alloca $ \\startPtr ->\n alloca $ \\endPtr -> do\n {# call unsafe editable_get_selection_bounds #}\n (toEditable self)\n startPtr\n endPtr\n start <- liftM fromIntegral $ peek startPtr\n end <- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- | Inserts text at a given position.\n--\neditableInsertText :: EditableClass self => self\n -> String -- ^ @newText@ - the text to insert.\n -> Int -- ^ @position@ - the position at which to insert the text.\n -> IO Int -- ^ returns the position after the newly inserted text.\neditableInsertText self newText position = \n with (fromIntegral position) $ \\positionPtr ->\n withUTFStringLen newText $ \\(newTextPtr, newTextLength) -> do\n {# call editable_insert_text #}\n (toEditable self)\n newTextPtr\n (fromIntegral newTextLength)\n positionPtr\n position <- peek positionPtr\n return (fromIntegral position)\n\n-- | Deletes a sequence of characters. The characters that are deleted are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters deleted will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableDeleteText :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO ()\neditableDeleteText self startPos endPos =\n {# call editable_delete_text #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n\n-- | Retrieves a sequence of characters. The characters that are retrieved are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters retrieved will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableGetChars :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO String -- ^ returns the characters in the indicated region.\neditableGetChars self startPos endPos =\n {# call unsafe editable_get_chars #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n >>= readUTFString\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard and then deleted from the widget.\n--\neditableCutClipboard :: EditableClass self => self -> IO ()\neditableCutClipboard self =\n {# call editable_cut_clipboard #}\n (toEditable self)\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard.\n--\neditableCopyClipboard :: EditableClass self => self -> IO ()\neditableCopyClipboard self =\n {# call editable_copy_clipboard #}\n (toEditable self)\n\n-- | Causes the contents of the clipboard to be pasted into the given widget\n-- at the current cursor position.\n--\neditablePasteClipboard :: EditableClass self => self -> IO ()\neditablePasteClipboard self =\n {# call editable_paste_clipboard #}\n (toEditable self)\n\n-- | Deletes the current contents of the widgets selection and disclaims the\n-- selection.\n--\neditableDeleteSelection :: EditableClass self => self -> IO ()\neditableDeleteSelection self =\n {# call editable_delete_selection #}\n (toEditable self)\n\n-- | Sets the cursor position.\n--\neditableSetPosition :: EditableClass self => self\n -> Int -- ^ @position@ - the position of the cursor. The cursor is\n -- displayed before the character with the given (base 0) index in\n -- the widget. The value must be less than or equal to the number of\n -- characters in the widget. A value of -1 indicates that the\n -- position should be set after the last character in the entry.\n -> IO ()\neditableSetPosition self position =\n {# call editable_set_position #}\n (toEditable self)\n (fromIntegral position)\n\n-- | Retrieves the current cursor position.\n--\neditableGetPosition :: EditableClass self => self\n -> IO Int -- ^ returns the position of the cursor. The cursor is displayed\n -- before the character with the given (base 0) index in the widget.\n -- The value will be less than or equal to the number of characters\n -- in the widget. Note that this position is in characters, not in\n -- bytes.\neditableGetPosition self =\n liftM fromIntegral $\n {# call unsafe editable_get_position #}\n (toEditable self)\n\n-- | Determines if the user can edit the text in the editable widget or not.\n--\neditableSetEditable :: EditableClass self => self\n -> Bool -- ^ @isEditable@ - @True@ if the user is allowed to edit the text\n -- in the widget.\n -> IO ()\neditableSetEditable self isEditable =\n {# call editable_set_editable #}\n (toEditable self)\n (fromBool isEditable)\n\n-- | Retrieves whether the text is editable. See 'editableSetEditable'.\n--\neditableGetEditable :: EditableClass self => self -> IO Bool\neditableGetEditable self =\n liftM toBool $\n {# call editable_get_editable #}\n (toEditable self)\n\n--------------------\n-- Attributes\n\n-- | \\'position\\' property. See 'editableGetPosition' and\n-- 'editableSetPosition'\n--\neditablePosition :: EditableClass self => Attr self Int\neditablePosition = newAttr\n editableGetPosition\n editableSetPosition\n\n-- | \\'editable\\' property. See 'editableGetEditable' and\n-- 'editableSetEditable'\n--\neditableEditable :: EditableClass self => Attr self Bool\neditableEditable = newAttr\n editableGetEditable\n editableSetEditable\n\n--------------------\n-- Signals\n\n-- | The 'onEditableChanged' signal is emitted at the end of a single\n-- user-visible operation on the contents of the 'Editable'.\n--\n-- * For inctance, a paste operation that replaces the contents of the\n-- selection will cause only one signal emission (even though it is\n-- implemented by first deleting the selection, then inserting the new\n-- content, and may cause multiple 'onEditableInserText' signals to be\n-- emitted).\n--\nonEditableChanged, afterEditableChanged :: EditableClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEditableChanged = connect_NONE__NONE \"changed\" False\nafterEditableChanged = connect_NONE__NONE \"changed\" True\n\n-- | Emitted when a piece of text is deleted from the 'Editable' widget.\n--\n-- * See 'onInsertText' for information on how to use this signal.\n--\nonDeleteText, afterDeleteText :: EditableClass self => self\n -> (Int -> Int -> IO ()) -- ^ @(\\startPos endPos -> ...)@\n -> IO (ConnectId self)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- | Stop the current signal that deletes text.\nstopDeleteText :: EditableClass self => ConnectId self -> IO ()\nstopDeleteText (ConnectId _ obj) =\n signalStopEmission obj \"delete_text\"\n\n-- | Emitted when a piece of text is inserted into the 'Editable' widget.\n--\n-- * The connected signal receives the text that is inserted, together with\n-- the position in the entry widget. The return value should be the position\n-- in the entry widget that lies past the recently inserted text (i.e.\n-- you should return the given position plus the length of the string).\n--\n-- * To modify the text that the user inserts, you need to connect to this\n-- signal, modify the text the way you want and then call\n-- 'editableInsertText'. To avoid that this signal handler is called\n-- recursively, you need to temporarily block it using\n-- 'signalBlock'. After the default signal\n-- handler has inserted your modified text, it is important that you\n-- prevent the default handler from being executed again when this signal\n-- handler returns. To stop the current signal, use 'stopInsertText'.\n-- The following code is an example of how to turn all input into uppercase:\n--\n-- > idRef <- newIORef undefined\n-- > id <- onInsertText entry $ \\str pos -> do\n-- > id <- readIORef idRef\n-- > signalBlock id\n-- > pos' <- editableInsertText entry (map toUpper str) pos\n-- > signalUnblock id\n-- > stopInsertText id\n-- > return pos'\n-- > writeIORef idRef id\n--\n-- Note that the 'afterInsertText' function is not very useful, except to\n-- track editing actions.\n--\nonInsertText, afterInsertText :: EditableClass self => self\n -> (String -> Int -> IO Int)\n -> IO (ConnectId self)\nonInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" False obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\nafterInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" True obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\n\n-- | Stop the current signal that inserts text.\nstopInsertText :: EditableClass self => ConnectId self -> IO ()\nstopInsertText (ConnectId _ obj) =\n signalStopEmission obj \"insert_text\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Interface Editable\n--\n-- Author : Axel Simon, Duncan Coutts\n--\n-- Created: 30 July 2004\n--\n-- Copyright (C) 1999-2005 Axel Simon, 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-- Interface for text-editing widgets\n--\nmodule Graphics.UI.Gtk.Entry.Editable (\n-- * Detail\n-- \n-- | The 'Editable' interface is an interface which should be implemented by\n-- text editing widgets, such as 'Entry'.\n-- It contains functions for generically manipulating an editable\n-- widget, a large number of action signals used for key bindings, and several\n-- signals that an application can connect to to modify the behavior of a\n-- widget.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | GInterface\n-- | +----Editable\n-- @\n\n-- * Types\n Editable,\n EditableClass,\n castToEditable, gTypeEditable,\n toEditable,\n\n-- * Methods\n editableSelectRegion,\n editableGetSelectionBounds,\n editableInsertText,\n editableDeleteText,\n editableGetChars,\n editableCutClipboard,\n editableCopyClipboard,\n editablePasteClipboard,\n editableDeleteSelection,\n editableSetEditable,\n editableGetEditable,\n editableSetPosition,\n editableGetPosition,\n\n-- * Attributes\n editablePosition,\n editableEditable,\n\n-- * Signals\n onEditableChanged,\n afterEditableChanged,\n onDeleteText,\n afterDeleteText,\n stopDeleteText,\n onInsertText,\n afterInsertText,\n stopInsertText\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Selects a region of text. The characters that are selected are those\n-- characters at positions from @startPos@ up to, but not including @endPos@.\n-- If @endPos@ is negative, then the the characters selected will be those\n-- characters from @startPos@ to the end of the text.\n--\n-- Calling this function with @start@=1 and @end@=4 it will mark \\\"ask\\\" in\n-- the string \\\"Haskell\\\".\n--\neditableSelectRegion :: EditableClass self => self\n -> Int -- ^ @start@ - the starting position.\n -> Int -- ^ @end@ - the end position.\n -> IO ()\neditableSelectRegion self start end =\n {# call editable_select_region #}\n (toEditable self)\n (fromIntegral start)\n (fromIntegral end)\n\n-- | Gets the current selection bounds, if there is a selection.\n--\neditableGetSelectionBounds :: EditableClass self => self\n -> IO (Int,Int) -- ^ @(start, end)@ - the starting and end positions. This\n -- pair is not ordered. The @end@ index represents the\n -- position of the cursor. The @start@ index is the other end\n -- of the selection. If both numbers are equal there is in\n -- fact no selection.\neditableGetSelectionBounds self =\n alloca $ \\startPtr ->\n alloca $ \\endPtr -> do\n {# call unsafe editable_get_selection_bounds #}\n (toEditable self)\n startPtr\n endPtr\n start <- liftM fromIntegral $ peek startPtr\n end <- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- | Inserts text at a given position.\n--\neditableInsertText :: EditableClass self => self\n -> String -- ^ @newText@ - the text to insert.\n -> Int -- ^ @position@ - the position at which to insert the text.\n -> IO Int -- ^ returns the position after the newly inserted text.\neditableInsertText self newText position = \n with (fromIntegral position) $ \\positionPtr ->\n withUTFStringLen newText $ \\(newTextPtr, newTextLength) -> do\n {# call editable_insert_text #}\n (toEditable self)\n newTextPtr\n (fromIntegral newTextLength)\n positionPtr\n position <- peek positionPtr\n return (fromIntegral position)\n\n-- | Deletes a sequence of characters. The characters that are deleted are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters deleted will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableDeleteText :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO ()\neditableDeleteText self startPos endPos =\n {# call editable_delete_text #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n\n-- | Retrieves a sequence of characters. The characters that are retrieved are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters retrieved will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableGetChars :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO String -- ^ returns the characters in the indicated region.\neditableGetChars self startPos endPos =\n {# call unsafe editable_get_chars #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n >>= readUTFString\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard and then deleted from the widget.\n--\neditableCutClipboard :: EditableClass self => self -> IO ()\neditableCutClipboard self =\n {# call editable_cut_clipboard #}\n (toEditable self)\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard.\n--\neditableCopyClipboard :: EditableClass self => self -> IO ()\neditableCopyClipboard self =\n {# call editable_copy_clipboard #}\n (toEditable self)\n\n-- | Causes the contents of the clipboard to be pasted into the given widget\n-- at the current cursor position.\n--\neditablePasteClipboard :: EditableClass self => self -> IO ()\neditablePasteClipboard self =\n {# call editable_paste_clipboard #}\n (toEditable self)\n\n-- | Deletes the current contents of the widgets selection and disclaims the\n-- selection.\n--\neditableDeleteSelection :: EditableClass self => self -> IO ()\neditableDeleteSelection self =\n {# call editable_delete_selection #}\n (toEditable self)\n\n-- | Sets the cursor position.\n--\neditableSetPosition :: EditableClass self => self\n -> Int -- ^ @position@ - the position of the cursor. The cursor is\n -- displayed before the character with the given (base 0) index in\n -- the widget. The value must be less than or equal to the number of\n -- characters in the widget. A value of -1 indicates that the\n -- position should be set after the last character in the entry.\n -> IO ()\neditableSetPosition self position =\n {# call editable_set_position #}\n (toEditable self)\n (fromIntegral position)\n\n-- | Retrieves the current cursor position.\n--\neditableGetPosition :: EditableClass self => self\n -> IO Int -- ^ returns the position of the cursor. The cursor is displayed\n -- before the character with the given (base 0) index in the widget.\n -- The value will be less than or equal to the number of characters\n -- in the widget. Note that this position is in characters, not in\n -- bytes.\neditableGetPosition self =\n liftM fromIntegral $\n {# call unsafe editable_get_position #}\n (toEditable self)\n\n-- | Determines if the user can edit the text in the editable widget or not.\n--\neditableSetEditable :: EditableClass self => self\n -> Bool -- ^ @isEditable@ - @True@ if the user is allowed to edit the text\n -- in the widget.\n -> IO ()\neditableSetEditable self isEditable =\n {# call editable_set_editable #}\n (toEditable self)\n (fromBool isEditable)\n\n-- | Retrieves whether the text is editable. See 'editableSetEditable'.\n--\neditableGetEditable :: EditableClass self => self -> IO Bool\neditableGetEditable self =\n liftM toBool $\n {# call editable_get_editable #}\n (toEditable self)\n\n--------------------\n-- Attributes\n\n-- | \\'position\\' property. See 'editableGetPosition' and\n-- 'editableSetPosition'\n--\neditablePosition :: EditableClass self => Attr self Int\neditablePosition = newAttr\n editableGetPosition\n editableSetPosition\n\n-- | \\'editable\\' property. See 'editableGetEditable' and\n-- 'editableSetEditable'\n--\neditableEditable :: EditableClass self => Attr self Bool\neditableEditable = newAttr\n editableGetEditable\n editableSetEditable\n\n--------------------\n-- Signals\n\n-- | Emitted when the settings of the 'Editable' widget changes.\n--\nonEditableChanged, afterEditableChanged :: EditableClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEditableChanged = connect_NONE__NONE \"changed\" False\nafterEditableChanged = connect_NONE__NONE \"changed\" True\n\n-- | Emitted when a piece of text is deleted from the 'Editable' widget.\n--\n-- * See 'onInsertText' for information on how to use this signal.\n--\nonDeleteText, afterDeleteText :: EditableClass self => self\n -> (Int -> Int -> IO ()) -- ^ @(\\startPos endPos -> ...)@\n -> IO (ConnectId self)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- | Stop the current signal that deletes text.\nstopDeleteText :: EditableClass self => ConnectId self -> IO ()\nstopDeleteText (ConnectId _ obj) =\n signalStopEmission obj \"delete_text\"\n\n-- | Emitted when a piece of text is inserted into the 'Editable' widget.\n--\n-- * The connected signal receives the text that is inserted, together with\n-- the position in the entry widget. The return value should be the position\n-- in the entry widget that lies past the recently inserted text (i.e.\n-- you should return the given position plus the length of the string).\n--\n-- * To modify the text that the user inserts, you need to connect to this\n-- signal, modify the text the way you want and then call\n-- 'editableInsertText'. To avoid that this signal handler is called\n-- recursively, you need to temporarily block it using\n-- 'signalBlock'. After the default signal\n-- handler has inserted your modified text, it is important that you\n-- prevent the default handler from being executed again when this signal\n-- handler returns. To stop the current signal, use 'stopInsertText'.\n-- The following code is an example of how to turn all input into uppercase:\n--\n-- > idRef <- newIORef undefined\n-- > id <- onInsertText entry $ \\str pos -> do\n-- > id <- readIORef idRef\n-- > signalBlock id\n-- > pos' <- editableInsertText entry (map toUpper str) pos\n-- > signalUnblock id\n-- > stopInsertText id\n-- > return pos'\n-- > writeIORef idRef id\n--\n-- Note that the 'afterInsertText' function is not very useful, except to\n-- track editing actions.\n--\nonInsertText, afterInsertText :: EditableClass self => self\n -> (String -> Int -> IO Int)\n -> IO (ConnectId self)\nonInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" False obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\nafterInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" True obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\n\n-- | Stop the current signal that inserts text.\nstopInsertText :: EditableClass self => ConnectId self -> IO ()\nstopInsertText (ConnectId _ obj) =\n signalStopEmission obj \"insert_text\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f46006017026b77af7fcbe86479799ad0295825d","subject":"gstreamer: document M.S.G.Core.Clock","message":"gstreamer: document M.S.G.Core.Clock\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-- | 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","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.Clock (\n \n Clock,\n ClockClass,\n castToClock,\n toClock,\n \n ClockTime,\n clockTimeNone,\n clockTimeIsValid,\n second,\n msecond,\n usecond,\n nsecond,\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID,\n \n ClockFlags(..),\n clockGetFlags,\n clockSetFlags,\n clockUnsetFlags,\n \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 clockTimeout,\n clockWindowSize,\n clockWindowThreshold\n \n ) where\n\nimport Data.Ratio ( Ratio\n , (%)\n , numerator\n , denominator )\nimport Control.Monad (liftM, 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\nclockGetFlags :: ClockClass clockT\n => clockT\n -> IO [ClockFlags]\nclockGetFlags = mkObjectGetFlags\n\nclockSetFlags :: ClockClass clockT\n => clockT\n -> [ClockFlags]\n -> IO ()\nclockSetFlags = mkObjectSetFlags\n\nclockUnsetFlags :: ClockClass clockT\n => clockT\n -> [ClockFlags]\n -> IO ()\nclockUnsetFlags = mkObjectUnsetFlags\n\nclockTimeIsValid :: ClockTime\n -> Bool\nclockTimeIsValid = (\/= clockTimeNone)\n\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\nclockSetMaster :: (ClockClass clock, ClockClass master)\n => clock\n -> master\n -> IO Bool\nclockSetMaster clock master =\n liftM toBool $ {# call clock_set_master #} (toClock clock) (toClock master)\n\nclockGetMaster :: ClockClass clock\n => clock\n -> IO (Maybe Clock)\nclockGetMaster clock =\n {# call clock_get_master #} (toClock clock) >>= maybePeek takeObject\n\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\nclockGetResolution :: ClockClass clock\n => clock\n -> IO ClockTime\nclockGetResolution clock =\n liftM fromIntegral $\n {# call clock_get_resolution #} (toClock clock)\n\nclockGetTime :: ClockClass clock\n => clock\n -> IO ClockTime\nclockGetTime clock =\n liftM fromIntegral $\n {# call clock_get_time #} (toClock clock)\n\nclockNewSingleShotID :: ClockClass clock\n => clock\n -> ClockTime\n -> IO ClockID\nclockNewSingleShotID clock time =\n {# call clock_new_single_shot_id #} (toClock clock)\n (fromIntegral time) >>=\n takeClockID . castPtr\n\nclockNewPeriodicID :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> IO ClockID\nclockNewPeriodicID clock startTime interval =\n {# call clock_new_periodic_id #} (toClock clock)\n (fromIntegral startTime)\n (fromIntegral interval) >>=\n takeClockID . castPtr\n\nclockGetInternalTime :: ClockClass clock\n => clock\n -> IO ClockTime\nclockGetInternalTime clock =\n liftM fromIntegral $\n {# call clock_get_internal_time #} (toClock clock)\n\nclockGetCalibration :: ClockClass clock\n => clock\n -> IO (ClockTime, ClockTime, Ratio ClockTime)\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\nclockSetCalibration :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> Ratio ClockTime\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\nclockIDGetTime :: ClockID\n -> IO ClockTime\nclockIDGetTime clockID =\n liftM fromIntegral $ withClockID clockID $\n {# call clock_id_get_time #} . castPtr\n\nclockIDWait :: ClockID\n -> IO (ClockReturn, ClockTimeDiff)\nclockIDWait clockID =\n alloca $ \\jitterPtr ->\n do result <- withClockID clockID $ \\clockIDPtr ->\n {# call clock_id_wait #} (castPtr clockIDPtr) jitterPtr\n jitter <- peek jitterPtr\n return $ (cToEnum result, fromIntegral jitter)\n\nclockIDUnschedule :: 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":"2488c0486642a8f97ada96c1b55b9463cf3d469c","subject":"gstreamer: document & implement missing API for M.S.G.Core.ElementFactory","message":"gstreamer: document & implement missing API for M.S.G.Core.ElementFactory\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte","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\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","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.ElementFactory (\n \n ElementFactory,\n ElementFactoryClass,\n castToElementFactory,\n toElementFactory,\n \n elementFactoryFind,\n elementFactoryGetElementType,\n elementFactoryGetLongname,\n elementFactoryGetKlass,\n elementFactoryGetDescription,\n elementFactoryGetAuthor,\n elementFactoryGetNumPadTemplates,\n elementFactoryGetURIType,\n elementFactoryGetURIProtocols,\n elementFactoryCreate,\n elementFactoryMake\n \n ) where\n\nimport Control.Monad ( liftM )\nimport System.Glib.FFI\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString\n , peekUTFStringArray0 )\nimport System.Glib.GType ( GType )\n{# import Media.Streaming.GStreamer.Core.Types #}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementFactoryFind :: String\n -> IO ElementFactory\nelementFactoryFind name =\n withUTFString name {# call element_factory_find #} >>= takeObject\n\nelementFactoryGetElementType :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO (Maybe GType)\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\nelementFactoryGetLongname :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetLongname factory =\n {# call element_factory_get_longname #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetKlass :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetKlass factory =\n {# call element_factory_get_klass #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetDescription :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetDescription factory =\n {# call element_factory_get_description #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetAuthor :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetAuthor factory =\n {# call element_factory_get_author #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetNumPadTemplates :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO Word\nelementFactoryGetNumPadTemplates factory =\n liftM fromIntegral $\n {# call element_factory_get_num_pad_templates #} $ toElementFactory factory\n\nelementFactoryGetURIType :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO Word\nelementFactoryGetURIType factory =\n liftM fromIntegral $\n {# call element_factory_get_uri_type #} $ toElementFactory factory\n\nelementFactoryGetURIProtocols :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO (Maybe [String])\nelementFactoryGetURIProtocols factory =\n {# call element_factory_get_uri_protocols #} (toElementFactory factory) >>=\n maybePeek peekUTFStringArray0\n\nelementFactoryCreate :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> String\n -> IO (Maybe Element)\nelementFactoryCreate factory name =\n withUTFString name $ \\cName ->\n {# call element_factory_create #} (toElementFactory factory) cName >>=\n maybePeek takeObject\n\nelementFactoryMake :: String\n -> String\n -> IO (Maybe Element)\nelementFactoryMake factoryName name =\n withUTFString factoryName $ \\cFactoryName ->\n withUTFString name $ \\cName ->\n {# call element_factory_make #} cFactoryName cName >>=\n maybePeek takeObject\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"22b703c9b57223b233b08c33afc9676b3cac0060","subject":"MINOR: sc_copy_context Does Not Call Back","message":"MINOR: sc_copy_context Does Not Call Back\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(..), CUInt(..), 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\n-- | Copied from bytestring-0.10.2.0 to make this package only depend on\n-- bytestring-0.10.0.0.\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\n-- | 'CSizeT' corresponds to the platform's 'size_t'\ntype CSizeT = {# type size_t #}\n\nwithByteStringLen :: ByteString -> ((CString, CSizeT) -> 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-- | A shonky encryption key, corresponds to 'shonky_crypt_key_t'\ndata ShonkyCryptKey = ShonkyCryptKey\n { sckKeyStart :: !Word8\n , sckKeyInc :: !Word8\n , sckOnlyAlnum :: !Bool\n } deriving Show\n\n-- Make 'ShonkyCryptKey' storable.\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-- Map C and Haskell type for the encryption keys.\n{#pointer shonky_crypt_key_t as ShonkyCryptKeyPtr -> ShonkyCryptKey #}\n\n-- Get a pointer to the 'sc_release_context' C function.\nforeign import ccall \"shonky-crypt.h &sc_release_context\"\n scReleaseContextPtr :: FunPtr (Ptr ShonkyCryptContext -> IO ())\n\n-- Free 'ShonkyCryptKey's with 'scReleaseContextPtr'\nnewShonkyCryptContextPointer :: Ptr ShonkyCryptContext -> IO ShonkyCryptContext\nnewShonkyCryptContextPointer p =\n do fp <- newForeignPtr scReleaseContextPtr p\n return $! ShonkyCryptContext fp\n\n-- | 'with' renamed because of c2hs parser\nwithTrickC2HS :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithTrickC2HS = with\n\nwithShonkyCryptContext :: ShonkyCryptContext -> (Ptr ShonkyCryptContext -> IO b) -> IO b\n{#pointer shonky_crypt_context_t as ShonkyCryptContext foreign newtype #}\n\n{#fun pure unsafe sc_alloc_context_with_key as\n ^ { withTrickC2HS *`ShonkyCryptKey' }\n -> `ShonkyCryptContext' newShonkyCryptContextPointer * #}\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 -> CSizeT -> IO ()\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 unsafe 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 #}\n\ndecryptS :: ShonkyCryptContext -> ByteString -> (ByteString, ShonkyCryptContext)\ndecryptS = scEnDeCryptInplace {#call unsafe sc_decrypt_inplace #}\n\ntype NewEnDeCryptFun =\n Ptr ShonkyCryptKey -> Ptr CChar -> CSizeT -> IO CString\n\nfromMallocedStorable :: Storable a => Ptr a -> IO a\nfromMallocedStorable p =\n do key <- peek p\n free p\n return key\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(..), CUInt(..), 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\n-- | Copied from bytestring-0.10.2.0 to make this package only depend on\n-- bytestring-0.10.0.0.\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\n-- | 'CSizeT' corresponds to the platform's 'size_t'\ntype CSizeT = {# type size_t #}\n\nwithByteStringLen :: ByteString -> ((CString, CSizeT) -> 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-- | A shonky encryption key, corresponds to 'shonky_crypt_key_t'\ndata ShonkyCryptKey = ShonkyCryptKey\n { sckKeyStart :: !Word8\n , sckKeyInc :: !Word8\n , sckOnlyAlnum :: !Bool\n } deriving Show\n\n-- Make 'ShonkyCryptKey' storable.\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-- Map C and Haskell type for the encryption keys.\n{#pointer shonky_crypt_key_t as ShonkyCryptKeyPtr -> ShonkyCryptKey #}\n\n-- Get a pointer to the 'sc_release_context' C function.\nforeign import ccall \"shonky-crypt.h &sc_release_context\"\n scReleaseContextPtr :: FunPtr (Ptr ShonkyCryptContext -> IO ())\n\n-- Free 'ShonkyCryptKey's with 'scReleaseContextPtr'\nnewShonkyCryptContextPointer :: Ptr ShonkyCryptContext -> IO ShonkyCryptContext\nnewShonkyCryptContextPointer p =\n do fp <- newForeignPtr scReleaseContextPtr p\n return $! ShonkyCryptContext fp\n\n-- | 'with' renamed because of c2hs parser\nwithTrickC2HS :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithTrickC2HS = with\n\nwithShonkyCryptContext :: ShonkyCryptContext -> (Ptr ShonkyCryptContext -> IO b) -> IO b\n{#pointer shonky_crypt_context_t as ShonkyCryptContext foreign newtype #}\n\n{#fun pure unsafe sc_alloc_context_with_key as\n ^ { withTrickC2HS *`ShonkyCryptKey' }\n -> `ShonkyCryptContext' newShonkyCryptContextPointer * #}\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 -> CSizeT -> IO ()\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 #}\n\ndecryptS :: ShonkyCryptContext -> ByteString -> (ByteString, ShonkyCryptContext)\ndecryptS = scEnDeCryptInplace {#call unsafe sc_decrypt_inplace #}\n\ntype NewEnDeCryptFun =\n Ptr ShonkyCryptKey -> Ptr CChar -> CSizeT -> IO CString\n\nfromMallocedStorable :: Storable a => Ptr a -> IO a\nfromMallocedStorable p =\n do key <- peek p\n free p\n return key\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":"fff2baa8020c55b4022779ec2a3de39340a9b8be","subject":"gio: S.G.AsyncResult: specify module exports","message":"gio: S.G.AsyncResult: specify module exports\n\ndarcs-hash:20081017163845-21862-9355813b9cfffba2bd0c953007eb7d87eb5748b6.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gio\/System\/GIO\/AsyncResult.chs","new_file":"gio\/System\/GIO\/AsyncResult.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.AsyncResult (\n AsyncResult,\n AsyncResultClass,\n AsyncReadyCallback\n ) where\n\nimport System.Glib.FFI\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\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-- 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.AsyncResult where\n\nimport System.Glib.FFI\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"dc60e54bea22059a0c534a72aa4f8ef53ebab9d7","subject":"gstreamer: M.S.G.Core.Bus documentation cleanup","message":"gstreamer: M.S.G.Core.Bus documentation cleanup\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"58ba1b74297a25c9adb00f47a368f808dc0f56b7","subject":"Use the #fun feature of c2hs","message":"Use the #fun feature of c2hs\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Bindings\/MPI\/Internal.chs","new_file":"src\/Bindings\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n#include \"constants.h\"\n\nmodule Bindings.MPI.Internal (init, finalize, send, recv, Comm, Datatype, commWorld, int) where\n\nimport Prelude hiding (init)\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\ntype Datatype = {# type MPI_Datatype #}\n\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_int\" int :: Datatype\n\ninit = {# call unsafe init_wrapper as ^ #}\n\n-- int MPI_Finalize(void)\nfinalize = {# call unsafe MPI_Finalize as ^ #}\n\n-- int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)\n-- send = {# call unsafe MPI_Send as ^ #}\n{# fun unsafe Send as ^ { id `Ptr ()', `Int', id `Datatype', `Int', `Int', id `Comm' } -> `Int' #}\n\n-- int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)\nrecv = {# call unsafe MPI_Recv as ^ #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n#include \"constants.h\"\n\nmodule Bindings.MPI.Internal (init, finalize, send, recv, Comm, Datatype, commWorld, int) where\n\nimport Prelude hiding (init)\nimport C2HS\n\ntype Comm = {# type MPI_Comm #}\ntype Datatype = {# type MPI_Datatype #}\n\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_int\" int :: Datatype\n\ninit = {# call init_wrapper as ^ #}\n\n-- int MPI_Finalize(void)\nfinalize = {# call MPI_Finalize as ^ #}\n\n-- int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)\nsend = {# call MPI_Send as ^ #}\n\n-- int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)\nrecv = {# call MPI_Recv as ^ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"46451ef39372ab5590d4fd787570856f525c89aa","subject":"implement more detailed signature verification","message":"implement more detailed signature verification\n","repos":"pontarius\/pontarius-gpg,Philonous\/pontarius-gpg","old_file":"src\/Bindings.chs","new_file":"src\/Bindings.chs","new_contents":"-- | Bindings to GPGMe\n--\n-- partial bindings to gpgme\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE OverloadedStrings #-}\n\n#include \n#include \n\nmodule Bindings where\n\nimport Control.Applicative ((<$>), (<*>))\nimport qualified Control.Exception as Ex\nimport Data.Bits\nimport qualified Data.ByteString as BS\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Unsafe as BS\nimport Data.Data\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.Foreign as Text\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport System.Posix.IO\nimport System.Posix.Types\n\nfromEnum' :: (Enum a, Num b) => a -> b\nfromEnum' = fromIntegral . fromEnum\n\ntoEnum' :: (Enum c, Integral a) => a -> c\ntoEnum' = toEnum . fromIntegral\n\nfromFlags :: (Enum a, Num b, Data.Bits.Bits b) => [a] -> b\nfromFlags = foldr (.|.) 0 . map fromEnum'\n\ntoFlags :: (Data.Bits.Bits a, Eq a, Num a, Enum b, Bounded b) =>\n a\n -> [b]\ntoFlags x = filter (\\y -> let y' = fromEnum' y in x .&. y' \/= 0)\n [minBound..maxBound]\n\n{#context lib = \"gpgme\" prefix = \"gpgme\" #}\n\n{#pointer gpgme_ctx_t as Ctx foreign newtype#}\n\ninstance Show Ctx where\n show _ = \"\"\n\n{#enum gpgme_err_code_t as ErrorCode {underscoreToCase}\n with prefix = \"GPG\"\n deriving (Show) #}\n\n{#enum gpgme_err_source_t as ErrorSource {underscoreToCase}\n with prefix = \"GPG\"\n\n deriving (Show) #}\n\ndata Error = Error { errCode :: ErrorCode\n , errSource :: ErrorSource\n , errorString :: Text.Text\n } deriving (Show, Typeable )\n\nnoError :: Error\nnoError = Error ErrNoError ErrSourceUnknown \"\"\n\ninstance Ex.Exception Error\n\nthrowError :: CUInt -> IO ()\nthrowError e' = do\n mbe <- toError e'\n case mbe of\n Nothing -> return ()\n Just e -> Ex.throwIO e\n\n#c\ngpgme_err_code_t gpgme_err_code_uninlined (gpgme_error_t err);\ngpgme_err_source_t gpgme_err_source_uninlined (gpgme_error_t err);\n#endc\n\ntoError :: CUInt -> IO (Maybe Error)\ntoError err = case err of\n 0 -> return Nothing\n _ -> Just <$>\n (allocaBytes 256 $ \\buff -> do -- We hope that any error message will\n -- be less than 256 bytes long\n _ <- {#call strerror_r#} err buff 256\n Error <$> (toEnum . fromIntegral\n <$> {# call err_code_uninlined #} err)\n <*> (toEnum . fromIntegral\n <$> {# call err_source_uninlined #} err)\n <*> (Text.pack <$> peekCString buff))\n\ncheckVersion :: Maybe Text -> IO (Maybe Text)\ncheckVersion Nothing = Just . Text.pack <$>\n (peekCString =<< {#call check_version#} nullPtr)\ncheckVersion (Just txt) = withCString (Text.unpack txt) $ \\buf -> do\n _ <- {#call check_version#} buf\n return Nothing\n\n\n{#enum gpgme_protocol_t as Protocol {underscoreToCase} deriving (Show, Eq)#}\n-- gpgme_engine_check_version (gpgme_protocol_t protocol)\n\nforeign import ccall unsafe \"&gpgme_release\"\n releaseCtx :: FunPtr (Ptr Ctx -> IO ())\n\nmkContext :: Ptr (Ptr Ctx) -> IO Ctx\nmkContext p = do\n if p == nullPtr\n then Ex.throw (Ex.AssertionFailed \"nullPtr\")\n else fmap Ctx $ newForeignPtr releaseCtx . castPtr =<< peek p\n\n\n-- withCtx :: Ctx -> (Ptr Ctx -> IO t) -> IO t\n-- withCtx x f = withForeignPtr (fromCtx x) f\n\n{#fun new as ctxNew'\n {alloca- `Ctx' mkContext*}\n -> `()' throwError*- #}\n\n-- | Check that version constraint is satisfied and create a new context\nctxNew :: Maybe Text -> IO Ctx\nctxNew minVersion = do\n _ <- checkVersion minVersion\n ctxNew'\n\n\n{#enum validity_t as Validity {underscoreToCase} deriving (Show) #}\n{#enum attr_t as Attr {underscoreToCase} deriving (Show) #}\n\n------------------------------------\n-- Keys\n------------------------------------\n\n{#pointer gpgme_key_t as Key foreign newtype #}\n\nwithKeysArray :: [Key] -> (Ptr (Ptr Key) -> IO b) -> IO b\nwithKeysArray ks' f = withKeys ks' $ \\ksPtrs -> withArray0 nullPtr ksPtrs f\n where\n withKeys [] g = g []\n withKeys (k:ks) g = withKey k $ \\kPtr -> withKeys ks (g . (kPtr:))\n\nforeign import ccall \"gpgme.h &gpgme_key_unref\"\n unrefPtr :: FunPtr (Ptr Key -> IO ())\n\ngetKeys :: Ctx\n -> Bool -- ^ Only keys with secret\n -> IO [Key]\ngetKeys ctx secretOnly = withCtx ctx $ \\ctxPtr -> do\n _ <- {#call gpgme_op_keylist_start #} ctxPtr nullPtr (fromEnum' secretOnly)\n alloca $ takeKeys ctxPtr\n where\n takeKeys ctxPtr (buf :: Ptr (Ptr Key)) = do\n err <- toError =<< {#call gpgme_op_keylist_next#} ctxPtr buf\n case err of\n Nothing -> do\n keyPtr <- peek buf\n key <- newForeignPtr unrefPtr keyPtr\n (Key key :) <$> takeKeys ctxPtr buf\n Just e -> case errCode e of\n ErrEof -> return []\n _ -> error \"takeKeys\"\n\nreserved :: (Ptr a -> t) -> t\nreserved f = f nullPtr\n\nreserved0 :: Num a => (a -> t) -> t\nreserved0 f = f 0\n\n{#fun key_get_string_attr as ^\n { withKey* `Key'\n , fromEnum' `Attr'\n , reserved- `Ptr()'\n , `Int'\n } -> `Maybe BS.ByteString' toMaybeText* #}\n\n-------------------------------\n-- Data Buffers\n-------------------------------\n\nnewtype DataBuffer = DataBuffer {fromDataBuffer :: Ptr ()}\nmkDataBuffer :: Ptr (Ptr ()) -> IO DataBuffer\nmkDataBuffer = fmap DataBuffer . peek\n\nwithDataBuffer :: DataBuffer -> (Ptr () -> t) -> t\nwithDataBuffer (DataBuffer buf) f = f buf\n\ntoMaybeText :: Ptr CChar -> IO (Maybe BS.ByteString)\ntoMaybeText ptr = maybePeek BS.packCString ptr\n\nwithMaybeText :: Maybe Text -> (Ptr CChar -> IO a) -> IO a\nwithMaybeText Nothing = ($ nullPtr)\nwithMaybeText (Just txt) = withCString (Text.unpack txt)\n\n\n\n{#fun data_new as ^\n { alloca- `DataBuffer' mkDataBuffer* }\n -> `()' throwError*- #}\n\npeekInt :: (Storable a, Num b, Integral a) => Ptr a -> IO b\npeekInt = fmap fromIntegral . peek\n\n{#fun data_release_and_get_mem as ^\n { fromDataBuffer `DataBuffer'\n , alloca- `Int' peekInt*\n } -> `Ptr ()' castPtr #}\n\ngetDataBufferBytes :: DataBuffer -> IO BS.ByteString\ngetDataBufferBytes db = do\n (dt, len) <- dataReleaseAndGetMem db\n res <- if dt == nullPtr then return BS.empty\n else do\n bs <- BS.packCStringLen (castPtr dt, len)\n {#call free#} dt\n return bs\n return res\n\n{# fun gpgme_op_export_keys as opExportKeys\n { withCtx* `Ctx'\n , withKeysArray* `[Key]'\n , reserved0- `CUInt'\n , fromDataBuffer `DataBuffer'\n } -> `Error' throwError*- #}\n\ndata ImportStatus = ImportStatus { isFprint :: BS.ByteString\n , isResult :: Maybe Error\n , isStatus :: Int -- TODO: convert to flags\n } deriving (Show)\n\nimportKeyBuffer :: Ctx -> DataBuffer -> IO [ImportStatus]\nimportKeyBuffer ctx keyBuffer = withCtx ctx $ \\ctxPtr ->\n withDataBuffer keyBuffer $ \\keyPtr -> do\n throwError =<< {#call op_import#} ctxPtr keyPtr\n result <- {#call op_import_result #} ctxPtr\n walkImports =<< {#get import_result_t.imports#} result\n where\n walkImports p = if p == nullPtr\n then return []\n else do\n is <- ImportStatus <$> (BS.packCString\n =<< {#get import_status_t.fpr #} p)\n <*> (toError =<< {#get import_status_t.result #} p)\n <*> (fromIntegral <$> {#get import_status_t.status #} p)\n (is:) <$> (walkImports =<< {#get import_status_t.next #} p)\n\n\nimportKeys :: Ctx -> ByteString -> IO [ImportStatus]\nimportKeys ctx bs = withBSData bs $ importKeyBuffer ctx\n\nexportKeys :: Ctx -> [Key] -> IO BS.ByteString\nexportKeys ctx keys = withBSBuffer $ opExportKeys ctx keys\n\nunsafeUseAsCStringLen' :: Num t =>\n BS.ByteString\n -> ((Ptr CChar, t) -> IO a)\n -> IO a\nunsafeUseAsCStringLen' bs f =\n BS.unsafeUseAsCStringLen bs $ \\(bs', l) -> f (bs', fromIntegral l)\n\n{# fun data_new_from_mem as ^\n { alloca- `DataBuffer' mkDataBuffer*\n , unsafeUseAsCStringLen' * `BS.ByteString'&\n , fromEnum' `Bool'\n } -> `Error' throwError*- #}\n\n{# fun data_release as ^\n { withDataBuffer* `DataBuffer'} -> `()' #}\n\n{# fun set_armor as ^\n { withCtx* `Ctx'\n , fromEnum' `Bool'\n } -> `()' #}\n\nwithBSData :: BS.ByteString -> (DataBuffer -> IO c) -> IO c\nwithBSData bs =\n Ex.bracket (dataNewFromMem bs True)\n dataRelease\n\nwithBSBuffer :: (DataBuffer -> IO a) -> IO BS.ByteString\nwithBSBuffer f =\n Ex.bracketOnError dataNew\n dataRelease\n $ \\db -> do\n _ <- f db\n getDataBufferBytes db\n\n\n-----------------------------------\n-- Signing\n-----------------------------------\n\n{#fun signers_clear as ^\n {withCtx* `Ctx'} -> `()'#}\n\n{#fun signers_add as ^\n { withCtx* `Ctx'\n , withKey* `Key'\n } -> `()' throwError* #}\n\n{# enum sig_mode_t as SigMode {underscoreToCase}\n with prefix = \"GPGME\"\n deriving (Show) #}\n\n{#fun op_sign as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer'\n , withDataBuffer* `DataBuffer'\n , fromEnum' `SigMode'\n } -> `()' throwError*- #}\n-- exportKey\n\n-- | Sign a text using a private signing key from the GPG keychain\nsign :: Ctx\n -> BS.ByteString -- ^ Text to sign\n -> Key -- ^ Signing key to use\n -> SigMode -- ^ Signing mode\n -> IO BS.ByteString\nsign ctx plain key mode = withBSData plain $ \\plainData ->\n withBSBuffer $ \\outData -> (do\n signersClear ctx\n signersAdd ctx key\n opSign ctx plainData outData mode)\n `Ex.finally` signersClear ctx\n\n{# enum sigsum_t as SigSummary {underscoreToCase} deriving (Bounded, Show)#}\n{# enum sig_stat_t as SigStat {underscoreToCase} deriving (Bounded, Show)#}\n\n{#fun op_verify as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer' -- sig\n , withDataBuffer* `DataBuffer' -- signed-text\n , withDataBuffer* `DataBuffer' -- plain\n } -> `()' throwError*- #}\n\n\ndata VerifyResult = VerifyResult { summary :: [SigSummary]\n , fingerprint :: ByteString\n , status :: SigStat\n , timestamp :: Integer\n , expTimestamp :: Integer\n , wrongKeyUsage :: Bool\n , pkaTrust :: Int\n , chainModel :: Bool\n , validity :: Validity\n , validityReason :: ErrorCode\n } deriving Show\n\npeekVerifyResults :: Ptr () -> IO [VerifyResult]\npeekVerifyResults ptr | ptr == nullPtr = return []\n | otherwise = do\n summary <- toFlags <$> {#get gpgme_signature_t->summary#} ptr\n fingerprint <- BS.packCString =<<{# get gpgme_signature_t->fpr#} ptr\n status' <- gpgme_err_code_uninlined =<< {#get gpgme_signature_t->status#} ptr\n let status = case toEnum' status' of\n ErrNoError -> SigStatGood\n ErrBadSignature -> SigStatBad\n ErrNoPubkey -> SigStatNokey\n ErrNoData -> SigStatNosig\n ErrSigExpired -> SigStatGoodExp\n ErrKeyExpired -> SigStatGoodExpkey\n _ -> SigStatError\n timestamp <- fromIntegral <$> {#get gpgme_signature_t->timestamp#} ptr\n expTimestamp <- fromIntegral <$> {#get gpgme_signature_t->exp_timestamp#} ptr\n wrongKeyUsage <- toEnum' <$> {#get gpgme_signature_t->wrong_key_usage#} ptr\n pkaTrust <- fromIntegral <$> {#get gpgme_signature_t->pka_trust#} ptr\n chainModel <- toEnum' <$> {#get gpgme_signature_t->chain_model #} ptr\n validity <- toEnum' <$> {#get gpgme_signature_t->validity #} ptr\n validityReason <- toEnum' <$> {#get gpgme_signature_t->validity_reason#} ptr\n let res = VerifyResult { summary = summary\n , fingerprint = fingerprint\n , status = status\n , timestamp = timestamp\n , expTimestamp = expTimestamp\n , wrongKeyUsage = wrongKeyUsage\n , pkaTrust = pkaTrust\n , chainModel = chainModel\n , validity = validity\n , validityReason = validityReason\n }\n next <- {#get gpgme_signature_t->next #} ptr\n nextResult <- peekVerifyResults next\n return (res : nextResult)\n\nverifyResult :: Ctx -> IO [VerifyResult]\nverifyResult ctx = withCtx ctx $ \\ctxPtr -> do\n res <- {# call gpgme_op_verify_result #} ctxPtr\n peekVerifyResults =<< {#get verify_result_t->signatures#} res\n\n-- | Verify a signature created in 'SigModeDetach' mode\nverifyDetach :: Ctx\n -> BS.ByteString -- ^ The source text that the signature pertains to\n -> BS.ByteString -- ^ The signature\n -> IO [VerifyResult]\nverifyDetach ctx signedText sig = withBSData signedText $ \\stData ->\n withBSData sig $ \\sigData -> do\n opVerify ctx sigData stData (DataBuffer nullPtr)\n verifyResult ctx\n\n-- | Verify a signature created in 'SigModeNormal' or 'SigModeClear' mode\nverify :: Ctx\n -> BS.ByteString -- ^ Text and attached Signature\n -> IO ([VerifyResult], BS.ByteString) -- ^ result and extracted plain text\nverify ctx sig = withBSData sig $ \\sigData -> do\n plain <- withBSBuffer $ \\plainData ->\n opVerify ctx sigData (DataBuffer nullPtr) plainData\n res <- verifyResult ctx\n return (res, plain)\n\n--------------------------------\n-- Passphrases\n--------------------------------\n\n-- gpgme_error_t (*gpgme_passphrase_cb_t)(void *hook, const char *uid_hint, const char *passphrase_info, int prev_was_bad, int fd)\n\ntype PassphraseCallback = Ptr () -- ^ Hook\n -> Ptr CChar -- ^ Uid Hint\n -> Ptr CChar -- ^ passphrase info\n -> CInt -- ^ Was Bad?\n -> CInt -- ^ fd\n -> IO CUInt\n\nforeign import ccall \"wrapper\"\n mkPasswordCallback :: PassphraseCallback -> IO (FunPtr PassphraseCallback)\n\nsetPassphraseCallback :: Ctx\n -> (String -> String -> Bool -> IO String)\n -> IO ()\nsetPassphraseCallback ctx f = do\n let cbFun _ uidHint pInfo bad fd = do\n uidHintString <- peekCString uidHint\n pInfoString <- peekCString pInfo\n out <- f uidHintString pInfoString (bad == 0)\n _ <- fdWrite (Fd fd) (filter (\/= '\\n') out ++ \"\\n\" )\n return 0\n cb <- mkPasswordCallback cbFun\n withCtx ctx $ \\ctxPtr -> {# call set_passphrase_cb #} ctxPtr cb nullPtr\n\ndata Engine = Engine { engineProtocol :: Protocol\n , engineFilename :: Maybe String\n , engineHomeDir :: Maybe String\n , engineVersion :: Maybe String\n , engineReqVersion :: Maybe String\n } deriving (Show)\n\ngetEngines :: Ctx -> IO [Engine]\ngetEngines ctx = withCtx ctx $ \\ctxPtr -> do\n goEngines =<< {#call ctx_get_engine_info #} ctxPtr\n where\n goEngines this = if this == nullPtr\n then return []\n else do\n engine <- Engine <$> (toEnum' <$> {# get engine_info_t.protocol#} this)\n <*> (peekCSM =<< {#get engine_info_t.file_name#} this)\n <*> (peekCSM =<< {#get engine_info_t.home_dir#} this)\n <*> (peekCSM =<< {#get engine_info_t.version#} this)\n <*> (peekCSM =<< {#get engine_info_t.req_version#} this)\n next <- {# get gpgme_engine_info_t.next #} this\n (engine:) <$> goEngines next\n peekCSM cString = if cString == nullPtr\n then return Nothing\n else Just <$> peekCString cString\n\nsetEngine :: Ctx -> Engine -> IO ()\nsetEngine ctx eng = withCtx ctx $ \\ctxPtr->\n withMBCString (engineFilename eng) $ \\fNamePtr ->\n withMBCString (engineHomeDir eng) $ \\hDirPtr ->\n throwError =<< {#call ctx_set_engine_info #} ctxPtr\n (fromEnum' $ engineProtocol eng)\n fNamePtr\n hDirPtr\n where\n withMBCString Nothing f = f nullPtr\n withMBCString (Just str) f = withCString str f\n\n{# enum pinentry_mode_t as PinentryMode {underscoreToCase} #}\n\n{# fun set_pinentry_mode as ^\n { withCtx* `Ctx'\n , fromEnum' `PinentryMode'\n } -> `()' throwError*- #}\n\n-------------------------------------------\n-- Key Creation ---------------------------\n-------------------------------------------\ndata GenKeyResult = GenKeyResult { genKeyhasPrimary :: Bool\n , genKeyhasSubKey :: Bool\n , genKeyFingerprint :: Maybe BS.ByteString\n } deriving (Show)\n\ngenKey :: Ctx -> String -> IO GenKeyResult\ngenKey ctx params = withCtx ctx $ \\ctxPtr ->\n withCString params $ \\paramsPtr -> do\n putStrLn \"starting key genearion\"\n throwError =<< {#call gpgme_op_genkey#} ctxPtr paramsPtr nullPtr nullPtr\n putStrLn \"retrieving result\"\n res <- {#call gpgme_op_genkey_result#} ctxPtr\n putStrLn \"Extracting result data\"\n prim <- toEnum' <$> {#get gpgme_genkey_result_t.primary#} res\n sub <- toEnum' <$> {#get gpgme_genkey_result_t.sub#} res\n fprint <- maybePeek BS.packCString =<< {#get gpgme_genkey_result_t.fpr#} res\n return $ GenKeyResult prim sub fprint\n\n------------------------------------------\n-- Key Deletion --------------------------\n------------------------------------------\n\n{# fun gpgme_op_delete as deleteKey\n { withCtx* `Ctx'\n , withKey* `Key'\n , fromEnum' `Bool'\n } -> `()' throwError*- #}\n\n------------------------------------------\n-- Key Editing ---------------------------\n------------------------------------------\n\n-- gpgme_error_t (*gpgme_edit_cb_t) (void *handle, gpgme_status_code_t status, const char *args, int fd)\n\n{# enum gpgme_status_code_t as StatusCode {underscoreToCase} deriving (Show, Read, Eq, Data, Typeable, Bounded) #}\n\ntype EditCallback' = Ptr () -> CInt -> CString -> CInt -> IO CUInt\ntype EditCallback = StatusCode -> Text -> Fd -> IO Error\n\nforeign import ccall \"wrapper\"\n mkEditCallback :: EditCallback' -> IO (FunPtr EditCallback')\n\n#c\ngpgme_error_t gpgme_err_make_uninlined ( gpgme_err_source_t err_source\n , gpgme_err_code_t err_code);\n#endc\n\n{# fun gpgme_err_make_uninlined as mkError\n { fromEnum' `ErrorSource'\n , fromEnum' `ErrorCode'\n }\n -> `CUInt' id #}\n\neditKey :: Ctx -> Key -> EditCallback -> IO ByteString\neditKey ctx key callback = do\n let callback' _ scInt cStr fdInt = do\n str <- if (cStr == nullPtr) then return \"\" else peekCString cStr\n err <- callback (toEnum $ fromIntegral scInt) (Text.pack str)\n (Fd fdInt)\n mkError (errSource err) (errCode err)\n Ex.bracket (mkEditCallback callback') freeHaskellFunPtr\n $ \\cb ->\n withCtx ctx $ \\ctxPtr ->\n withKey key $ \\keyPtr ->\n withBSBuffer $ \\buffer ->\n withDataBuffer buffer $ \\bufferPtr ->\n throwError =<< {#call gpgme_op_edit#} ctxPtr keyPtr cb nullPtr bufferPtr\n\n-----------------------------------------\n-- Process ------------------------------\n-----------------------------------------\n\n{# fun kill as ^\n { fromIntegral `CPid'\n , fromIntegral `Int'\n } -> `Int' fromIntegral #}\n","old_contents":"-- | Bindings to GPGMe\n--\n-- partial bindings to gpgme\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE OverloadedStrings #-}\n\n#include \n#include \n\nmodule Bindings where\n\nimport Control.Applicative ((<$>), (<*>))\nimport qualified Control.Exception as Ex\nimport Data.Bits\nimport qualified Data.ByteString as BS\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Unsafe as BS\nimport Data.Data\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.Foreign as Text\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport System.Posix.IO\nimport System.Posix.Types\n\nfromEnum' :: (Enum a, Num b) => a -> b\nfromEnum' = fromIntegral . fromEnum\n\ntoEnum' :: (Enum c, Integral a) => a -> c\ntoEnum' = toEnum . fromIntegral\n\nfromFlags :: (Enum a, Num b, Data.Bits.Bits b) => [a] -> b\nfromFlags = foldr (.|.) 0 . map fromEnum'\n\ntoFlags x = filter (\\y -> let y' = fromEnum' y in x .|. y' == y')\n [minBound..maxBound]\n\n{#context lib = \"gpgme\" prefix = \"gpgme\" #}\n\n{#pointer gpgme_ctx_t as Ctx foreign newtype#}\n\ninstance Show Ctx where\n show _ = \"\"\n\n{#enum gpgme_err_code_t as ErrorCode {underscoreToCase}\n with prefix = \"GPG\"\n deriving (Show) #}\n\n{#enum gpgme_err_source_t as ErrorSource {underscoreToCase}\n with prefix = \"GPG\"\n\n deriving (Show) #}\n\ndata Error = Error { errCode :: ErrorCode\n , errSource :: ErrorSource\n , errorString :: Text.Text\n } deriving (Show, Typeable )\n\nnoError :: Error\nnoError = Error ErrNoError ErrSourceUnknown \"\"\n\ninstance Ex.Exception Error\n\nthrowError :: CUInt -> IO ()\nthrowError e' = do\n mbe <- toError e'\n case mbe of\n Nothing -> return ()\n Just e -> Ex.throwIO e\n\n#c\ngpgme_err_code_t gpgme_err_code_uninlined (gpgme_error_t err);\ngpgme_err_source_t gpgme_err_source_uninlined (gpgme_error_t err);\n#endc\n\ntoError :: CUInt -> IO (Maybe Error)\ntoError err = case err of\n 0 -> return Nothing\n _ -> Just <$>\n (allocaBytes 256 $ \\buff -> do -- We hope that any error message will\n -- be less than 256 bytes long\n _ <- {#call strerror_r#} err buff 256\n Error <$> (toEnum . fromIntegral\n <$> {# call err_code_uninlined #} err)\n <*> (toEnum . fromIntegral\n <$> {# call err_source_uninlined #} err)\n <*> (Text.pack <$> peekCString buff))\n\ncheckVersion :: Maybe Text -> IO (Maybe Text)\ncheckVersion Nothing = Just . Text.pack <$>\n (peekCString =<< {#call check_version#} nullPtr)\ncheckVersion (Just txt) = withCString (Text.unpack txt) $ \\buf -> do\n _ <- {#call check_version#} buf\n return Nothing\n\n\n{#enum gpgme_protocol_t as Protocol {underscoreToCase} deriving (Show, Eq)#}\n-- gpgme_engine_check_version (gpgme_protocol_t protocol)\n\nforeign import ccall unsafe \"&gpgme_release\"\n releaseCtx :: FunPtr (Ptr Ctx -> IO ())\n\nmkContext :: Ptr (Ptr Ctx) -> IO Ctx\nmkContext p = do\n if p == nullPtr\n then Ex.throw (Ex.AssertionFailed \"nullPtr\")\n else fmap Ctx $ newForeignPtr releaseCtx . castPtr =<< peek p\n\n\n-- withCtx :: Ctx -> (Ptr Ctx -> IO t) -> IO t\n-- withCtx x f = withForeignPtr (fromCtx x) f\n\n{#fun new as ctxNew'\n {alloca- `Ctx' mkContext*}\n -> `()' throwError*- #}\n\n-- | Check that version constraint is satisfied and create a new context\nctxNew :: Maybe Text -> IO Ctx\nctxNew minVersion = do\n _ <- checkVersion minVersion\n ctxNew'\n\n\n{#enum validity_t as Validity {underscoreToCase} deriving (Show) #}\n{#enum attr_t as Attr {underscoreToCase} deriving (Show) #}\n\n------------------------------------\n-- Keys\n------------------------------------\n\n{#pointer gpgme_key_t as Key foreign newtype #}\n\nwithKeysArray :: [Key] -> (Ptr (Ptr Key) -> IO b) -> IO b\nwithKeysArray ks' f = withKeys ks' $ \\ksPtrs -> withArray0 nullPtr ksPtrs f\n where\n withKeys [] g = g []\n withKeys (k:ks) g = withKey k $ \\kPtr -> withKeys ks (g . (kPtr:))\n\nforeign import ccall \"gpgme.h &gpgme_key_unref\"\n unrefPtr :: FunPtr (Ptr Key -> IO ())\n\ngetKeys :: Ctx\n -> Bool -- ^ Only keys with secret\n -> IO [Key]\ngetKeys ctx secretOnly = withCtx ctx $ \\ctxPtr -> do\n _ <- {#call gpgme_op_keylist_start #} ctxPtr nullPtr (fromEnum' secretOnly)\n alloca $ takeKeys ctxPtr\n where\n takeKeys ctxPtr (buf :: Ptr (Ptr Key)) = do\n err <- toError =<< {#call gpgme_op_keylist_next#} ctxPtr buf\n case err of\n Nothing -> do\n keyPtr <- peek buf\n key <- newForeignPtr unrefPtr keyPtr\n (Key key :) <$> takeKeys ctxPtr buf\n Just e -> case errCode e of\n ErrEof -> return []\n _ -> error \"takeKeys\"\n\nreserved :: (Ptr a -> t) -> t\nreserved f = f nullPtr\n\nreserved0 :: Num a => (a -> t) -> t\nreserved0 f = f 0\n\n{#fun key_get_string_attr as ^\n { withKey* `Key'\n , fromEnum' `Attr'\n , reserved- `Ptr()'\n , `Int'\n } -> `Maybe BS.ByteString' toMaybeText* #}\n\n-------------------------------\n-- Data Buffers\n-------------------------------\n\nnewtype DataBuffer = DataBuffer {fromDataBuffer :: Ptr ()}\nmkDataBuffer :: Ptr (Ptr ()) -> IO DataBuffer\nmkDataBuffer = fmap DataBuffer . peek\n\nwithDataBuffer :: DataBuffer -> (Ptr () -> t) -> t\nwithDataBuffer (DataBuffer buf) f = f buf\n\ntoMaybeText :: Ptr CChar -> IO (Maybe BS.ByteString)\ntoMaybeText ptr = maybePeek BS.packCString ptr\n\nwithMaybeText :: Maybe Text -> (Ptr CChar -> IO a) -> IO a\nwithMaybeText Nothing = ($ nullPtr)\nwithMaybeText (Just txt) = withCString (Text.unpack txt)\n\n\n\n{#fun data_new as ^\n { alloca- `DataBuffer' mkDataBuffer* }\n -> `()' throwError*- #}\n\npeekInt :: (Storable a, Num b, Integral a) => Ptr a -> IO b\npeekInt = fmap fromIntegral . peek\n\n{#fun data_release_and_get_mem as ^\n { fromDataBuffer `DataBuffer'\n , alloca- `Int' peekInt*\n } -> `Ptr ()' castPtr #}\n\ngetDataBufferBytes :: DataBuffer -> IO BS.ByteString\ngetDataBufferBytes db = do\n (dt, len) <- dataReleaseAndGetMem db\n res <- if dt == nullPtr then return BS.empty\n else do\n bs <- BS.packCStringLen (castPtr dt, len)\n {#call free#} dt\n return bs\n return res\n\n{# fun gpgme_op_export_keys as opExportKeys\n { withCtx* `Ctx'\n , withKeysArray* `[Key]'\n , reserved0- `CUInt'\n , fromDataBuffer `DataBuffer'\n } -> `Error' throwError*- #}\n\ndata ImportStatus = ImportStatus { isFprint :: BS.ByteString\n , isResult :: Maybe Error\n , isStatus :: Int -- TODO: convert to flags\n } deriving (Show)\n\nimportKeyBuffer :: Ctx -> DataBuffer -> IO [ImportStatus]\nimportKeyBuffer ctx keyBuffer = withCtx ctx $ \\ctxPtr ->\n withDataBuffer keyBuffer $ \\keyPtr -> do\n throwError =<< {#call op_import#} ctxPtr keyPtr\n result <- {#call op_import_result #} ctxPtr\n walkImports =<< {#get import_result_t.imports#} result\n where\n walkImports p = if p == nullPtr\n then return []\n else do\n is <- ImportStatus <$> (BS.packCString\n =<< {#get import_status_t.fpr #} p)\n <*> (toError =<< {#get import_status_t.result #} p)\n <*> (fromIntegral <$> {#get import_status_t.status #} p)\n (is:) <$> (walkImports =<< {#get import_status_t.next #} p)\n\n\nimportKeys :: Ctx -> ByteString -> IO [ImportStatus]\nimportKeys ctx bs = withBSData bs $ importKeyBuffer ctx\n\nexportKeys :: Ctx -> [Key] -> IO BS.ByteString\nexportKeys ctx keys = withBSBuffer $ opExportKeys ctx keys\n\nunsafeUseAsCStringLen' :: Num t =>\n BS.ByteString\n -> ((Ptr CChar, t) -> IO a)\n -> IO a\nunsafeUseAsCStringLen' bs f =\n BS.unsafeUseAsCStringLen bs $ \\(bs', l) -> f (bs', fromIntegral l)\n\n{# fun data_new_from_mem as ^\n { alloca- `DataBuffer' mkDataBuffer*\n , unsafeUseAsCStringLen' * `BS.ByteString'&\n , fromEnum' `Bool'\n } -> `Error' throwError*- #}\n\n{# fun data_release as ^\n { withDataBuffer* `DataBuffer'} -> `()' #}\n\n{# fun set_armor as ^\n { withCtx* `Ctx'\n , fromEnum' `Bool'\n } -> `()' #}\n\nwithBSData :: BS.ByteString -> (DataBuffer -> IO c) -> IO c\nwithBSData bs =\n Ex.bracket (dataNewFromMem bs True)\n dataRelease\n\nwithBSBuffer :: (DataBuffer -> IO a) -> IO BS.ByteString\nwithBSBuffer f =\n Ex.bracketOnError dataNew\n dataRelease\n $ \\db -> do\n _ <- f db\n getDataBufferBytes db\n\n\n-----------------------------------\n-- Signing\n-----------------------------------\n\n{#fun signers_clear as ^\n {withCtx* `Ctx'} -> `()'#}\n\n{#fun signers_add as ^\n { withCtx* `Ctx'\n , withKey* `Key'\n } -> `()' throwError* #}\n\n{# enum sig_mode_t as SigMode {underscoreToCase}\n with prefix = \"GPGME\"\n deriving (Show) #}\n\n{#fun op_sign as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer'\n , withDataBuffer* `DataBuffer'\n , fromEnum' `SigMode'\n } -> `()' throwError*- #}\n-- exportKey\n\n-- | Sign a text using a private signing key from the GPG keychain\nsign :: Ctx\n -> BS.ByteString -- ^ Text to sign\n -> Key -- ^ Signing key to use\n -> SigMode -- ^ Signing mode\n -> IO BS.ByteString\nsign ctx plain key mode = withBSData plain $ \\plainData ->\n withBSBuffer $ \\outData -> (do\n signersClear ctx\n signersAdd ctx key\n opSign ctx plainData outData mode)\n `Ex.finally` signersClear ctx\n\n{# enum sigsum_t as SigSummary {underscoreToCase} deriving (Bounded, Show)#}\n{# enum sig_stat_t as SigStat {underscoreToCase} deriving (Bounded, Show)#}\n\n{#fun op_verify as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer' -- sig\n , withDataBuffer* `DataBuffer' -- signed-text\n , withDataBuffer* `DataBuffer' -- plain\n } -> `()' throwError*- #}\n\ncheckVerifyResult :: Ctx -> IO SigStat\ncheckVerifyResult ctx = withCtx ctx $ \\ctx' -> do\n alloca $ \\sigStatPtr -> do\n res <- {#call get_sig_status#} ctx' 0 sigStatPtr nullPtr\n if (res == nullPtr)\n then return SigStatNosig\n else do\n sigStat <- peek sigStatPtr\n return $! (toEnum' sigStat :: SigStat)\n\n\n-- | Verify a signature created in 'SigModeDetach' mode\nverifyDetach :: Ctx\n -> BS.ByteString -- ^ The source text that the signature pertains to\n -> BS.ByteString -- ^ The signature\n -> IO SigStat\nverifyDetach ctx signedText sig = withBSData signedText $ \\stData ->\n withBSData sig $ \\sigData -> do\n opVerify ctx sigData stData (DataBuffer nullPtr)\n checkVerifyResult ctx\n\n-- | Verify a signature created in 'SigModeNormal' or 'SigModeClear' mode\nverify :: Ctx\n -> BS.ByteString -- ^ Text and attached Signature\n -> IO (SigStat, BS.ByteString) -- ^ result and extracted plain text\nverify ctx sig = withBSData sig $ \\sigData -> do\n plain <- withBSBuffer $ \\plainData ->\n opVerify ctx sigData (DataBuffer nullPtr) plainData\n res <- checkVerifyResult ctx\n return (res, plain)\n\n--------------------------------\n-- Passphrases\n--------------------------------\n\n-- gpgme_error_t (*gpgme_passphrase_cb_t)(void *hook, const char *uid_hint, const char *passphrase_info, int prev_was_bad, int fd)\n\ntype PassphraseCallback = Ptr () -- ^ Hook\n -> Ptr CChar -- ^ Uid Hint\n -> Ptr CChar -- ^ passphrase info\n -> CInt -- ^ Was Bad?\n -> CInt -- ^ fd\n -> IO CUInt\n\nforeign import ccall \"wrapper\"\n mkPasswordCallback :: PassphraseCallback -> IO (FunPtr PassphraseCallback)\n\nsetPassphraseCallback :: Ctx\n -> (String -> String -> Bool -> IO String)\n -> IO ()\nsetPassphraseCallback ctx f = do\n let cbFun _ uidHint pInfo bad fd = do\n uidHintString <- peekCString uidHint\n pInfoString <- peekCString pInfo\n out <- f uidHintString pInfoString (bad == 0)\n _ <- fdWrite (Fd fd) (filter (\/= '\\n') out ++ \"\\n\" )\n return 0\n cb <- mkPasswordCallback cbFun\n withCtx ctx $ \\ctxPtr -> {# call set_passphrase_cb #} ctxPtr cb nullPtr\n\ndata Engine = Engine { engineProtocol :: Protocol\n , engineFilename :: Maybe String\n , engineHomeDir :: Maybe String\n , engineVersion :: Maybe String\n , engineReqVersion :: Maybe String\n } deriving (Show)\n\ngetEngines :: Ctx -> IO [Engine]\ngetEngines ctx = withCtx ctx $ \\ctxPtr -> do\n goEngines =<< {#call ctx_get_engine_info #} ctxPtr\n where\n goEngines this = if this == nullPtr\n then return []\n else do\n engine <- Engine <$> (toEnum' <$> {# get engine_info_t.protocol#} this)\n <*> (peekCSM =<< {#get engine_info_t.file_name#} this)\n <*> (peekCSM =<< {#get engine_info_t.home_dir#} this)\n <*> (peekCSM =<< {#get engine_info_t.version#} this)\n <*> (peekCSM =<< {#get engine_info_t.req_version#} this)\n next <- {# get gpgme_engine_info_t.next #} this\n (engine:) <$> goEngines next\n peekCSM cString = if cString == nullPtr\n then return Nothing\n else Just <$> peekCString cString\n\nsetEngine :: Ctx -> Engine -> IO ()\nsetEngine ctx eng = withCtx ctx $ \\ctxPtr->\n withMBCString (engineFilename eng) $ \\fNamePtr ->\n withMBCString (engineHomeDir eng) $ \\hDirPtr ->\n throwError =<< {#call ctx_set_engine_info #} ctxPtr\n (fromEnum' $ engineProtocol eng)\n fNamePtr\n hDirPtr\n where\n withMBCString Nothing f = f nullPtr\n withMBCString (Just str) f = withCString str f\n\n{# enum pinentry_mode_t as PinentryMode {underscoreToCase} #}\n\n{# fun set_pinentry_mode as ^\n { withCtx* `Ctx'\n , fromEnum' `PinentryMode'\n } -> `()' throwError*- #}\n\n-------------------------------------------\n-- Key Creation ---------------------------\n-------------------------------------------\ndata GenKeyResult = GenKeyResult { genKeyhasPrimary :: Bool\n , genKeyhasSubKey :: Bool\n , genKeyFingerprint :: Maybe BS.ByteString\n } deriving (Show)\n\ngenKey :: Ctx -> String -> IO GenKeyResult\ngenKey ctx params = withCtx ctx $ \\ctxPtr ->\n withCString params $ \\paramsPtr -> do\n putStrLn \"starting key genearion\"\n throwError =<< {#call gpgme_op_genkey#} ctxPtr paramsPtr nullPtr nullPtr\n putStrLn \"retrieving result\"\n res <- {#call gpgme_op_genkey_result#} ctxPtr\n putStrLn \"Extracting result data\"\n prim <- toEnum' <$> {#get gpgme_genkey_result_t.primary#} res\n sub <- toEnum' <$> {#get gpgme_genkey_result_t.sub#} res\n fprint <- maybePeek BS.packCString =<< {#get gpgme_genkey_result_t.fpr#} res\n return $ GenKeyResult prim sub fprint\n\n------------------------------------------\n-- Key Deletion --------------------------\n------------------------------------------\n\n{# fun gpgme_op_delete as deleteKey\n { withCtx* `Ctx'\n , withKey* `Key'\n , fromEnum' `Bool'\n } -> `()' throwError*- #}\n\n------------------------------------------\n-- Key Editing ---------------------------\n------------------------------------------\n\n-- gpgme_error_t (*gpgme_edit_cb_t) (void *handle, gpgme_status_code_t status, const char *args, int fd)\n\n{# enum gpgme_status_code_t as StatusCode {underscoreToCase} deriving (Show, Read, Eq, Data, Typeable, Bounded) #}\n\ntype EditCallback' = Ptr () -> CInt -> CString -> CInt -> IO CUInt\ntype EditCallback = StatusCode -> Text -> Fd -> IO Error\n\nforeign import ccall \"wrapper\"\n mkEditCallback :: EditCallback' -> IO (FunPtr EditCallback')\n\n#c\ngpgme_error_t gpgme_err_make_uninlined ( gpgme_err_source_t err_source\n , gpgme_err_code_t err_code);\n#endc\n\n{# fun gpgme_err_make_uninlined as mkError\n { fromEnum' `ErrorSource'\n , fromEnum' `ErrorCode'\n }\n -> `CUInt' id #}\n\neditKey :: Ctx -> Key -> EditCallback -> IO ByteString\neditKey ctx key callback = do\n let callback' _ scInt cStr fdInt = do\n str <- if (cStr == nullPtr) then return \"\" else peekCString cStr\n err <- callback (toEnum $ fromIntegral scInt) (Text.pack str)\n (Fd fdInt)\n mkError (errSource err) (errCode err)\n Ex.bracket (mkEditCallback callback') freeHaskellFunPtr\n $ \\cb ->\n withCtx ctx $ \\ctxPtr ->\n withKey key $ \\keyPtr ->\n withBSBuffer $ \\buffer ->\n withDataBuffer buffer $ \\bufferPtr ->\n throwError =<< {#call gpgme_op_edit#} ctxPtr keyPtr cb nullPtr bufferPtr\n\n-----------------------------------------\n-- Process ------------------------------\n-----------------------------------------\n\n{# fun kill as ^\n { fromIntegral `CPid'\n , fromIntegral `Int'\n } -> `Int' fromIntegral #}\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"3ba3ad2b122fc32c16009b32eb17460827daa95c","subject":"Fix SourceLanguage.chs docs.","message":"Fix SourceLanguage.chs docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceLanguage (\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguage\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguage \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguage \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguage \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or emtpy if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the mime types or emtpy if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceLanguage (\n SourceLanguage,\n SourceLanguageClass,\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | \n--\nsourceLanguageGetId :: SourceLanguage -> IO String\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | \n--\nsourceLanguageGetName :: SourceLanguage -> IO String\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | \n--\nsourceLanguageGetSection :: SourceLanguage -> IO String\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- |\n--\nsourceLanguageGetHidden :: SourceLanguage -> IO Bool\nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage -> String -> IO String\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- |\n--\nsourceLanguageGetMimeTypes :: SourceLanguage -> IO [String]\nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- |\n--\nsourceLanguageGetGlobs :: SourceLanguage -> IO [String]\nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- |\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- |\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- |\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- |\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f4944d641a64d5b60e3617ba2f23a3e97282505b","subject":"implemented withProgressFun to tidy up createCopy'","message":"implemented withProgressFun to tidy up createCopy'\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\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , Error (..)\n , Geotransform (..)\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 , bandSize\n , readBand\n , writeBand\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.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\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\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\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , Error (..)\n , Geotransform (..)\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 , bandSize\n , readBand\n , writeBand\n , fillBand\n\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Concurrent (newMVar, takeMVar, putMVar, MVar)\nimport Control.Exception (finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\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 wrapProgressFun progressFun >>= \\pFunc ->\n finally \n (do 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 (freeHaskellFunPtr pFunc)\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\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\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":"72e7ed495fb40b405141f63f32e2a474ddd5c1f4","subject":"Add function `widgetGetAllocation` and fix version tag.","message":"Add function `widgetGetAllocation` and fix version tag.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"59b3770ee9de36ce1e0db92bf34a70d2b95246b7","subject":"Update on\/afterEdited to use new TreeIter and to use connect_STRING_STRING__NONE rather than connect_PTR_STRING__NONE. This is a different implementation than the one in ModelView since the latter has a different type too. So this is just an intrim implementation.","message":"Update on\/afterEdited to use new TreeIter\nand to use connect_STRING_STRING__NONE rather than \nconnect_PTR_STRING__NONE. This is a different implementation than the \none in ModelView since the latter has a different type too. So this is \njust an intrim implementation.\n","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CellRendererText.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CellRendererText.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CellRendererText TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.7 $ 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-- A 'CellRenderer' which displays a single-line text.\n--\nmodule Graphics.UI.Gtk.TreeList.CellRendererText (\n-- * Detail\n-- \n-- | This widget derives from 'CellRenderer'. It provides the \n-- possibility to display some text by setting the 'Attribute' \n-- 'cellText' to the column of a 'TreeModel' by means of \n-- 'treeViewAddAttribute' from 'TreeModelColumn'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'CellRenderer'\n-- | +----CellRendererText\n-- | +----'CellRendererCombo'\n-- @\n\n-- * Types\n CellRendererText,\n CellRendererTextClass,\n castToCellRendererText,\n toCellRendererText,\n\n-- * Constructors\n cellRendererTextNew,\n\n-- * Attributes\n cellText,\n cellMarkup,\n cellBackground,\n cellForeground,\n cellEditable,\n\n-- * Signals\n onEdited,\n afterEdited\n ) where\n\nimport Maybe\t(fromMaybe)\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\nimport Graphics.UI.Gtk.General.Structs\t\t(treeIterSize)\nimport Graphics.UI.Gtk.TreeList.CellRenderer\t(Attribute(..))\nimport System.Glib.StoreValue\t\t\t(GenericValue(..), TMType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new CellRendererText object.\n--\ncellRendererTextNew :: IO CellRendererText\ncellRendererTextNew =\n makeNewObject mkCellRendererText $\n liftM (castPtr :: Ptr CellRenderer -> Ptr CellRendererText) $\n {# call unsafe cell_renderer_text_new #}\n\n-- helper function\n--\nstrAttr :: [String] -> Attribute CellRendererText String\nstrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring . Just)\n\t\t(\\[GVstring str] -> return (fromMaybe \"\" str))\n\nmStrAttr :: [String] -> Attribute CellRendererText (Maybe String)\nmStrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring)\n\t\t(\\[GVstring str] -> return str)\n\n--------------------\n-- Properties\n\n-- | Define the attribute that specifies the text to be\n-- rendered.\n--\ncellText :: Attribute CellRendererText String\ncellText = strAttr [\"text\"]\n\n-- | Define a markup string instead of a text.\n--\ncellMarkup :: Attribute CellRendererText String\ncellMarkup = strAttr [\"markup\"]\n\n-- | A named color for the background paint.\n--\ncellBackground :: Attribute CellRendererText (Maybe String)\ncellBackground = mStrAttr [\"background\"]\n\n-- | A named color for the foreground paint.\n--\ncellForeground :: Attribute CellRendererText (Maybe String)\ncellForeground = mStrAttr [\"foreground\"]\n\n-- | Determines wether the content can be altered.\n--\n-- * If this flag is set, the user can alter the cell.\n--\ncellEditable :: Attribute CellRendererText (Maybe Bool)\ncellEditable = Attribute [\"editable\",\"editable-set\"] [TMboolean,TMboolean]\n\t (\\mb -> return $ case mb of\n\t\t (Just bool) -> [GVboolean bool, GVboolean True]\n\t\t Nothing -> [GVboolean True, GVboolean False])\n\t\t (\\[GVboolean e, GVboolean s] -> return $\n\t\t if s then Just e else Nothing)\n\n-- | Emitted when the user finished editing a cell.\n--\n-- * This signal is not emitted when editing is disabled (see \n-- 'cellEditable') or when the user aborts editing.\n--\nonEdited, afterEdited :: TreeModelClass tm => CellRendererText -> tm ->\n\t\t\t (TreeIter -> String -> IO ()) ->\n\t\t\t IO (ConnectId CellRendererText)\nonEdited cr tm user = connect_STRING_STRING__NONE \"edited\" False cr $\n \\path string ->\n alloca $ \\iterPtr ->\n withCString path $ \\pathPtr -> do\n res <- {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iterPtr\n pathPtr\n if toBool res\n then do\n iter <- peek iterPtr\n user iter string\n else\n putStrLn \"edited signal: invalid tree path\"\n\nafterEdited cr tm user = connect_STRING_STRING__NONE \"edited\" True cr $\n \\path string ->\n alloca $ \\iterPtr ->\n withCString path $ \\pathPtr -> do\n res <- {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iterPtr\n pathPtr\n if toBool res\n then do\n iter <- peek iterPtr\n user iter string\n else\n putStrLn \"edited signal: invalid tree path\"\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CellRendererText TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.7 $ 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-- A 'CellRenderer' which displays a single-line text.\n--\nmodule Graphics.UI.Gtk.TreeList.CellRendererText (\n-- * Detail\n-- \n-- | This widget derives from 'CellRenderer'. It provides the \n-- possibility to display some text by setting the 'Attribute' \n-- 'cellText' to the column of a 'TreeModel' by means of \n-- 'treeViewAddAttribute' from 'TreeModelColumn'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'CellRenderer'\n-- | +----CellRendererText\n-- | +----'CellRendererCombo'\n-- @\n\n-- * Types\n CellRendererText,\n CellRendererTextClass,\n castToCellRendererText,\n toCellRendererText,\n\n-- * Constructors\n cellRendererTextNew,\n\n-- * Attributes\n cellText,\n cellMarkup,\n cellBackground,\n cellForeground,\n cellEditable,\n\n-- * Signals\n onEdited,\n afterEdited\n ) where\n\nimport Maybe\t(fromMaybe)\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\nimport Graphics.UI.Gtk.General.Structs\t\t(treeIterSize)\nimport Graphics.UI.Gtk.TreeList.CellRenderer\t(Attribute(..))\nimport System.Glib.StoreValue\t\t\t(GenericValue(..), TMType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new CellRendererText object.\n--\ncellRendererTextNew :: IO CellRendererText\ncellRendererTextNew =\n makeNewObject mkCellRendererText $\n liftM (castPtr :: Ptr CellRenderer -> Ptr CellRendererText) $\n {# call unsafe cell_renderer_text_new #}\n\n-- helper function\n--\nstrAttr :: [String] -> Attribute CellRendererText String\nstrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring . Just)\n\t\t(\\[GVstring str] -> return (fromMaybe \"\" str))\n\nmStrAttr :: [String] -> Attribute CellRendererText (Maybe String)\nmStrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring)\n\t\t(\\[GVstring str] -> return str)\n\n--------------------\n-- Properties\n\n-- | Define the attribute that specifies the text to be\n-- rendered.\n--\ncellText :: Attribute CellRendererText String\ncellText = strAttr [\"text\"]\n\n-- | Define a markup string instead of a text.\n--\ncellMarkup :: Attribute CellRendererText String\ncellMarkup = strAttr [\"markup\"]\n\n-- | A named color for the background paint.\n--\ncellBackground :: Attribute CellRendererText (Maybe String)\ncellBackground = mStrAttr [\"background\"]\n\n-- | A named color for the foreground paint.\n--\ncellForeground :: Attribute CellRendererText (Maybe String)\ncellForeground = mStrAttr [\"foreground\"]\n\n-- | Determines wether the content can be altered.\n--\n-- * If this flag is set, the user can alter the cell.\n--\ncellEditable :: Attribute CellRendererText (Maybe Bool)\ncellEditable = Attribute [\"editable\",\"editable-set\"] [TMboolean,TMboolean]\n\t (\\mb -> return $ case mb of\n\t\t (Just bool) -> [GVboolean bool, GVboolean True]\n\t\t Nothing -> [GVboolean True, GVboolean False])\n\t\t (\\[GVboolean e, GVboolean s] -> return $\n\t\t if s then Just e else Nothing)\n\n-- | Emitted when the user finished editing a cell.\n--\n-- * This signal is not emitted when editing is disabled (see \n-- 'cellEditable') or when the user aborts editing.\n--\nonEdited, afterEdited :: TreeModelClass tm => CellRendererText -> tm ->\n\t\t\t (TreeIter -> String -> IO ()) ->\n\t\t\t IO (ConnectId CellRendererText)\nonEdited cr tm user = connect_PTR_STRING__NONE \"edited\" False cr $\n \\strPtr string ->\n mallocTreeIter >>= \\iter ->\n {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iter\n strPtr\n >>= \\res -> if toBool res then user iter string else\n putStrLn \"edited signal: invalid tree path\"\n\nafterEdited cr tm user = connect_PTR_STRING__NONE \"edited\" True cr $\n \\strPtr string ->\n mallocTreeIter >>= \\iter ->\n {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iter\n strPtr\n >>= \\res -> if toBool res then user iter string else\n putStrLn \"edited signal: invalid tree path\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e4b97530ed2f8699c3beac5a8d7deebbba978fe9","subject":"add versions of loadData* that read directly from a Ptr","message":"add versions of loadData* that read directly from a Ptr\n\nThe data must be NULL terminated. The ByteString versions still exist unchanged, except this way we can avoid the additional copy in order to add the trailing NULL as required by the CUDA library.\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module.chs","new_file":"Foreign\/CUDA\/Driver\/Module.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !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, this is extracted below\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 case s of\n Success -> return (JITResult time infoLog mdl)\n _ -> cudaError (unlines [describe s, B.unpack 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n getFun, getPtr, getTex, loadFile, loadData, loadDataEx, unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\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--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO 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, this is extracted below\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 case s of\n Success -> return (JITResult time infoLog mdl)\n _ -> cudaError (unlines [describe s, B.unpack 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\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--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE useByteString #-}\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":"77e8ec25ce81f381e03df5977b2b668788f8a261","subject":"gstreamer: M.S.G.Core.Element: document everything, use new signal types","message":"gstreamer: M.S.G.Core.Element: document everything, use new signal types\n\ndarcs-hash:20080212040550-21862-9bb81317145d2206c15fda8e9e4dc8e37e07185e.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Element.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 pipeline elements.\nmodule Media.Streaming.GStreamer.Core.Element (\n\n-- * Detail\n\n -- | 'Element' is the abstract base class needed to construct an\n -- element that can be used in a GStreamer pipeline.\n -- \n -- All elements have pads (of the type 'Pad'). These pads link to\n -- pads on other elements. 'Buffer's flow between these linked\n -- pads. An 'Element' has a 'Pad' for each input (or sink) and\n -- output (or source).\n -- \n -- An element's pad can be retrieved by name with\n -- 'elementGetStaticPad' or 'elementGetRequestPad'. An 'Iterator'\n -- over all an element's pads can be retrieved with\n -- 'elementIteratePads'.\n -- \n -- Elements can be linked through their pads. If the link is\n -- straightforward, use the 'elementLink' convenience function to\n -- link two elements. Use 'elementLinkFiltered' to link two\n -- elements constrained by a specified set of 'Caps'. For finer\n -- control, use 'elementLinkPads' and 'elementLinkPadsFiltered' to\n -- specify the pads to link on each element by name.\n -- \n -- Each element has a 'State'. You can get and set the state of an\n -- element with 'elementGetState' and 'elementSetState'. To get a\n -- string representation of a 'State', use 'elementStateGetName'.\n -- \n -- You can get and set a 'Clock' on an element using\n -- 'elementGetClock' and 'elementSetClock'. Some elements can\n -- provide a clock for the pipeline if 'elementProvidesClock'\n -- returns 'True'. With the 'elementProvideClock' method one can\n -- retrieve the clock provided by such an element. Not all\n -- elements require a clock to operate correctly. If\n -- 'elementRequiresClock' returns 'True', a clock should be set on\n -- the element with 'elementSetClock'.\n -- \n -- Note that clock slection and distribution is normally handled\n -- by the toplevel 'Pipeline' so the clock functions should only\n -- be used in very specific situations.\n\n-- * Types \n Element,\n ElementClass,\n castToElement,\n toElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n\n-- * Element Operations\n elementAddPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n elementNoMorePads,\n elementPadAdded,\n elementPadRemoved,\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on the element.\nelementGetFlags :: ElementClass elementT\n => elementT\n -> IO [ElementFlags]\nelementGetFlags = mkObjectGetFlags\n\n-- | Set the given flags on the element.\nelementSetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementSetFlags = mkObjectSetFlags\n\n-- | Unset the given flags on the element.\nelementUnsetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementUnsetFlags = mkObjectUnsetFlags\n\n-- | Add a pad (link point) to an element. The pad's parent will be set to\n-- @element@.\n-- \n-- Pads are not automatically activated so elements should perform\n-- the needed steps to activate the pad in case this pad is added in\n-- the 'StatePaused' or 'StatePlaying' state. See 'padSetActive' for\n-- more information about activating pads.\n-- \n-- This function will emit the 'elementPadAdded' signal on the\n-- element.\nelementAddPad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\n-- | Look for an unlinked pad to which the given pad can link. It is not\n-- guaranteed that linking the pads will work, though it should work in most\n-- cases.\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - the element for\n -- which a pad should be found\n -> padT -- ^ @pad@ - the pad to find\n -- a compatible one for\n -> Caps -- ^ @caps@ - the 'Caps' to\n -- use as a filter\n -> IO (Maybe Pad) -- ^ the compatible 'Pad', or\n -- 'Nothing' if none was found\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek takeObject\n\n-- | Retrieve a pad template from @element@ that is compatible with\n-- @padTemplate@. Pads from compatible templates can be linked\n-- together.\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT)\n => elementT -- ^ @element@ - \n -> padTemplateT -- ^ @padTemplate@ - \n -> IO (Maybe PadTemplate) -- ^ the compatible'PadTemplate',\n -- or 'Nothing' if none was found\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek takeObject\n\n-- | Retrieve a pad from the element by name. This version only\n-- retrieves request pads. The pad should be released with\n-- 'elementReleaseRequestPad'.\nelementGetRequestPad :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> String -- ^ @name@ - \n -> IO (Maybe Pad) -- ^ the requested 'Pad' if\n -- found, otherwise 'Nothing'.\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek peekObject\n\n-- | Retreive a pad from @element@ by name. This version only\n-- retrieves already-existing (i.e. \"static\") pads.\nelementGetStaticPad :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> String -- ^ @name@ - \n -> IO (Maybe Pad) -- ^ the requested 'Pad' if\n -- found, otherwise 'Nothing'.\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek takeObject\n\n-- | Release a request pad that was previously obtained with\n-- 'elementGetRequestPad'.\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\n-- | Remove @pad@ from @element@.\n-- \n-- This function is used by plugin developers and should not be used\n-- by applications. Pads that were dynamically requested from\n-- elements with 'elementGetRequestPad' should be released with the\n-- 'elementReleaseRequestPad' function instead.\n-- \n-- Pads are not automatically deactivated so elements should perform the needed\n-- steps to deactivate the pad in case this pad is removed in the PAUSED or\n-- PLAYING state. See 'padSetActive' for more information about\n-- deactivating pads.\n-- \n-- The pad and the element should be unlocked when calling this function.\n-- \n-- This function will emit the 'padRemoved' signal on the element.\n-- \n-- Returns: 'True' if the pad could be removed. Can return 'False' if the\n-- pad does not belong to the provided element.\nelementRemovePad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO Bool -- ^ 'True' if the pad was succcessfully\n -- removed, otherwise 'False'\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\n-- | Retrieve an 'Iterator' over @element@'s pads.\nelementIteratePads :: (ElementClass elementT)\n => elementT -- ^ @element@ - \n -> IO (Iterator Pad) -- ^ an iterator over the element's pads.\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= takeIterator\n\n\n-- | Retrieve an 'Iterator' over @element@'s sink pads.\nelementIterateSinkPads :: (ElementClass elementT)\n => elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\n-- | Retrieve an 'Iterator' over @element@'s src pads.\nelementIterateSrcPads :: (ElementClass elementT)\n => elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\n-- | Link @src@ to @sink@. The link must be from source to\n-- sink; the other direction will not be tried. The function\n-- looks for existing pads that aren't linked yet. It will request\n-- new pads if necessary. Such pads must be released manually (with\n-- 'elementReleaseRequestPad') when unlinking. If multiple links are\n-- possible, only one is established.\n-- \n-- Make sure you have added your elements to a 'Bin' or 'Pipeline'\n-- with 'binAdd' before trying to link them.\nelementLink :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> sinkT -- ^ @sink@ - \n -> IO Bool -- ^ 'True' if the pads could be linked,\n -- otherwise 'False'\nelementLink src sink =\n liftM toBool $ {# call element_link #} (toElement src) (toElement sink)\n\n-- | Unlink all source pads of the @src@ from all sink pads of the\n-- @sink@.\nelementUnlink :: (ElementClass srcT, ElementClass sinkT)\n => srcT\n -> sinkT\n -> IO ()\nelementUnlink src sink =\n {# call element_unlink #} (toElement src) (toElement sink)\n\n-- | Link the named pads of @src@ and @sink@.\nelementLinkPads :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - the element containing the source pad\n -> Maybe String -- ^ @srcPadName@ - the name of the source pad, or 'Nothing' for any pad\n -> sinkT -- ^ @sink@ - the element containing the sink pad\n -> Maybe String -- ^ @sinkPadName@ - the name of the sink pad, or 'Nothing' for any pad\n -> IO Bool -- ^ 'True' if the pads could be linked, otherwise 'False'\nelementLinkPads src srcPadName sink sinkPadName =\n maybeWith withUTFString sinkPadName $ \\cSinkPadName ->\n maybeWith withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement sink) cSinkPadName\n\n-- | Unlink the named pads of @src@ and @sink@.\nelementUnlinkPads :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> String -- ^ @srcPadName@ - \n -> sinkT -- ^ @sink@ - \n -> String -- ^ @sinkPadName@ - \n -> IO ()\nelementUnlinkPads src srcPadName sink sinkPadName =\n withUTFString sinkPadName $ \\cSinkPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement sink) cSinkPadName\n\n-- | Link the named pads of @src@ and @sink@. A side effect is that if\n-- one of the pads has no parent, it becomes a child of the parent\n-- of the other element. If they have different parents, the link\n-- will fail. If @caps@ is not 'Nothing', make sure that the 'Caps'\n-- of the link is a subset of @caps@.\nelementLinkPadsFiltered :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> Maybe String -- ^ @srcPadName@ - \n -> sinkT -- ^ @sink@ - \n -> Maybe String -- ^ @sinkPadName@ - \n -> Caps -- ^ @caps@ - \n -> IO Bool -- ^ 'True' if the pads could be\n -- linked, otherwise 'False'\nelementLinkPadsFiltered src srcPadName sink sinkPadName filter =\n maybeWith withUTFString sinkPadName $ \\cSinkPadName ->\n maybeWith withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement sink) cSinkPadName filter\n\n-- | Link @src@ to @dest@ using the given 'Caps' as a filter. The link\n-- must be from source to sink; the other direction will not be\n-- tried. The function looks for existing pads that aren't linked\n-- yet. If will request new pads if necessary. If multiple links are\n-- possible, only one is established.\n-- \n-- Make sure you have added your elements to a 'Bin' or 'Pipeline'\n-- with 'binAdd' before trying to link them.\nelementLinkFiltered :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> sinkT -- ^ @sink@ - \n -> Maybe Caps -- ^ @caps@ - \n -> IO Bool -- ^ 'True' if the pads could be\n -- linked, otherwise 'False'\nelementLinkFiltered src sink filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement src) (toElement sink) $\n fromMaybe (Caps nullForeignPtr) filter\n\n-- | Set the base time of @element@. See 'elementGetBaseTime' for more\n-- information.\nelementSetBaseTime :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> ClockTimeDiff -- ^ @time@ - \n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\n-- | Return the base time of @element@. The base time is the absolute\n-- time of the clock when this element was last set to\n-- 'StatePlaying'. Subtract the base time from the clock time to get\n-- the stream time of the element.\nelementGetBaseTime :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ClockTimeDiff -- ^ the base time of the element\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\n-- | Set the 'Bus' used by @element@. For internal use only, unless\n-- you're testing elements.\nelementSetBus :: (ElementClass elementT, BusClass busT)\n => elementT -- ^ @element@ - \n -> busT -- ^ @bus@ - \n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\n-- | Get the bus of @element@. Not that only a 'Pipeline' will\n-- provide a bus for the application.\nelementGetBus :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bus -- ^ the bus used by the element\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= takeObject\n\n-- | Get the factory used to create @element@.\nelementGetFactory :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ElementFactory -- ^ the factory that created @element@\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= peekObject\n\n-- | Set the 'Index' used by @element@.\nelementSetIndex :: (ElementClass elementT, IndexClass indexT)\n => elementT -- ^ @element@ - \n -> indexT -- ^ @index@ - \n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\n-- | Get the 'Index' used by @element@.\nelementGetIndex :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Index) -- ^ the index, or 'Nothing' if @element@ has none\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek takeObject\n\n-- | Determine whether @element@ can be indexed.\nelementIsIndexable :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element can be indexed\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\n-- | Determine whether @element@ requires a clock.\nelementRequiresClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element requires a clock\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\n-- | Set the 'Clock' used by @element@.\nelementSetClock :: (ElementClass elementT, ClockClass clockT)\n => elementT -- ^ @element@ - \n -> clockT -- ^ @clock@ - \n -> IO Bool -- ^ 'True' if the element accepted the clock\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\n-- | Get the 'Clock' used by @element@.\nelementGetClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Clock) -- ^ the clock, or 'Nothing' if @element@ has none\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek takeObject\n\n-- | Determine whether @element@ provides a clock. A 'Clock' provided\n-- by an element can be used as the global clock for a pipeline. An\n-- element that can provide a clock is only required to do so in the\n-- 'StatePaused' state, meaning that it is fully negotiated and has\n-- allocated the resources needed to operate the clock.\nelementProvidesClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element provides a clock\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\n-- | Get the 'Clock' provided by @element@.\n-- \n-- Note that an element is only required to provide a clock in the\n-- 'StatePaused' state. Some elements can provide a clock in other\n-- states.\nelementProvideClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Clock) -- ^ a 'Clock', or 'Nothing' if\n -- none could be provided\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek takeObject\n\n-- | Set the state of @element@ to @state@. This function will try to\n-- set the requested state by going through all the intermediary\n-- states and calling the class's state change function for each.\n-- \n-- This function can return 'StateChangeAsync', in which case the\n-- element will perform the remainder of the state change\n-- asynchronously in another thread. An application can use\n-- 'elementGetState' to wait for the completion of the state change\n-- or it can wait for a state change message on the bus.\nelementSetState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> State -- ^ @state@ - \n -> IO StateChangeReturn -- ^ the result of the state change\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\n-- | Get the state of @element@.\n-- \n-- For elements that performed an asynchronous state change, as\n-- reported by 'elementSetState', this function will block up to the\n-- specified timeout value for the state change to complete. If the\n-- element completes the state change or goes into an error, this\n-- function returns immediately with a return value of\n-- 'StateChangeSuccess' or 'StateChangeFailure', respectively.\n-- \n-- This function returns 'StateChangeNoPreroll' if the element\n-- successfully changed its state but is not able to provide data\n-- yet. This mostly happens for live sources that not only produce\n-- data in the 'StatePlaying' state. While the state change return\n-- is equivalent to 'StateChangeSuccess', it is returned to the\n-- application to signal that some sink elements might not be able\n-- to somplete their state change because an element is not\n-- producing data to complete the preroll. When setting the element\n-- to playing, the preroll will complete and playback will start.\nelementGetState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> ClockTime -- ^ @timeout@ - \n -> IO (StateChangeReturn, Maybe State, Maybe State)\n -- ^ the result of the state change, the current\n -- state, and the pending state\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do poke statePtr (-1) -- -1 is not use by any enum value\n poke pendingPtr (-1)\n result <- {# call element_get_state #} (toElement element)\n statePtr\n pendingPtr\n (fromIntegral timeout)\n state <- unmarshalState statePtr\n pending <- unmarshalState pendingPtr\n return (toEnum $ fromIntegral result, state, pending)\n where unmarshalState statePtr = do\n cState <- peek statePtr\n if cState \/= -1\n then return $ Just $ toEnum $ fromIntegral cState\n else return Nothing\n\n-- | Lock the state of @element@, so state changes in the parent don't\n-- affect this element any longer.\nelementSetLockedState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> Bool -- ^ @lockedState@ - 'True' for locked, 'False' for unlocked\n -> IO Bool -- ^ 'True' if the state was changed, 'False' if bad\n -- parameters were given or no change was needed\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\n-- | Determine whether @element@'s state is locked.\nelementIsLockedState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if @element@'s state is locked, 'False' otherwise\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\n-- | Abort @element@'s state change. This function is used by elements\n-- that do asynchronous state changes and find out something is wrong.\n-- \n-- This function should be called with the state lock held.\nelementAbortState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\n-- | Get a string representation of @state@.\nelementStateGetName :: State -- ^ @state@ - \n -> String -- ^ the name of @state@\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\n-- | Get a string representation of @stateRet@.\nelementStateChangeReturnGetName :: StateChangeReturn -- ^ @stateRet@ - \n -> String -- ^ the name of @stateRet@\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\n-- | Try to change the state of @element@ to the same as its\n-- parent. If this function returns 'False', the state of the\n-- element is undefined.\nelementSyncStateWithParent :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element's state could be\n -- synced with its parent's state\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\n-- | Perform a query on the given element.\n-- \n-- For elements that don't implement a query handler, this function\n-- forwards the query to a random srcpad or to the peer of a random\n-- linked sinkpad of this element.\nelementQuery :: (ElementClass element, QueryClass query)\n => element -- ^ @element@ - \n -> query -- ^ @query@ - \n -> IO Bool -- ^ 'True' if the query could be performed\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n fmap toBool $ {# call element_query #} (toElement element) $ Query query'\n\n-- | Query an element for the convertion of a value from one format to\n-- another.\nelementQueryConvert :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @srcFormat@ - the format to convert from\n -> Int64 -- ^ @srcVal@ - the value to convert\n -> Format -- ^ @destFormat@ - the format to convert to\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryConvert element srcFormat srcVal destFormat =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do poke destFormatPtr $ fromIntegral $ fromEnum destFormat\n success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\n-- | Query an element for its stream position.\nelementQueryPosition :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @format@ - the format requested\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryPosition element format =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\n-- | Query an element for its stream duration.\nelementQueryDuration :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @format@ - the format requested\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryDuration element format =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\n-- | Send an event to an element.\n-- \n-- If the element doesn't implement an event handler, the event will\n-- be pushed to a random linked sink pad for upstream events or a\n-- random linked source pad for downstream events.\nelementSendEvent :: (ElementClass element, EventClass event)\n => element -- ^ @element@ - the element to send the event to\n -> event -- ^ @event@ - the event to send\n -> IO Bool -- ^ 'True' if the event was handled\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\n-- | Perform a seek on the given element. This function only supports\n-- seeking to a position relative to the start of the stream. For\n-- more complex operations like segment seeks (such as for looping),\n-- or changing the playback rate, or seeking relative to the last\n-- configured playback segment you should use 'elementSeek'.\n-- \n-- In a completely prerolled pipeline in the 'StatePaused' or\n-- 'StatePlaying' states, seeking is always guaranteed to return\n-- 'True' on a seekable media type, or 'False' when the media type\n-- is certainly not seekable (such as a live stream).\n-- \n-- Some elements allow for seeking in the 'StateReady' state, in\n-- which case they will store the seek event and execute it when\n-- they are put into the 'StatePaused' state. If the element\n-- supports seek in \"StateReady\", it will always return 'True' when\n-- it recieves the event in the 'StateReady' state.\nelementSeekSimple :: ElementClass element\n => element -- ^ @element@ - the element to seek on\n -> Format -- ^ @format@ - the 'Format' to evecute the seek in,\n -- such as 'FormatTime'\n -> [SeekFlags] -- ^ @seekFlags@ - seek options; playback applications\n -- will usually want to use\n -- @['SeekFlagFlush','SeekFlagKeyUnit']@\n -> Int64 -- ^ @seekPos@ - the position to seek to, relative to\n -- start; if you are doing a seek in\n -- 'FormatTime' this value is in nanoseconds;\n -- see 'second', 'msecond', 'usecond', &\n -- 'nsecond'\n -> IO Bool -- ^ 'True' if the seek operation succeeded\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\n-- | Send a seek event to an element. See\n-- 'Media.Streaming.GStreamer.Core.Event.eventNewSeek' for the\n-- details of the parameters. The seek event is sent to the element\n-- using 'elementSendEvent'.\nelementSeek :: ElementClass element\n => element -- ^ @element@ - the element to seek on\n -> Double -- ^ @rate@ - the new playback rate\n -> Format -- ^ @format@ - the format of the seek values\n -> [SeekFlags] -- ^ @seekFlags@ - the options to use\n -> SeekType -- ^ @curType@ - type and flags for the new current position\n -> Int64 -- ^ @cur@ - the value of the new current position\n -> SeekType -- ^ @stopType@ - type and flags for the new stop position\n -> Int64 -- ^ @stop@ - the value of the new stop position\n -> IO Bool -- ^ 'True' if the event was handled\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\n-- | The signal emitted when an element will not generate more dynamic\n-- pads.\nelementNoMorePads :: (ElementClass element)\n => Signal element (IO ())\nelementNoMorePads =\n Signal $ connect_NONE__NONE \"no-more-pads\"\n\n-- | The signal emitted when a new 'Pad' has been added to the\n-- element.\nelementPadAdded :: (ElementClass element)\n => Signal element (Pad -> IO ())\nelementPadAdded =\n Signal $ connect_OBJECT__NONE \"pad-added\"\n\n-- | The signal emitted when a 'Pad' has been removed from the\n-- element.\nelementPadRemoved :: (ElementClass element)\n => Signal element (Pad -> IO ())\nelementPadRemoved =\n Signal $ connect_OBJECT__NONE \"pad-removed\"\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.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementGetFlags :: ElementClass elementT\n => elementT\n -> IO [ElementFlags]\nelementGetFlags = mkObjectGetFlags\n\nelementSetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementSetFlags = mkObjectSetFlags\n\nelementUnsetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementUnsetFlags = mkObjectUnsetFlags\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek takeObject\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek takeObject\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek takeObject\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek peekObject\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek takeObject\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= takeIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= takeObject\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= peekObject\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek takeObject\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek takeObject\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek takeObject\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM Just $ withForeignPtr query' $ takeMiniObject . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Word64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> Format\n -> IO (Maybe (Format, Word64))\nelementQueryPosition element format =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> Format\n -> IO (Maybe (Format, Word64))\nelementQueryDuration element format =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1d7f01a121ed57618f30117ac85dad9c5ea86b9c","subject":"gio: S.G.AsyncResult: specify module exports","message":"gio: S.G.AsyncResult: specify module exports\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gio\/System\/GIO\/AsyncResult.chs","new_file":"gio\/System\/GIO\/AsyncResult.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.AsyncResult (\n AsyncResult,\n AsyncResultClass,\n AsyncReadyCallback\n ) where\n\nimport System.Glib.FFI\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\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-- 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.AsyncResult where\n\nimport System.Glib.FFI\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f00ef965de5e4e125324e2982433b49479e5329c","subject":"Made #fun of opFree","message":"Made #fun of opFree\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*- #}\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{-\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 , mpiErrorCode :: CInt\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 code\n\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 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 #}\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 , mpiErrorCode :: CInt\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 code\n\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":"8186090b2bbd5838bc04cc1b8cf8b1596dce9caa","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\/CPLError.chs","new_file":"src\/GDAL\/Internal\/CPLError.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n , withErrorHandler\n , popLastError\n , checkCPLError\n , checkGDALCall\n , checkGDALCall_\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Concurrent (runInBoundThread, rtsSupportsBoundThreads)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad (void, liftM)\nimport Control.Monad.Catch (\n Exception (..)\n , SomeException\n , MonadCatch\n , MonadMask\n , MonadThrow (throwM)\n , mask\n , onException\n , bracket\n , finally\n )\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable, cast)\nimport Data.Monoid (mconcat)\n\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (nullPtr)\nimport Foreign.Storable (peekByteOff)\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport Foreign.Ptr (Ptr)\n\nimport GDAL.Internal.Util (toEnumC, peekEncodedCString)\n\n#include \"cpl_error.h\"\n#include \"cbits.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ndata GDALException\n = forall e. (Exception e, NFData e) =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !Text}\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException\n :: (Exception e, NFData e) => e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException\n :: (Exception e, NFData e) => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\ninstance NFData GDALException where\n rnf (GDALBindingException e) = rnf e\n rnf (GDALException e n m) = rnf e `seq` rnf n `seq` rnf m `seq` ()\n\nthrowBindingException :: (MonadThrow m, Exception e, NFData e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\ninstance NFData ErrorType where\n rnf a = a `seq` ()\n\ninstance NFData ErrorNum where\n rnf a = a `seq` ()\n\n\ncheckGDALCall\n :: (MonadMask m, MonadIO m, Exception e)\n => (Maybe GDALException -> a -> Maybe e) -> m a -> m a\ncheckGDALCall isOk act = mask $ \\restore -> do\n liftIO $ clearErrors\n a <- restore act `onException` (liftIO popLastError)\n err <- liftIO popLastError\n case isOk err a of\n Nothing -> return a\n Just e -> throwM e\n{-# INLINE checkGDALCall #-}\n\ncheckGDALCall_\n :: (MonadMask m, MonadIO m, Functor m, Exception e)\n => (Maybe GDALException -> a -> Maybe e) -> m a -> m ()\n{-# INLINE checkGDALCall_ #-}\ncheckGDALCall_ isOk = void . checkGDALCall isOk\n\ncheckCPLError :: IO CInt -> IO ()\ncheckCPLError = checkGDALCall_ $ \\mExc r ->\n case (mExc, toEnumC r) of\n (Nothing, CE_None) -> Nothing\n (Nothing, e) -> Just (GDALException e AssertionFailed \"checkCPLError\")\n (e, _) -> e\n{-# INLINE checkCPLError #-}\n\n{#pointer ErrorCell #}\n\npopLastError :: IO (Maybe GDALException)\npopLastError =\n bracket {#call unsafe pop_last as ^#}\n {#call unsafe destroy_ErrorCell as ^#} $ \\ec -> do\n if ec == nullPtr\n then return Nothing\n else do\n msg <- peekEncodedCString =<< {#get ErrorCell->msg #} ec\n errClass <- liftM toEnumC ({#get ErrorCell->errClass#} ec)\n errNo <- liftM toEnumC ({#get ErrorCell->errNo#} ec)\n return (Just (GDALException errClass errNo msg))\n\nclearErrors :: IO ()\nclearErrors = {#call unsafe clear_stack as ^#}\n\nwithErrorHandler :: IO a -> IO a\nwithErrorHandler act = runBounded $\n ({#call unsafe push_error_handler as ^#} >> act)\n `finally` {#call unsafe pop_error_handler as ^#}\n where\n runBounded\n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n","old_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n , withErrorHandler\n , popLastError\n , checkCPLError\n , checkGDALCall\n , checkGDALCall_\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Concurrent (runInBoundThread, rtsSupportsBoundThreads)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad (void, liftM)\nimport Control.Monad.Catch (\n Exception (..)\n , SomeException\n , MonadCatch\n , MonadMask\n , MonadThrow (throwM)\n , mask\n , onException\n , bracket\n , finally\n )\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable, cast)\nimport Data.Monoid (mconcat)\n\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (nullPtr)\nimport Foreign.Storable (peekByteOff)\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport Foreign.Ptr (Ptr)\n\nimport GDAL.Internal.Util (toEnumC, peekEncodedCString)\n\n#include \"cpl_error.h\"\n#include \"cbits.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ndata GDALException\n = forall e. (Exception e, NFData e) =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !Text}\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException\n :: (Exception e, NFData e) => e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException\n :: (Exception e, NFData e) => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\ninstance NFData GDALException where\n rnf (GDALBindingException e) = rnf e\n rnf (GDALException e n m) = rnf e `seq` rnf n `seq` rnf m `seq` ()\n\nthrowBindingException :: (MonadThrow m, Exception e, NFData e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\ninstance NFData ErrorType where\n rnf a = a `seq` ()\n\ninstance NFData ErrorNum where\n rnf a = a `seq` ()\n\n\ncheckGDALCall\n :: (MonadMask m, MonadIO m, Exception e)\n => (Maybe GDALException -> a -> Maybe e) -> m a -> m a\ncheckGDALCall isOk act = mask $ \\restore -> do\n liftIO $ clearErrors\n a <- restore act `onException` (liftIO popLastError)\n err <- liftIO popLastError\n case isOk err a of\n Nothing -> return a\n Just e -> throwM e\n{-# INLINE checkGDALCall #-}\n\ncheckGDALCall_\n :: (MonadMask m, MonadIO m, Exception e)\n => (Maybe GDALException -> a -> Maybe e) -> m a -> m ()\n{-# INLINE checkGDALCall_ #-}\ncheckGDALCall_ isOk = void . checkGDALCall isOk\n\ncheckCPLError :: IO CInt -> IO ()\ncheckCPLError = checkGDALCall_ $ \\mExc r ->\n case (mExc, toEnumC r) of\n (Nothing, CE_None) -> Nothing\n (Nothing, e) -> Just (GDALException e AssertionFailed \"checkCPLError\")\n (e, _) -> e\n{-# INLINE checkCPLError #-}\n\n{#pointer ErrorCell #}\n\npopLastError :: IO (Maybe GDALException)\npopLastError =\n bracket {#call unsafe pop_last as ^#}\n {#call unsafe destroy_ErrorCell as ^#} $ \\ec -> do\n if ec == nullPtr\n then return Nothing\n else do\n msg <- peekEncodedCString =<< {#get ErrorCell->msg #} ec\n errClass <- liftM toEnumC ({#get ErrorCell->errClass#} ec)\n errNo <- liftM toEnumC ({#get ErrorCell->errNo#} ec)\n return (Just (GDALException errClass errNo msg))\n\nclearErrors :: IO ()\nclearErrors = {#call unsafe clear_stack as ^#}\n\nwithErrorHandler :: IO a -> IO a\nwithErrorHandler act = runBounded $\n ({#call unsafe push_error_handler as ^#} >> act)\n `finally` {#call unsafe pop_error_handler as ^#}\n where\n runBounded\n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d8f1ff1fe86e36143f12f8171d43df23dd1c5142","subject":"gstreamer: remove commented function messageParseAsyncStart in Message.chs","message":"gstreamer: remove commented function messageParseAsyncStart in Message.chs","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n \n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n --messageParseAsyncStart\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\n{-\nmessageParseAsyncStart :: Message\n -> Bool\nmessageParseAsyncStart message =\n toBool $ unsafePerformIO $ alloca $ \\newBaseTimePtr ->\n do poke newBaseTimePtr $ fromBool False\n {# call message_parse_async_start #} message newBaseTimePtr\n peek newBaseTimePtr\n-}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b5e60ddc708ec46bb98f2903b7737801073ec050","subject":"Added skeletonization to Morphology","message":"Added skeletonization to Morphology\n","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, ViewPatterns#-}\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 ,skeletonize\n ,dilateOp,erodeOp,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\n\n-- Morphological opening\nopenOp :: StructuringElement -> ImageOperation GrayScale d\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 d\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 d -> ImageOperation GrayScale d\ngeodesic mask op = op #> IM.limitToOp mask\n\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 (Int, Int) -> KernelShape -> StructuringElement\nstructuringElement s d | isGoodSE s d = createSE s d \n | otherwise = error \"Bad values in structuring element\"\n\n-- Create SE with custom shape that is taken from flat list shape.\ncreateSE :: (Int, Int) -> (Int, Int) -> KernelShape -> StructuringElement\ncreateSE (fromIntegral -> w,fromIntegral -> h) (fromIntegral -> x,fromIntegral -> y) shape = unsafePerformIO $ do\n iptr <- {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ shape) nullPtr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\ncustomSE :: (CInt, CInt) -> (CInt, CInt) -> [CInt] -> ConvKernel\ncustomSE s@(w,h) o shape | isGoodSE s o \n && length shape == fromIntegral (w*h)\n = createCustomSE s o shape\n\ncreateCustomSE (w,h) (x,y) shape = unsafePerformIO $ do\n iptr <- withArray shape $ \\arr ->\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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\nskeletonize :: Image GrayScale D8 -> Image GrayScale D8\nskeletonize i = fst . snd . head . dropWhile (\\x -> fst x > 0) . iterate (skeletonize'.snd)\n $\u00a0(1,(CV.Image.empty (getSize i),i))\nskeletonize' :: (Image GrayScale D8, Image GrayScale D8) -> (Int, (Image GrayScale D8, Image GrayScale D8))\nskeletonize' (skel,img) = (countNonZero tmp, (tmp, erode se 1 img))\n where \n tmp = unsafeOperateOn img $ openOp se #> IM.notOp #> IM.andOp img Nothing #> IM.orOp skel Nothing\n se = structuringElement (3,3) (1,1) CrossShape \n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, UnicodeSyntax, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\n\n-- Morphological opening\nopenOp :: StructuringElement -> ImageOperation GrayScale d\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 d\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 d -> ImageOperation GrayScale d\ngeodesic mask op = op #> IM.limitToOp mask\n\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 (Int, Int) -> KernelShape -> StructuringElement\nstructuringElement s d | isGoodSE s d = createSE s d \n | otherwise = error \"Bad values in structuring element\"\n\n-- Create SE with custom shape that is taken from flat list shape.\ncreateSE :: (Int, Int) -> (Int, Int) -> KernelShape -> StructuringElement\ncreateSE (fromIntegral -> w,fromIntegral -> h) (fromIntegral -> x,fromIntegral -> y) shape = unsafePerformIO $ do\n iptr <- {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ shape) nullPtr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\ncustomSE :: (CInt, CInt) -> (CInt, CInt) -> [CInt] -> ConvKernel\ncustomSE s@(w,h) o shape | isGoodSE s o \n && length shape == fromIntegral (w*h)\n = createCustomSE s o shape\n\ncreateCustomSE (w,h) (x,y) shape = unsafePerformIO $ do\n iptr <- withArray shape $ \\arr ->\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"78d3ef1f28f5f06cb32dfbc6cebb51886a269540","subject":"Added some documentation","message":"Added some documentation","repos":"BeautifulDestinations\/CV,aleator\/CV,aleator\/CV,TomMD\/CV","old_file":"CV\/Transforms.chs","new_file":"CV\/Transforms.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, ScopedTypeVariables, PatternGuards, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\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 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 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 axis img = unsafePerformIO $ do\n 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 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 target <- emptyCopy img \n withImage img $ \\cimg ->\n withImage target $\u00a0\\ctarget ->\n {#call radialRemap#} cimg ctarget (realToFrac k)\n return target\n\n-- |\u00a0Scale image by a ratio on both axes\nscaleSingleRatio tpe x img = scale tpe (x,x) img\n\n\n-- | Scale an image\nscale :: (RealFloat a) => Interpolation -> (a,a) -> Image GrayScale D32 -> Image GrayScale 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\nscaleToSize :: Interpolation -> Bool -> (Int,Int) -> Image GrayScale D32 -> Image GrayScale 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\noneParamPerspective img k\n = unsafePerformIO $ \n withImage img $ \\cimg -> creatingImage $ {#call simplePerspective#} k cimg\n\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\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\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\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\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\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\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 pyramid = foldl1 (\\a b -> (pyrUp a) #+ b) (pyramid)\n -- where \n -- safeAdd x y = sameSizePad y x #+ y \n\n-- | Enlarge image so, that it's size is divisible by 2^n \n-- TODO: Could have wider type\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 CV_DIST_C\n ,CV_DIST_L1\n ,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\"\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 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 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 axis img = unsafePerformIO $ do\n 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 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 target <- emptyCopy img \n withImage img $ \\cimg ->\n withImage target $\u00a0\\ctarget ->\n {#call radialRemap#} cimg ctarget (realToFrac k)\n return target\n\nscaleSingleRatio tpe x img = scale tpe (x,x) img\n\nscale :: (RealFloat a) => Interpolation -> (a,a) -> Image GrayScale D32 -> Image GrayScale 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\nscaleToSize :: Interpolation -> Bool -> (Int,Int) -> Image GrayScale D32 -> Image GrayScale 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\noneParamPerspective img k\n = unsafePerformIO $ \n withImage img $ \\cimg -> creatingImage $ {#call simplePerspective#} k cimg\n\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\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\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\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\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\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\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 pyramid = foldl1 (\\a b -> (pyrUp a) #+ b) (pyramid)\n -- where \n -- safeAdd x y = sameSizePad y x #+ y \n\n-- | Enlarge image so, that it's size is divisible by 2^n \n-- TODO: Could have wider type\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 CV_DIST_C\n ,CV_DIST_L1\n ,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":"e339df9638813cd21c8a0c670952a2da970759c6","subject":"Refactoring","message":"Refactoring\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\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 undefined spStr (fromBool acrossFs) cdsStr\n retEither res $ undefined\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\n-- TODO: Refactor some bits\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\n-- TODO: Add tysig\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","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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\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 undefined spStr (fromBool acrossFs) cdsStr\n if res == 0\n then undefined\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Index) $ peek idx\n else return . Left . toEnum . fromIntegral $ res\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\n-- TODO: Refactor some bits\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bdc956b92379911c9c53de20a48aec6e5a0ae255","subject":"Don't bind attributes we don't understand.","message":"Don't bind attributes we don't understand.","repos":"vincenthz\/webkit","old_file":"glib\/System\/Glib\/GValueTypes.chs","new_file":"glib\/System\/Glib\/GValueTypes.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetUChar,\n valueGetUChar,\n valueSetChar,\n valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue (fromIntegral value)\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n liftM fromIntegral $ {# call unsafe value_get_uchar #} gvalue\n\n--these belong somewhere else, are in new c2hs's C2HS module\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\n--valueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar :: GValue -> Char -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue (cFromEnum value)\n\n--valueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar :: GValue -> IO Char\nvalueGetChar gvalue =\n liftM cToEnum $ {# call unsafe value_get_char #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"3dfa719afa638cd868027cae75a60bcd9165aaf5","subject":"Output feeding and signal capabilities for VteLite widgets","message":"Output feeding and signal capabilities for VteLite widgets\n\ndarcs-hash:20090216172650-ceb9a-79ceb0abc15bb803e962ba1fa84a7a5afca32005.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/VteLite.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/VteLite.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Button\n--\n-- Author : Axel Simon\n--\n-- Created: 15 May 2001\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-- A widget that creates a signal when clicked on\n--\nmodule Graphics.UI.Gtk.VteLite (\n\n-- * Types\n VteTerminal,\n VteLiteClass,\n\n-- * Constructors\n vteLiteNew,\n\n-- * Methods\n vteLiteSetFontFromString,\n vteLiteSetMouseAutoHide,\n vteLiteBeginAppOutput,\n vteLiteFinishAppOutput,\n vteLiteFeed,\n\n-- * Signals\n onLineReceived\n ) where\n\nimport Control.Monad\t(liftM)\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport System.Glib.FFI\nimport System.Glib.UTFString\n\n{#pointer *VteTerminal foreign newtype #}\n\nclass WidgetClass o => VteLiteClass o\ntoVteLite :: VteLiteClass o => o -> VteTerminal\ntoVteLite = unsafeCastGObject . toGObject\n\nmkVteLite = VteTerminal\nunVteLite (VteTerminal o) = o\n\ninstance VteLiteClass VteTerminal\ninstance ObjectClass VteTerminal\ninstance WidgetClass VteTerminal\ninstance GObjectClass VteTerminal where\n toGObject = mkGObject . castForeignPtr . unVteLite\n unsafeCastGObject = mkVteLite . castForeignPtr . unGObject\n\nvteLiteNew :: IO VteTerminal\nvteLiteNew =\n makeNewObject mkVteLite $\n liftM (castPtr :: Ptr Widget -> Ptr VteTerminal) $\n {# call unsafe vte_terminal_new #}\n\nvteLiteSetFontFromString terminal font =\n withUTFString font $ \\fontPtr ->\n {# call vte_terminal_set_font_from_string #}\n (toVteLite terminal)\n fontPtr\n\nvteLiteSetMouseAutoHide terminal status =\n {# call vte_terminal_set_mouse_autohide #}\n (toVteLite terminal)\n (fromBool status)\n\nvteLiteBeginAppOutput terminal =\n {# call vte_terminal_begin_app_output #}\n (toVteLite terminal)\n\nvteLiteFinishAppOutput terminal =\n {# call vte_terminal_finish_app_output #}\n (toVteLite terminal)\n\nvteLiteFeed terminal input =\n withUTFString input $ \\inputPtr ->\n {# call vte_terminal_feed #}\n (toVteLite terminal)\n inputPtr\n (fromIntegral (length input))\n\nonLineReceived :: VteLiteClass t => t\n -> (String -> IO ())\n -> IO (ConnectId t)\nonLineReceived = connect_STRING__NONE \"line-received\" False\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Button\n--\n-- Author : Axel Simon\n--\n-- Created: 15 May 2001\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-- A widget that creates a signal when clicked on\n--\nmodule Graphics.UI.Gtk.VteLite (\n\n-- * Types\n VteTerminal,\n-- VteLiteClass,\n-- castToVteLite,\n-- toVteLite,\n\n-- * Constructors\n vteLiteNew,\n\n-- * Methods\n vteLiteSetFontFromString,\n vteLiteSetMouseAutoHide,\n vteLiteBeginAppOutput,\n vteLiteFinishAppOutput,\n-- vteLiteFeed,\n\n-- * Signals\n-- onLineReceived\n ) where\n\nimport Control.Monad\t(liftM)\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.FFI\nimport System.Glib.UTFString\n\n{#pointer *VteTerminal foreign newtype #}\n\nclass WidgetClass o => VteLiteClass o\ntoVteLite :: VteLiteClass o => o -> VteTerminal\ntoVteLite = unsafeCastGObject . toGObject\n\nmkVteLite = VteTerminal\nunVteLite (VteTerminal o) = o\n\ninstance VteLiteClass VteTerminal\ninstance ObjectClass VteTerminal\ninstance WidgetClass VteTerminal\ninstance GObjectClass VteTerminal where\n toGObject = mkGObject . castForeignPtr . unVteLite\n unsafeCastGObject = mkVteLite . castForeignPtr . unGObject\n\nvteLiteNew :: IO VteTerminal\nvteLiteNew =\n makeNewObject mkVteLite $\n liftM (castPtr :: Ptr Widget -> Ptr VteTerminal) $\n {# call unsafe vte_terminal_new #}\n\nvteLiteSetFontFromString terminal font =\n withUTFString font $ \\fontPtr ->\n {# call vte_terminal_set_font_from_string #}\n (toVteLite terminal)\n fontPtr\n\nvteLiteSetMouseAutoHide terminal status =\n {# call vte_terminal_set_mouse_autohide #}\n (toVteLite terminal)\n (fromBool status)\n\nvteLiteBeginAppOutput terminal =\n {# call vte_terminal_begin_app_output #}\n (toVteLite terminal)\n\nvteLiteFinishAppOutput terminal =\n {# call vte_terminal_finish_app_output #}\n (toVteLite terminal)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"26b45886279abfc300b05f354f1800b172e2f3a3","subject":"pick a better name than \"weird\"","message":"pick a better name than \"weird\"\n","repos":"GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto","old_file":"lib\/Implementation\/Cryptodev.chs","new_file":"lib\/Implementation\/Cryptodev.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"261275242dc2d4f7e0df4890e6f3892936c6c9da","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","repos":"vincenthz\/webkit","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":"606d92bac42aa8cb93f9b23ab3b46adfa91046f7","subject":"Add mutex functions to Gtk and remove the funky threaded intialisation function.","message":"Add mutex functions to Gtk and remove the funky threaded intialisation function.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n threadsEnter,\n threadsLeave,\n \n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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\nunsafeInitGUIForThreadedRTS = initGUI\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 header 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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\n--\n-- * If you want to use Gtk2Hs and in a multi-threaded application then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'. See also 'threadsEnter'.\n--\ninitGUI :: IO [String]\ninitGUI = do\n when rtsSupportsBoundThreads initialiseGThreads\n threadsEnter\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\n\n-- | Acquired the global Gtk lock.\n--\n-- * During normal operation, this lock is held by the thread from which all\n-- interaction with Gtk is performed. When calling 'mainGUI', the thread will\n-- release this global lock before it waits for user interaction. During this\n-- time it is, in principle, possible to use a different OS thread (any other\n-- Haskell thread that is bound to the Gtk OS thread will be blocked anyway)\n-- to interact with Gtk by explicitly acquiring the lock, calling Gtk functions\n-- and releasing the lock. However, the Gtk functions that are called from this\n-- different thread may not trigger any calls to the OS since this will\n-- lead to a crash on Windows (the Win32 API can only be used from a single\n-- thread). Since it is very hard to tell which function only interacts on\n-- Gtk data structures and which function call actual OS functions, it\n-- is best not to use this feature at all. A better way to perform updates\n-- in the background is to spawn a Haskell thread and to perform the update\n-- to Gtk widgets using 'postGUIAsync' or 'postGUISync'. These will execute\n-- their arguments from the main loop, that is, from the OS thread of Gtk,\n-- thereby ensuring that any Gtk and OS function can be called.\n--\n{#fun unsafe gdk_threads_enter as threadsEnter {} -> `()' #}\n\n-- | Release the global Gtk lock.\n--\n-- * The use of this function is not recommended. See 'threadsEnter'.\n--\n{#fun unsafe gdk_threads_leave as threadsLeave {} -> `()' #}\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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 header 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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"08e4e748a36b98ae4b29f23840dcbb7a47268d11","subject":"fix display of NVVM UserError","message":"fix display of NVVM UserError\n","repos":"nvidia-compiler-sdk\/hsnvvm","old_file":"Foreign\/LibNVVM\/Error.chs","new_file":"Foreign\/LibNVVM\/Error.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n-- Copyright (c) 2012-2014 NVIDIA Corporation. All rights reserved.\n--\n-- Permission is hereby granted, free of charge, to any person obtaining a copy\n-- of this software and associated documentation files (the \"Software\"), to deal\n-- in the Software without restriction, including without limitation the rights\n-- to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n-- copies of the Software, and to permit persons to whom the Software is\n-- furnished to do so, subject to the following conditions:\n--\n-- The above copyright notice and this permission notice shall be included in\n-- all copies or substantial portions of the Software.\n--\n-- THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n-- SOFTWARE.\n-- |\n-- Module : Foreign.LibNVVM.Error\n-- Copyright : NVIDIA Corporation\n-- License : MIT\n--\n-- Maintainer : Sean Lee \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\nmodule Foreign.LibNVVM.Error (\n\n -- * Error code\n Status(..), NVVMException(..),\n nvvmError, describe,\n\n -- * Helper functions\n resultIfOk, nothingIfOk,\n\n) where\n\nimport Control.Exception\nimport Data.Typeable\nimport System.IO.Unsafe\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.LibNVVM.Internal\n\n#include \"cbits\/stubs.h\"\n{# context lib = \"nvvm\" #}\n\n-- |\n-- The type 'Status' is an enumeration whose values represent the status of the\n-- last libNVVM operation.\n--\n{# enum nvvmResult as Status\n { underscoreToCase\n , NVVM_SUCCESS as Success\n }\n with prefix=\"NVVM_ERROR\" deriving (Eq, Show) #}\n\n\n-- | An NVVM Exception\n--\ndata NVVMException\n = ExitCode Status\n | UserError String\n deriving Typeable\n\ninstance Exception NVVMException\n\ninstance Show NVVMException where\n showsPrec n (ExitCode s) = showsPrec n (\"NVVM Exception: \" ++ describe s)\n showsPrec _ (UserError s) = showString s\n\n-- | Raise an 'NVVMException' in the IO monad\n--\nnvvmError :: String -> IO a\nnvvmError s = throwIO (UserError s)\n\n\n-- Helper function\n-- ---------------\n\n-- | Get the message string for a given NVVM result code\n--\n{# fun pure unsafe nvvmGetErrorString as describe\n { cFromEnum `Status' } -> `String' #}\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--\n{-# INLINE resultIfOk #-}\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status, result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n-- |\n-- Throw an exception with an error string associated with an unsuccessful\n-- return code, otherwise return unit.\n--\n{-# INLINE nothingIfOk #-}\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n-- Copyright (c) 2012-2014 NVIDIA Corporation. All rights reserved.\n--\n-- Permission is hereby granted, free of charge, to any person obtaining a copy\n-- of this software and associated documentation files (the \"Software\"), to deal\n-- in the Software without restriction, including without limitation the rights\n-- to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n-- copies of the Software, and to permit persons to whom the Software is\n-- furnished to do so, subject to the following conditions:\n--\n-- The above copyright notice and this permission notice shall be included in\n-- all copies or substantial portions of the Software.\n--\n-- THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n-- SOFTWARE.\n-- |\n-- Module : Foreign.LibNVVM.Error\n-- Copyright : NVIDIA Corporation\n-- License : MIT\n--\n-- Maintainer : Sean Lee \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\nmodule Foreign.LibNVVM.Error (\n\n -- * Error code\n Status(..), NVVMException(..),\n nvvmError, describe,\n\n -- * Helper functions\n resultIfOk, nothingIfOk,\n\n) where\n\nimport Control.Exception\nimport Data.Typeable\nimport System.IO.Unsafe\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.LibNVVM.Internal\n\n#include \"cbits\/stubs.h\"\n{# context lib = \"nvvm\" #}\n\n-- |\n-- The type 'Status' is an enumeration whose values represent the status of the\n-- last libNVVM operation.\n--\n{# enum nvvmResult as Status\n { underscoreToCase\n , NVVM_SUCCESS as Success\n }\n with prefix=\"NVVM_ERROR\" deriving (Eq, Show) #}\n\n\n-- | An NVVM Exception\n--\ndata NVVMException\n = ExitCode Status\n | UserError String\n deriving Typeable\n\ninstance Exception NVVMException\n\ninstance Show NVVMException where\n showsPrec n (ExitCode s) = showsPrec n (\"NVVM Exception: \" ++ describe s)\n showsPrec n (UserError s) = showsPrec n s\n\n-- | Raise an 'NVVMException' in the IO monad\n--\nnvvmError :: String -> IO a\nnvvmError s = throwIO (UserError s)\n\n\n-- Helper function\n-- ---------------\n\n-- | Get the message string for a given NVVM result code\n--\n{# fun pure unsafe nvvmGetErrorString as describe\n { cFromEnum `Status' } -> `String' #}\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--\n{-# INLINE resultIfOk #-}\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status, result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n-- |\n-- Throw an exception with an error string associated with an unsuccessful\n-- return code, otherwise return unit.\n--\n{-# INLINE nothingIfOk #-}\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"096a22f0d22802d6a53c8501f7d673e4e4229003","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":"b8efe568c25fee400517db608e45fc9f16b74f61","subject":"Refactoring","message":"Refactoring\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Config.chs","new_file":"src\/haskell\/Data\/HGit2\/Config.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Config where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Foreign\nimport Foreign.C\n\nnewtype Config = Config CPtr\n\n-- | Locate the path to the global configuration file\n--\n-- The user or global configuration file is usually located in\n-- `$HOME\/.gitconfig`.\n--\n-- This method will try to guess the full path to that file, if the file\n-- exists. The returned path may be used on any `git_config` call to load the\n-- global configuration file.\nfindGlobalConfig :: IO (Maybe String)\nfindGlobalConfig = alloca $ \\pth -> do\n res <- {#call git_config_find_global#} pth\n if res == 0\n then fmap Just $ peekCString pth\n else return Nothing\n\n-- | Open the global configuration file\nopenGlobalConfig :: IO (Either GitError Config)\nopenGlobalConfig = alloca $ \\conf -> do\n res <- {#call git_config_open_global#} conf\n retEither res $ fmap (Right . Config) $ peek conf\n\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-- The string is owned by the variable and should not be freed by the user.\nconfigString :: Config -> String -> IO (Either GitError String)\nconfigString (Config c) vn = alloca $ \\out -> do\n vn' <- newCString vn\n res <- {#call git_config_get_string#} c vn' out\n retEither res $ fmap Right $ peekCString =<< peek out\n\n-- | Set the value of an integer config variable.\nsetConfigInt :: Config -> String -> Int -> IO (Maybe GitError)\nsetConfigInt conf vn val =\n mConfig {#call git_config_set_int#} conf vn (fromIntegral val)\n\n-- | Set the value of a long integer config variable.\nsetConfigInteger :: Config -> String -> Integer -> IO (Maybe GitError)\nsetConfigInteger conf vn val =\n mConfig {#call git_config_set_long#} conf vn (fromIntegral val)\n\n-- | Set the value of a boolean config variable.\nsetConfigBool :: Config -> String -> Bool -> IO (Maybe GitError)\nsetConfigBool conf vn val =\n mConfig {#call git_config_set_bool#} conf vn (fromBool val)\n\n-- | Set the value of a string config variable.\nsetConfigString :: Config -> String -> String -> IO (Maybe GitError)\nsetConfigString conf vn val =\n mConfig {#call git_config_set_string#} conf vn =<< newCString val\n\n-- | Delete a config variable\ndelConfig :: Config -> String -> IO (Maybe GitError)\ndelConfig (Config c) vn = do\n str <- newCString vn\n retMaybe =<< {#call git_config_delete#} c str\n\nmConfig :: (CPtr -> CString -> t -> IO CInt) -> Config -> String -> t\n -> IO (Maybe GitError)\nmConfig call (Config c) vn val = do\n str <- newCString vn\n retMaybe =<< call c str val\n\n-- TODO: foreachConfig :: Config ->\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Config where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Foreign\nimport Foreign.C\n\nnewtype Config = Config CPtr\n\n-- | Locate the path to the global configuration file\n--\n-- The user or global configuration file is usually located in\n-- `$HOME\/.gitconfig`.\n--\n-- This method will try to guess the full path to that file, if the file\n-- exists. The returned path may be used on any `git_config` call to load the\n-- global configuration file.\nfindGlobalConfig :: IO (Maybe String)\nfindGlobalConfig = alloca $ \\pth -> do\n res <- {#call git_config_find_global#} pth\n if res == 0\n then fmap Just $ peekCString pth\n else return Nothing\n\n-- | Open the global configuration file\nopenGlobalConfig :: IO (Either GitError Config)\nopenGlobalConfig = alloca $ \\conf -> do\n res <- {#call git_config_open_global#} conf\n retEither res $ fmap (Right . Config) $ peek conf\n\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-- The string is owned by the variable and should not be freed by the user.\nconfigString :: Config -> String -> IO (Either GitError String)\nconfigString (Config c) vn = alloca $ \\out -> do\n vn' <- newCString vn\n res <- {#call git_config_get_string#} c vn' out\n retEither res $ fmap Right $ peekCString =<< peek out\n\n-- | Set the value of an integer config variable.\nsetConfigInt :: Config -> String -> Int -> IO (Maybe GitError)\nsetConfigInt (Config c) vn val = do\n str <- newCString vn\n retMaybe =<< {#call git_config_set_int#} c str (fromIntegral val)\n\n-- | Set the value of a long integer config variable.\nsetConfigInteger :: Config -> String -> Integer -> IO (Maybe GitError)\nsetConfigInteger (Config c) vn val = do\n str <- newCString vn\n retMaybe =<< {#call git_config_set_long#} c str (fromIntegral val)\n\n-- | Set the value of a boolean config variable.\nsetConfigBool :: Config -> String -> Bool -> IO (Maybe GitError)\nsetConfigBool (Config c) vn val = do\n str <- newCString vn\n retMaybe =<< {#call git_config_set_bool#} c str (fromBool val)\n\n-- | Set the value of a string config variable.\nsetConfigString :: Config -> String -> String -> IO (Maybe GitError)\nsetConfigString (Config c) vn val = do\n str <- newCString vn\n vl' <- newCString val\n retMaybe =<< {#call git_config_set_string#} c str vl'\n\n-- | Delete a config variable\ndelConfig :: Config -> String -> IO (Maybe GitError)\ndelConfig (Config c) vn = do\n str <- newCString vn\n retMaybe =<< {#call git_config_delete#} c str\n\n-- TODO: foreachConfig :: Config ->\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"94e5b8c66b9bfe7aaf76e1f476bbd681f3ad6ea9","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\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException CantCreateMultipleGeomFields\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException CantCreateMultipleGeomFields\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5e8ff985cb3585e732fe88d8645e4409554e30fb","subject":"occupancy calculator magic values for compute 2.1 devices","message":"occupancy calculator magic values for compute 2.1 devices\n\nIgnore-this: 84ad2a849d2b3ff2942554bea700013f\n\ndarcs-hash:20110209211713-dcabc-6577e11113cbe33bc12fa16193ab485f195740e8.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute, ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..),\n resources\n )\n where\n\n#include \n\nimport Data.Int\nimport Data.Maybe\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability\n--\ntype Compute = Double\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Compute, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxBlockSize :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: (Int,Int),\n maxTextureDim3D :: (Int,Int,Int),\n#endif\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: Bool, -- ^ Device supports and has enabled error correction\n#endif\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: Int, -- ^ Warp size\n threadsPerMP :: Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: Int, -- ^ Maximum number of in-flight warps per multiprocessor\n sharedMemPerMP :: Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: Int, -- ^ Register allocation unit size\n regAllocWarp :: Int, -- ^ Register allocation granularity for warps\n allocation :: Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device\n-- TLM: default to highest compute capability, when no specific data available?\n--\nresources :: DeviceProperties -> DeviceResources\nresources dev = fromMaybe err (lookup compute gpuData)\n where\n compute = computeCapability dev\n err = error $ \"No data for device: \"\n ++ shows (deviceName dev) \" (compute \" ++ shows compute \")\"\n\n gpuData =\n [(1.0, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.1, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.2, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(1.3, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(2.0, DeviceResources 32 1536 8 48 49152 128 32768 64 1 Warp)\n ,(2.1, DeviceResources 32 1536 8 48 49152 128 32768 64 1 Warp)\n ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute, ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..),\n resources\n )\n where\n\n#include \n\nimport Data.Int\nimport Data.Maybe\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability\n--\ntype Compute = Double\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Compute, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxBlockSize :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: (Int,Int),\n maxTextureDim3D :: (Int,Int,Int),\n#endif\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: Bool, -- ^ Device supports and has enabled error correction\n#endif\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: Int, -- ^ Warp size\n threadsPerMP :: Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: Int, -- ^ Maximum number of in-flight warps per multiprocessor\n sharedMemPerMP :: Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: Int, -- ^ Register allocation unit size\n regAllocWarp :: Int, -- ^ Register allocation granularity for warps\n allocation :: Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device\n--\nresources :: DeviceProperties -> DeviceResources\nresources dev = fromMaybe err (lookup compute gpuData)\n where\n compute = computeCapability dev\n err = error $ \"No data for device: \"\n ++ shows (deviceName dev) \" (compute \" ++ shows compute \")\"\n\n gpuData =\n [(1.0, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.1, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.2, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(1.3, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(2.0, DeviceResources 32 1536 8 48 49152 128 32768 64 1 Warp)\n ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"fd8283e2f634d5cbac1dd8373eafa42fb0b6c68c","subject":"Don't bind attributes we don't understand.","message":"Don't bind attributes we don't understand.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"glib\/System\/Glib\/GValueTypes.chs","new_file":"glib\/System\/Glib\/GValueTypes.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetUChar,\n valueGetUChar,\n valueSetChar,\n valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue (fromIntegral value)\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n liftM fromIntegral $ {# call unsafe value_get_uchar #} gvalue\n\n--these belong somewhere else, are in new c2hs's C2HS module\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\n--valueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar :: GValue -> Char -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue (cFromEnum value)\n\n--valueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar :: GValue -> IO Char\nvalueGetChar gvalue =\n liftM cToEnum $ {# call unsafe value_get_char #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"756abe1fa9b2ec5b7e5ae4779a6b13673b0d1ad2","subject":"strictness","message":"strictness\n","repos":"nvidia-compiler-sdk\/hsnvvm","old_file":"Foreign\/LibNVVM\/Compile.chs","new_file":"Foreign\/LibNVVM\/Compile.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- |\n-- Module : Foreign.LibNVVM.Compile\n-- Copyright : 2012 Sean Lee\n-- 2014 Trevor L. McDonell\n-- License :\n--\n-- Maintainer : Sean Lee \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\nmodule Foreign.LibNVVM.Compile (\n\n -- * Compilation result\n Result(..), CompileFlag(..), VerifyFlag,\n\n -- * Compilation\n compileModule, compileModules,\n\n) where\n\nimport Prelude hiding ( log )\nimport Data.ByteString ( ByteString )\nimport Data.Word\nimport Control.Exception\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Unsafe as B\nimport qualified Data.ByteString.Internal as B\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Marshal\nimport Foreign.Storable\nimport Foreign.CUDA.Analysis\nimport Foreign.LibNVVM.Error\nimport Foreign.LibNVVM.Internal\n\n#include \n\n{# context lib=\"nvvm\" #}\n\n\n-- | The return type of compiling a module(s) is the compilation log together\n-- with the resulting binary ptx\/cubin.\n--\ndata Result = Result {\n -- | Any compilation or verification messages and warnings that were\n -- generated during compilation of the NVVM module. Note that even upon\n -- successful completion, the log may not be empty.\n --\n nvvmLog :: {-# UNPACK #-} !ByteString\n , nvvmResult :: {-# UNPACK #-} !ByteString\n }\n\n\n-- | An opaque handle to an NVVM program\n--\nnewtype Program = Program { useProgram :: {# type nvvmProgram #}}\n deriving (Eq, Show)\n\n\n-- | The available program compilation flags\n--\ndata CompileFlag\n -- | Level of optimisation to apply (0-3) (Default: 3)\n = OptimisationLevel !Int\n\n -- | Compute architecture to target (Default: Compute 2.0)\n | Target !Compute\n\n -- | Flush denormal values to zero when performing single-precision floating\n -- point operations (Default: preserve denormal values)\n | FlushToZero\n\n -- | Use a faster approximation for single-precision floating-point square\n -- root (Default: use IEEE round-to-nearest mode)\n | FastSqrt\n\n -- | Use a faster approximation for single-precision floating-point division\n -- and reciprocal operations (Default: use IEEE round-to-nearest mode)\n | FastDiv\n\n -- | Disable fused-multiply-add contraction (Default: enabled)\n | DisableFMA\n\n -- | Generate debugging symbols (-g) (Default: no)\n | GenerateDebugInfo\n\n\n-- | The available program verification flags\n--\ndata VerifyFlag\n\n\ncompileFlagToArg :: CompileFlag -> String\ncompileFlagToArg f =\n case f of\n OptimisationLevel o -> printf \"-opt=%d\" o\n Target (Compute n m) -> printf \"-arch=compute_%d%d\" n m\n FlushToZero -> \"-ftz=1\"\n FastSqrt -> \"-prec-sqrt=0\"\n FastDiv -> \"-prec-div=0\"\n DisableFMA -> \"-fma=0\"\n GenerateDebugInfo -> \"-g\"\n\n\nverifyFlagToArg :: VerifyFlag -> String\nverifyFlagToArg _ = error \"verifyFlagToArg\"\n\n\n-- High-level interface\n-- --------------------\n\n-- | Compile an NVVM IR module according to the specified options. If an error\n-- occurs an exception is thrown, otherwise the generated PTX is returned\n-- together with any warning or verification messages generated during\n-- compilation.\n--\n-- The input NVVM IR module can be either in the bitcode representation or the\n-- text representation.\n--\ncompileModule\n :: String -- ^ name of the module (optional)\n -> ByteString -- ^ module NVVM IR\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModule name bc = compileModules [(name,bc)]\n\n\n-- | Compile and link multiple NVVM IR modules together to form a single\n-- program. The compiled result is represented in PTX.\n--\n-- Each NVVM IR module may individually be in either the bitcode representation\n-- or in the text representation.\n--\ncompileModules\n :: [(String, ByteString)] -- ^ modules to compile and link\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModules modules opts verify =\n bracket create destroy $ \\prg -> do\n res <- try $ do\n mapM_ (uncurry (addModule prg)) modules\n when verify (verifyProgram prg [])\n compileProgram prg opts\n compilerResult prg\n log <- compilerLog prg\n case res of\n Left (err :: NVVMException) -> nvvmError (unlines [show err, B.unpack log])\n Right ptx -> return $! Result log ptx\n\n\n-- The raw interface to libNVVM\n-- ----------------------------\n\n-- | Create a new program handle\n--\ncreate :: IO Program\ncreate = resultIfOk =<< nvvmCreateProgram\n\n{-# INLINE nvvmCreateProgram #-}\n{# fun unsafe nvvmCreateProgram\n { alloca- `Program' peekProgram*\n }\n -> `Status' cToEnum #}\n where\n peekProgram = liftM Program . peek\n\n\n-- | Destroy a program handle\n--\ndestroy :: Program -> IO ()\ndestroy p = nothingIfOk =<< nvvmDestroyProgram p\n\n{-# INLINE nvvmDestroyProgram #-}\n{# fun unsafe nvvmDestroyProgram\n { withProgram* `Program' } -> `Status' cToEnum #}\n where\n withProgram = with . useProgram\n\n\n-- | Add an NVVM IR module to the given program compilation unit. An exception\n-- is raised if:\n--\n-- * The 'Program' to add to is invalid; or\n--\n-- * The NVVM module IR is invalid.\n--\naddModule :: Program -> String -> ByteString -> IO ()\naddModule prg name mdl =\n B.unsafeUseAsCStringLen mdl $ \\(b,n) -> do\n nothingIfOk =<< nvvmAddModuleToProgram prg b n name\n\n{-# INLINE nvvmAddModuleToProgram #-}\n{# fun unsafe nvvmAddModuleToProgram\n { useProgram `Program'\n , id `CString'\n , cIntConv `Int'\n , withCString'* `String'\n }\n -> `Status' cToEnum #}\n where\n withCString' [] f = f nullPtr -- defaults to \"\"\n withCString' s f = withCString s f\n\n\n-- | Compile the given 'Program' and all modules that have been previously added\n-- to it.\n--\ncompileProgram :: Program -> [CompileFlag] -> IO ()\ncompileProgram prg opts =\n bracket\n (mapM (newCString . compileFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmCompileProgram prg))\n\n{-# INLINE nvvmCompileProgram #-}\n{# fun unsafe nvvmCompileProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the result of compiling a 'Program' as a 'ByteString' containing\n-- the generated PTX. An exception is raised if the compilation unit is invalid.\n--\ncompilerResult :: Program -> IO ByteString\ncompilerResult prg = do\n n <- resultIfOk =<< nvvmGetCompiledResultSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetCompiledResult prg log\n return $! B.fromForeignPtr log 0 (n-1) -- size includes the NULL terminator\n\n{-# INLINE nvvmGetCompiledResult #-}\n{# fun unsafe nvvmGetCompiledResult\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetCompiledResultSize #-}\n{# fun unsafe nvvmGetCompiledResultSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the log of compiling a 'Program' as a 'ByteString'.\n--\ncompilerLog :: Program -> IO ByteString\ncompilerLog prg = do\n n <- resultIfOk =<< nvvmGetProgramLogSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetProgramLog prg log\n return $! B.fromForeignPtr log 0 (n-1) -- size includes the NULL terminator\n\n{-# INLINE nvvmGetProgramLog #-}\n{# fun unsafe nvvmGetProgramLog\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetProgramLogSize #-}\n{# fun unsafe nvvmGetProgramLogSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Verify the NVVM program. If an error is encountered, an exception is\n-- thrown.\n--\nverifyProgram :: Program -> [VerifyFlag] -> IO ()\nverifyProgram prg opts =\n bracket\n (mapM (newCString . verifyFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmVerifyProgram prg))\n\n{# fun unsafe nvvmVerifyProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- |\n-- Module : Foreign.LibNVVM.Compile\n-- Copyright : 2012 Sean Lee\n-- 2014 Trevor L. McDonell\n-- License :\n--\n-- Maintainer : Sean Lee \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\nmodule Foreign.LibNVVM.Compile (\n\n -- * Compilation result\n Result(..), CompileFlag(..), VerifyFlag,\n\n -- * Compilation\n compileModule, compileModules,\n\n) where\n\nimport Prelude hiding ( log )\nimport Data.ByteString ( ByteString )\nimport Data.Word\nimport Control.Exception\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Unsafe as B\nimport qualified Data.ByteString.Internal as B\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Marshal\nimport Foreign.Storable\nimport Foreign.CUDA.Analysis\nimport Foreign.LibNVVM.Error\nimport Foreign.LibNVVM.Internal\n\n#include \n\n{# context lib=\"nvvm\" #}\n\n\n-- | The return type of compiling a module(s) is the compilation log together\n-- with the resulting binary ptx\/cubin.\n--\ndata Result = Result {\n -- | Any compilation or verification messages and warnings that were\n -- generated during compilation of the NVVM module. Note that even upon\n -- successful completion, the log may not be empty.\n --\n nvvmLog :: {-# UNPACK #-} !ByteString\n , nvvmResult :: {-# UNPACK #-} !ByteString\n }\n\n\n-- | An opaque handle to an NVVM program\n--\nnewtype Program = Program { useProgram :: {# type nvvmProgram #}}\n deriving (Eq, Show)\n\n\n-- | The available program compilation flags\n--\ndata CompileFlag\n -- | Level of optimisation to apply (0-3) (Default: 3)\n = OptimisationLevel !Int\n\n -- | Compute architecture to target (Default: Compute 2.0)\n | Target !Compute\n\n -- | Flush denormal values to zero when performing single-precision floating\n -- point operations (Default: preserve denormal values)\n | FlushToZero\n\n -- | Use a faster approximation for single-precision floating-point square\n -- root (Default: use IEEE round-to-nearest mode)\n | FastSqrt\n\n -- | Use a faster approximation for single-precision floating-point division\n -- and reciprocal operations (Default: use IEEE round-to-nearest mode)\n | FastDiv\n\n -- | Disable fused-multiply-add contraction (Default: enabled)\n | DisableFMA\n\n -- | Generate debugging symbols (-g) (Default: no)\n | GenerateDebugInfo\n\n\n-- | The available program verification flags\n--\ndata VerifyFlag\n\n\ncompileFlagToArg :: CompileFlag -> String\ncompileFlagToArg f =\n case f of\n OptimisationLevel o -> printf \"-opt=%d\" o\n Target (Compute n m) -> printf \"-arch=compute_%d%d\" n m\n FlushToZero -> \"-ftz=1\"\n FastSqrt -> \"-prec-sqrt=0\"\n FastDiv -> \"-prec-div=0\"\n DisableFMA -> \"-fma=0\"\n GenerateDebugInfo -> \"-g\"\n\n\nverifyFlagToArg :: VerifyFlag -> String\nverifyFlagToArg _ = error \"verifyFlagToArg\"\n\n\n-- High-level interface\n-- --------------------\n\n-- | Compile an NVVM IR module according to the specified options. If an error\n-- occurs an exception is thrown, otherwise the generated PTX is returned\n-- together with any warning or verification messages generated during\n-- compilation.\n--\n-- The input NVVM IR module can be either in the bitcode representation or the\n-- text representation.\n--\ncompileModule\n :: String -- ^ name of the module (optional)\n -> ByteString -- ^ module NVVM IR\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModule name bc = compileModules [(name,bc)]\n\n\n-- | Compile and link multiple NVVM IR modules together to form a single\n-- program. The compiled result is represented in PTX.\n--\n-- Each NVVM IR module may individually be in either the bitcode representation\n-- or in the text representation.\n--\ncompileModules\n :: [(String, ByteString)] -- ^ modules to compile and link\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModules modules opts verify =\n bracket create destroy $ \\prg -> do\n res <- try $ do\n mapM_ (uncurry (addModule prg)) modules\n when verify (verifyProgram prg [])\n compileProgram prg opts\n compilerResult prg\n log <- compilerLog prg\n case res of\n Left (err :: NVVMException) -> nvvmError (unlines [show err, B.unpack log])\n Right ptx -> return $ Result log ptx\n\n\n-- The raw interface to libNVVM\n-- ----------------------------\n\n-- | Create a new program handle\n--\ncreate :: IO Program\ncreate = resultIfOk =<< nvvmCreateProgram\n\n{-# INLINE nvvmCreateProgram #-}\n{# fun unsafe nvvmCreateProgram\n { alloca- `Program' peekProgram*\n }\n -> `Status' cToEnum #}\n where\n peekProgram = liftM Program . peek\n\n\n-- | Destroy a program handle\n--\ndestroy :: Program -> IO ()\ndestroy p = nothingIfOk =<< nvvmDestroyProgram p\n\n{-# INLINE nvvmDestroyProgram #-}\n{# fun unsafe nvvmDestroyProgram\n { withProgram* `Program' } -> `Status' cToEnum #}\n where\n withProgram = with . useProgram\n\n\n-- | Add an NVVM IR module to the given program compilation unit. An exception\n-- is raised if:\n--\n-- * The 'Program' to add to is invalid; or\n--\n-- * The NVVM module IR is invalid.\n--\naddModule :: Program -> String -> ByteString -> IO ()\naddModule prg name mdl =\n B.unsafeUseAsCStringLen mdl $ \\(b,n) -> do\n nothingIfOk =<< nvvmAddModuleToProgram prg b n name\n\n{-# INLINE nvvmAddModuleToProgram #-}\n{# fun unsafe nvvmAddModuleToProgram\n { useProgram `Program'\n , id `CString'\n , cIntConv `Int'\n , withCString'* `String'\n }\n -> `Status' cToEnum #}\n where\n withCString' [] f = f nullPtr -- defaults to \"\"\n withCString' s f = withCString s f\n\n\n-- | Compile the given 'Program' and all modules that have been previously added\n-- to it.\n--\ncompileProgram :: Program -> [CompileFlag] -> IO ()\ncompileProgram prg opts =\n bracket\n (mapM (newCString . compileFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmCompileProgram prg))\n\n{-# INLINE nvvmCompileProgram #-}\n{# fun unsafe nvvmCompileProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the result of compiling a 'Program' as a 'ByteString' containing\n-- the generated PTX. An exception is raised if the compilation unit is invalid.\n--\ncompilerResult :: Program -> IO ByteString\ncompilerResult prg = do\n n <- resultIfOk =<< nvvmGetCompiledResultSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetCompiledResult prg log\n return $! B.fromForeignPtr log 0 (n-1) -- size includes the NULL terminator\n\n{-# INLINE nvvmGetCompiledResult #-}\n{# fun unsafe nvvmGetCompiledResult\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetCompiledResultSize #-}\n{# fun unsafe nvvmGetCompiledResultSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the log of compiling a 'Program' as a 'ByteString'.\n--\ncompilerLog :: Program -> IO ByteString\ncompilerLog prg = do\n n <- resultIfOk =<< nvvmGetProgramLogSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetProgramLog prg log\n return $! B.fromForeignPtr log 0 (n-1) -- size includes the NULL terminator\n\n{-# INLINE nvvmGetProgramLog #-}\n{# fun unsafe nvvmGetProgramLog\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetProgramLogSize #-}\n{# fun unsafe nvvmGetProgramLogSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Verify the NVVM program. If an error is encountered, an exception is\n-- thrown.\n--\nverifyProgram :: Program -> [VerifyFlag] -> IO ()\nverifyProgram prg opts =\n bracket\n (mapM (newCString . verifyFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmVerifyProgram prg))\n\n{# fun unsafe nvvmVerifyProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"ec9d972b1437fe63c661a896f09445776acf8d8a","subject":"Fix documenation to Editable.","message":"Fix documenation to Editable.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/Editable.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/Editable.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Interface Editable\n--\n-- Author : Axel Simon, Duncan Coutts\n--\n-- Created: 30 July 2004\n--\n-- Copyright (C) 1999-2005 Axel Simon, 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-- Interface for text-editing widgets\n--\nmodule Graphics.UI.Gtk.Entry.Editable (\n-- * Detail\n-- \n-- | The 'Editable' interface is an interface which should be implemented by\n-- text editing widgets, such as 'Entry'.\n-- It contains functions for generically manipulating an editable\n-- widget, a large number of action signals used for key bindings, and several\n-- signals that an application can connect to to modify the behavior of a\n-- widget.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | GInterface\n-- | +----Editable\n-- @\n\n-- * Types\n Editable,\n EditableClass,\n castToEditable, gTypeEditable,\n toEditable,\n\n-- * Methods\n editableSelectRegion,\n editableGetSelectionBounds,\n editableInsertText,\n editableDeleteText,\n editableGetChars,\n editableCutClipboard,\n editableCopyClipboard,\n editablePasteClipboard,\n editableDeleteSelection,\n editableSetEditable,\n editableGetEditable,\n editableSetPosition,\n editableGetPosition,\n\n-- * Attributes\n editablePosition,\n editableEditable,\n\n-- * Signals\n onEditableChanged,\n afterEditableChanged,\n onDeleteText,\n afterDeleteText,\n stopDeleteText,\n onInsertText,\n afterInsertText,\n stopInsertText\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Selects a region of text. The characters that are selected are those\n-- characters at positions from @startPos@ up to, but not including @endPos@.\n-- If @endPos@ is negative, then the the characters selected will be those\n-- characters from @startPos@ to the end of the text.\n--\n-- Calling this function with @start@=1 and @end@=4 it will mark \\\"ask\\\" in\n-- the string \\\"Haskell\\\".\n--\neditableSelectRegion :: EditableClass self => self\n -> Int -- ^ @start@ - the starting position.\n -> Int -- ^ @end@ - the end position.\n -> IO ()\neditableSelectRegion self start end =\n {# call editable_select_region #}\n (toEditable self)\n (fromIntegral start)\n (fromIntegral end)\n\n-- | Gets the current selection bounds, if there is a selection.\n--\neditableGetSelectionBounds :: EditableClass self => self\n -> IO (Int,Int) -- ^ @(start, end)@ - the starting and end positions. This\n -- pair is not ordered. The @end@ index represents the\n -- position of the cursor. The @start@ index is the other end\n -- of the selection. If both numbers are equal there is in\n -- fact no selection.\neditableGetSelectionBounds self =\n alloca $ \\startPtr ->\n alloca $ \\endPtr -> do\n {# call unsafe editable_get_selection_bounds #}\n (toEditable self)\n startPtr\n endPtr\n start <- liftM fromIntegral $ peek startPtr\n end <- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- | Inserts text at a given position.\n--\neditableInsertText :: EditableClass self => self\n -> String -- ^ @newText@ - the text to insert.\n -> Int -- ^ @position@ - the position at which to insert the text.\n -> IO Int -- ^ returns the position after the newly inserted text.\neditableInsertText self newText position = \n with (fromIntegral position) $ \\positionPtr ->\n withUTFStringLen newText $ \\(newTextPtr, newTextLength) -> do\n {# call editable_insert_text #}\n (toEditable self)\n newTextPtr\n (fromIntegral newTextLength)\n positionPtr\n position <- peek positionPtr\n return (fromIntegral position)\n\n-- | Deletes a sequence of characters. The characters that are deleted are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters deleted will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableDeleteText :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO ()\neditableDeleteText self startPos endPos =\n {# call editable_delete_text #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n\n-- | Retrieves a sequence of characters. The characters that are retrieved are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters retrieved will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableGetChars :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO String -- ^ returns the characters in the indicated region.\neditableGetChars self startPos endPos =\n {# call unsafe editable_get_chars #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n >>= readUTFString\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard and then deleted from the widget.\n--\neditableCutClipboard :: EditableClass self => self -> IO ()\neditableCutClipboard self =\n {# call editable_cut_clipboard #}\n (toEditable self)\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard.\n--\neditableCopyClipboard :: EditableClass self => self -> IO ()\neditableCopyClipboard self =\n {# call editable_copy_clipboard #}\n (toEditable self)\n\n-- | Causes the contents of the clipboard to be pasted into the given widget\n-- at the current cursor position.\n--\neditablePasteClipboard :: EditableClass self => self -> IO ()\neditablePasteClipboard self =\n {# call editable_paste_clipboard #}\n (toEditable self)\n\n-- | Deletes the current contents of the widgets selection and disclaims the\n-- selection.\n--\neditableDeleteSelection :: EditableClass self => self -> IO ()\neditableDeleteSelection self =\n {# call editable_delete_selection #}\n (toEditable self)\n\n-- | Sets the cursor position.\n--\neditableSetPosition :: EditableClass self => self\n -> Int -- ^ @position@ - the position of the cursor. The cursor is\n -- displayed before the character with the given (base 0) index in\n -- the widget. The value must be less than or equal to the number of\n -- characters in the widget. A value of -1 indicates that the\n -- position should be set after the last character in the entry.\n -> IO ()\neditableSetPosition self position =\n {# call editable_set_position #}\n (toEditable self)\n (fromIntegral position)\n\n-- | Retrieves the current cursor position.\n--\neditableGetPosition :: EditableClass self => self\n -> IO Int -- ^ returns the position of the cursor. The cursor is displayed\n -- before the character with the given (base 0) index in the widget.\n -- The value will be less than or equal to the number of characters\n -- in the widget. Note that this position is in characters, not in\n -- bytes.\neditableGetPosition self =\n liftM fromIntegral $\n {# call unsafe editable_get_position #}\n (toEditable self)\n\n-- | Determines if the user can edit the text in the editable widget or not.\n--\neditableSetEditable :: EditableClass self => self\n -> Bool -- ^ @isEditable@ - @True@ if the user is allowed to edit the text\n -- in the widget.\n -> IO ()\neditableSetEditable self isEditable =\n {# call editable_set_editable #}\n (toEditable self)\n (fromBool isEditable)\n\n-- | Retrieves whether the text is editable. See 'editableSetEditable'.\n--\neditableGetEditable :: EditableClass self => self -> IO Bool\neditableGetEditable self =\n liftM toBool $\n {# call editable_get_editable #}\n (toEditable self)\n\n--------------------\n-- Attributes\n\n-- | \\'position\\' property. See 'editableGetPosition' and\n-- 'editableSetPosition'\n--\neditablePosition :: EditableClass self => Attr self Int\neditablePosition = newAttr\n editableGetPosition\n editableSetPosition\n\n-- | \\'editable\\' property. See 'editableGetEditable' and\n-- 'editableSetEditable'\n--\neditableEditable :: EditableClass self => Attr self Bool\neditableEditable = newAttr\n editableGetEditable\n editableSetEditable\n\n--------------------\n-- Signals\n\n-- | The 'onEditableChanged' signal is emitted at the end of a single\n-- user-visible operation on the contents of the 'Editable'.\n--\n-- * For inctance, a paste operation that replaces the contents of the\n-- selection will cause only one signal emission (even though it is\n-- implemented by first deleting the selection, then inserting the new\n-- content, and may cause multiple 'onEditableInserText' signals to be\n-- emitted).\n--\nonEditableChanged, afterEditableChanged :: EditableClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEditableChanged = connect_NONE__NONE \"changed\" False\nafterEditableChanged = connect_NONE__NONE \"changed\" True\n\n-- | Emitted when a piece of text is deleted from the 'Editable' widget.\n--\n-- * See 'onInsertText' for information on how to use this signal.\n--\nonDeleteText, afterDeleteText :: EditableClass self => self\n -> (Int -> Int -> IO ()) -- ^ @(\\startPos endPos -> ...)@\n -> IO (ConnectId self)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- | Stop the current signal that deletes text.\nstopDeleteText :: EditableClass self => ConnectId self -> IO ()\nstopDeleteText (ConnectId _ obj) =\n signalStopEmission obj \"delete_text\"\n\n-- | Emitted when a piece of text is inserted into the 'Editable' widget.\n--\n-- * The connected signal receives the text that is inserted, together with\n-- the position in the entry widget. The return value should be the position\n-- in the entry widget that lies past the recently inserted text (i.e.\n-- you should return the given position plus the length of the string).\n--\n-- * To modify the text that the user inserts, you need to connect to this\n-- signal, modify the text the way you want and then call\n-- 'editableInsertText'. To avoid that this signal handler is called\n-- recursively, you need to temporarily block it using\n-- 'signalBlock'. After the default signal\n-- handler has inserted your modified text, it is important that you\n-- prevent the default handler from being executed again when this signal\n-- handler returns. To stop the current signal, use 'stopInsertText'.\n-- The following code is an example of how to turn all input into uppercase:\n--\n-- > idRef <- newIORef undefined\n-- > id <- onInsertText entry $ \\str pos -> do\n-- > id <- readIORef idRef\n-- > signalBlock id\n-- > pos' <- editableInsertText entry (map toUpper str) pos\n-- > signalUnblock id\n-- > stopInsertText id\n-- > return pos'\n-- > writeIORef idRef id\n--\n-- Note that the 'afterInsertText' function is not very useful, except to\n-- track editing actions.\n--\nonInsertText, afterInsertText :: EditableClass self => self\n -> (String -> Int -> IO Int)\n -> IO (ConnectId self)\nonInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" False obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\nafterInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" True obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\n\n-- | Stop the current signal that inserts text.\nstopInsertText :: EditableClass self => ConnectId self -> IO ()\nstopInsertText (ConnectId _ obj) =\n signalStopEmission obj \"insert_text\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Interface Editable\n--\n-- Author : Axel Simon, Duncan Coutts\n--\n-- Created: 30 July 2004\n--\n-- Copyright (C) 1999-2005 Axel Simon, 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-- Interface for text-editing widgets\n--\nmodule Graphics.UI.Gtk.Entry.Editable (\n-- * Detail\n-- \n-- | The 'Editable' interface is an interface which should be implemented by\n-- text editing widgets, such as 'Entry'.\n-- It contains functions for generically manipulating an editable\n-- widget, a large number of action signals used for key bindings, and several\n-- signals that an application can connect to to modify the behavior of a\n-- widget.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | GInterface\n-- | +----Editable\n-- @\n\n-- * Types\n Editable,\n EditableClass,\n castToEditable, gTypeEditable,\n toEditable,\n\n-- * Methods\n editableSelectRegion,\n editableGetSelectionBounds,\n editableInsertText,\n editableDeleteText,\n editableGetChars,\n editableCutClipboard,\n editableCopyClipboard,\n editablePasteClipboard,\n editableDeleteSelection,\n editableSetEditable,\n editableGetEditable,\n editableSetPosition,\n editableGetPosition,\n\n-- * Attributes\n editablePosition,\n editableEditable,\n\n-- * Signals\n onEditableChanged,\n afterEditableChanged,\n onDeleteText,\n afterDeleteText,\n stopDeleteText,\n onInsertText,\n afterInsertText,\n stopInsertText\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Selects a region of text. The characters that are selected are those\n-- characters at positions from @startPos@ up to, but not including @endPos@.\n-- If @endPos@ is negative, then the the characters selected will be those\n-- characters from @startPos@ to the end of the text.\n--\n-- Calling this function with @start@=1 and @end@=4 it will mark \\\"ask\\\" in\n-- the string \\\"Haskell\\\".\n--\neditableSelectRegion :: EditableClass self => self\n -> Int -- ^ @start@ - the starting position.\n -> Int -- ^ @end@ - the end position.\n -> IO ()\neditableSelectRegion self start end =\n {# call editable_select_region #}\n (toEditable self)\n (fromIntegral start)\n (fromIntegral end)\n\n-- | Gets the current selection bounds, if there is a selection.\n--\neditableGetSelectionBounds :: EditableClass self => self\n -> IO (Int,Int) -- ^ @(start, end)@ - the starting and end positions. This\n -- pair is not ordered. The @end@ index represents the\n -- position of the cursor. The @start@ index is the other end\n -- of the selection. If both numbers are equal there is in\n -- fact no selection.\neditableGetSelectionBounds self =\n alloca $ \\startPtr ->\n alloca $ \\endPtr -> do\n {# call unsafe editable_get_selection_bounds #}\n (toEditable self)\n startPtr\n endPtr\n start <- liftM fromIntegral $ peek startPtr\n end <- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- | Inserts text at a given position.\n--\neditableInsertText :: EditableClass self => self\n -> String -- ^ @newText@ - the text to insert.\n -> Int -- ^ @position@ - the position at which to insert the text.\n -> IO Int -- ^ returns the position after the newly inserted text.\neditableInsertText self newText position = \n with (fromIntegral position) $ \\positionPtr ->\n withUTFStringLen newText $ \\(newTextPtr, newTextLength) -> do\n {# call editable_insert_text #}\n (toEditable self)\n newTextPtr\n (fromIntegral newTextLength)\n positionPtr\n position <- peek positionPtr\n return (fromIntegral position)\n\n-- | Deletes a sequence of characters. The characters that are deleted are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters deleted will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableDeleteText :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO ()\neditableDeleteText self startPos endPos =\n {# call editable_delete_text #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n\n-- | Retrieves a sequence of characters. The characters that are retrieved are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters retrieved will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableGetChars :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO String -- ^ returns the characters in the indicated region.\neditableGetChars self startPos endPos =\n {# call unsafe editable_get_chars #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n >>= readUTFString\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard and then deleted from the widget.\n--\neditableCutClipboard :: EditableClass self => self -> IO ()\neditableCutClipboard self =\n {# call editable_cut_clipboard #}\n (toEditable self)\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard.\n--\neditableCopyClipboard :: EditableClass self => self -> IO ()\neditableCopyClipboard self =\n {# call editable_copy_clipboard #}\n (toEditable self)\n\n-- | Causes the contents of the clipboard to be pasted into the given widget\n-- at the current cursor position.\n--\neditablePasteClipboard :: EditableClass self => self -> IO ()\neditablePasteClipboard self =\n {# call editable_paste_clipboard #}\n (toEditable self)\n\n-- | Deletes the current contents of the widgets selection and disclaims the\n-- selection.\n--\neditableDeleteSelection :: EditableClass self => self -> IO ()\neditableDeleteSelection self =\n {# call editable_delete_selection #}\n (toEditable self)\n\n-- | Sets the cursor position.\n--\neditableSetPosition :: EditableClass self => self\n -> Int -- ^ @position@ - the position of the cursor. The cursor is\n -- displayed before the character with the given (base 0) index in\n -- the widget. The value must be less than or equal to the number of\n -- characters in the widget. A value of -1 indicates that the\n -- position should be set after the last character in the entry.\n -> IO ()\neditableSetPosition self position =\n {# call editable_set_position #}\n (toEditable self)\n (fromIntegral position)\n\n-- | Retrieves the current cursor position.\n--\neditableGetPosition :: EditableClass self => self\n -> IO Int -- ^ returns the position of the cursor. The cursor is displayed\n -- before the character with the given (base 0) index in the widget.\n -- The value will be less than or equal to the number of characters\n -- in the widget. Note that this position is in characters, not in\n -- bytes.\neditableGetPosition self =\n liftM fromIntegral $\n {# call unsafe editable_get_position #}\n (toEditable self)\n\n-- | Determines if the user can edit the text in the editable widget or not.\n--\neditableSetEditable :: EditableClass self => self\n -> Bool -- ^ @isEditable@ - @True@ if the user is allowed to edit the text\n -- in the widget.\n -> IO ()\neditableSetEditable self isEditable =\n {# call editable_set_editable #}\n (toEditable self)\n (fromBool isEditable)\n\n-- | Retrieves whether the text is editable. See 'editableSetEditable'.\n--\neditableGetEditable :: EditableClass self => self -> IO Bool\neditableGetEditable self =\n liftM toBool $\n {# call editable_get_editable #}\n (toEditable self)\n\n--------------------\n-- Attributes\n\n-- | \\'position\\' property. See 'editableGetPosition' and\n-- 'editableSetPosition'\n--\neditablePosition :: EditableClass self => Attr self Int\neditablePosition = newAttr\n editableGetPosition\n editableSetPosition\n\n-- | \\'editable\\' property. See 'editableGetEditable' and\n-- 'editableSetEditable'\n--\neditableEditable :: EditableClass self => Attr self Bool\neditableEditable = newAttr\n editableGetEditable\n editableSetEditable\n\n--------------------\n-- Signals\n\n-- | Emitted when the settings of the 'Editable' widget changes.\n--\nonEditableChanged, afterEditableChanged :: EditableClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEditableChanged = connect_NONE__NONE \"changed\" False\nafterEditableChanged = connect_NONE__NONE \"changed\" True\n\n-- | Emitted when a piece of text is deleted from the 'Editable' widget.\n--\n-- * See 'onInsertText' for information on how to use this signal.\n--\nonDeleteText, afterDeleteText :: EditableClass self => self\n -> (Int -> Int -> IO ()) -- ^ @(\\startPos endPos -> ...)@\n -> IO (ConnectId self)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- | Stop the current signal that deletes text.\nstopDeleteText :: EditableClass self => ConnectId self -> IO ()\nstopDeleteText (ConnectId _ obj) =\n signalStopEmission obj \"delete_text\"\n\n-- | Emitted when a piece of text is inserted into the 'Editable' widget.\n--\n-- * The connected signal receives the text that is inserted, together with\n-- the position in the entry widget. The return value should be the position\n-- in the entry widget that lies past the recently inserted text (i.e.\n-- you should return the given position plus the length of the string).\n--\n-- * To modify the text that the user inserts, you need to connect to this\n-- signal, modify the text the way you want and then call\n-- 'editableInsertText'. To avoid that this signal handler is called\n-- recursively, you need to temporarily block it using\n-- 'signalBlock'. After the default signal\n-- handler has inserted your modified text, it is important that you\n-- prevent the default handler from being executed again when this signal\n-- handler returns. To stop the current signal, use 'stopInsertText'.\n-- The following code is an example of how to turn all input into uppercase:\n--\n-- > idRef <- newIORef undefined\n-- > id <- onInsertText entry $ \\str pos -> do\n-- > id <- readIORef idRef\n-- > signalBlock id\n-- > pos' <- editableInsertText entry (map toUpper str) pos\n-- > signalUnblock id\n-- > stopInsertText id\n-- > return pos'\n-- > writeIORef idRef id\n--\n-- Note that the 'afterInsertText' function is not very useful, except to\n-- track editing actions.\n--\nonInsertText, afterInsertText :: EditableClass self => self\n -> (String -> Int -> IO Int)\n -> IO (ConnectId self)\nonInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" False obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\nafterInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" True obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\n\n-- | Stop the current signal that inserts text.\nstopInsertText :: EditableClass self => ConnectId self -> IO ()\nstopInsertText (ConnectId _ obj) =\n signalStopEmission obj \"insert_text\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"bb4da3618f40ae71568efb205019b43e68dabb6a","subject":"Use 'SourceUndoManagerClass sum => sum' replace SourceUndoManager as function argument.","message":"Use 'SourceUndoManagerClass sum => sum' replace SourceUndoManager as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceUndoManager.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceUndoManager.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceUndoManager\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceUndoManager (\n-- * Description\n-- | The 'SourceUndoManager' interface can be implemented to provide custom undo management to a\n-- 'SourceBuffer'. Use 'sourceBufferSetUndoManager' to install a custom undo manager for a\n-- particular source buffer.\n-- \n-- Use 'sourceUndoManagerCanUndoChanged' and 'sourceUndoManagerCanRedoChanged' when\n-- respectively the undo state or redo state of the undo stack has changed.\n\n-- * Types \n SourceUndoManager,\n SourceUndoManagerClass,\n \n-- * Methods \n sourceUndoManagerCanUndo,\n sourceUndoManagerCanRedo,\n sourceUndoManagerUndo,\n sourceUndoManagerRedo,\n sourceUndoManagerBeginNotUndoableAction,\n sourceUndoManagerEndNotUndoableAction,\n\n-- * Signals\n sourceUndoManagerCanRedoChanged,\n sourceUndoManagerCanUndoChanged,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get whether there are undo operations available.\nsourceUndoManagerCanUndo :: SourceUndoManagerClass sum => sum\n -> IO Bool -- ^ returns 'True' if there are undo operations available, 'False' otherwise \nsourceUndoManagerCanUndo sm =\n liftM toBool $\n {#call gtk_source_undo_manager_can_undo #} (toSourceUndoManager sm)\n\n-- | Get whether there are redo operations available.\nsourceUndoManagerCanRedo :: SourceUndoManagerClass sum => sum\n -> IO Bool -- ^ returns 'True' if there are redo operations available, 'False' otherwise \nsourceUndoManagerCanRedo sm =\n liftM toBool $\n {#call gtk_source_undo_manager_can_redo #} (toSourceUndoManager sm)\n\n-- | Perform a single undo. Calling this function when there are no undo operations available is an\n-- error. Use @gtkSourceUndoManagerCanUndo@ to find out if there are undo operations available.\nsourceUndoManagerUndo :: SourceUndoManagerClass sum => sum -> IO ()\nsourceUndoManagerUndo sm =\n {#call gtk_source_undo_manager_undo #} (toSourceUndoManager sm)\n\n-- | Perform a single redo. Calling this function when there are no redo operations available is an\n-- error. Use @gtkSourceUndoManagerCanRedo@ to find out if there are redo operations available.\nsourceUndoManagerRedo :: SourceUndoManagerClass sum => sum -> IO ()\nsourceUndoManagerRedo sm =\n {#call gtk_source_undo_manager_redo #} (toSourceUndoManager sm)\n\n-- | Begin a not undoable action on the buffer. All changes between this call and the call to\n-- @gtkSourceUndoManagerEndNotUndoableAction@ cannot be undone. This function should be\n-- re-entrant.\nsourceUndoManagerBeginNotUndoableAction :: SourceUndoManagerClass sum => sum -> IO ()\nsourceUndoManagerBeginNotUndoableAction sm =\n {#call gtk_source_undo_manager_begin_not_undoable_action #} (toSourceUndoManager sm)\n\n-- | Ends a not undoable action on the buffer.\nsourceUndoManagerEndNotUndoableAction :: SourceUndoManagerClass sum => sum -> IO ()\nsourceUndoManagerEndNotUndoableAction sm =\n {#call gtk_source_undo_manager_end_not_undoable_action #} (toSourceUndoManager sm)\n\n-- | Emitted when the ability to redo has changed.\n--\nsourceUndoManagerCanRedoChanged :: SourceUndoManagerClass sum => Signal sum (IO ())\nsourceUndoManagerCanRedoChanged = Signal $ connect_NONE__NONE \"can-redo-changed\"\n\n-- | Emitted when the ability to undo has changed.\n--\nsourceUndoManagerCanUndoChanged :: SourceUndoManagerClass sum => Signal sum (IO ())\nsourceUndoManagerCanUndoChanged = Signal $ connect_NONE__NONE \"can-undo-changed\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceUndoManager\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceUndoManager (\n-- * Description\n-- | The 'SourceUndoManager' interface can be implemented to provide custom undo management to a\n-- 'SourceBuffer'. Use 'sourceBufferSetUndoManager' to install a custom undo manager for a\n-- particular source buffer.\n-- \n-- Use 'sourceUndoManagerCanUndoChanged' and 'sourceUndoManagerCanRedoChanged' when\n-- respectively the undo state or redo state of the undo stack has changed.\n\n-- * Types \n SourceUndoManager,\n \n-- * Methods \n sourceUndoManagerCanUndo,\n sourceUndoManagerCanRedo,\n sourceUndoManagerUndo,\n sourceUndoManagerRedo,\n sourceUndoManagerBeginNotUndoableAction,\n sourceUndoManagerEndNotUndoableAction,\n\n-- * Signals\n sourceUndoManagerCanRedoChanged,\n sourceUndoManagerCanUndoChanged,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get whether there are undo operations available.\nsourceUndoManagerCanUndo :: SourceUndoManager\n -> IO Bool -- ^ returns 'True' if there are undo operations available, 'False' otherwise \nsourceUndoManagerCanUndo sm =\n liftM toBool $\n {#call gtk_source_undo_manager_can_undo #} sm\n\n-- | Get whether there are redo operations available.\nsourceUndoManagerCanRedo :: SourceUndoManager\n -> IO Bool -- ^ returns 'True' if there are redo operations available, 'False' otherwise \nsourceUndoManagerCanRedo sm =\n liftM toBool $\n {#call gtk_source_undo_manager_can_redo #} sm\n\n-- | Perform a single undo. Calling this function when there are no undo operations available is an\n-- error. Use @gtkSourceUndoManagerCanUndo@ to find out if there are undo operations available.\nsourceUndoManagerUndo :: SourceUndoManager -> IO ()\nsourceUndoManagerUndo sm =\n {#call gtk_source_undo_manager_undo #} sm\n\n-- | Perform a single redo. Calling this function when there are no redo operations available is an\n-- error. Use @gtkSourceUndoManagerCanRedo@ to find out if there are redo operations available.\nsourceUndoManagerRedo :: SourceUndoManager -> IO ()\nsourceUndoManagerRedo sm =\n {#call gtk_source_undo_manager_redo #} sm\n\n-- | Begin a not undoable action on the buffer. All changes between this call and the call to\n-- @gtkSourceUndoManagerEndNotUndoableAction@ cannot be undone. This function should be\n-- re-entrant.\nsourceUndoManagerBeginNotUndoableAction :: SourceUndoManager -> IO ()\nsourceUndoManagerBeginNotUndoableAction sm =\n {#call gtk_source_undo_manager_begin_not_undoable_action #} sm\n\n-- | Ends a not undoable action on the buffer.\nsourceUndoManagerEndNotUndoableAction :: SourceUndoManager -> IO ()\nsourceUndoManagerEndNotUndoableAction sm =\n {#call gtk_source_undo_manager_end_not_undoable_action #} sm\n\n-- | Emitted when the ability to redo has changed.\n--\nsourceUndoManagerCanRedoChanged :: Signal SourceUndoManager (IO ())\nsourceUndoManagerCanRedoChanged = Signal $ connect_NONE__NONE \"can-redo-changed\"\n\n-- | Emitted when the ability to undo has changed.\n--\nsourceUndoManagerCanUndoChanged :: Signal SourceUndoManager (IO ())\nsourceUndoManagerCanUndoChanged = Signal $ connect_NONE__NONE \"can-undo-changed\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"97f076597117e1ea8bd8621fd6a03d84df6816ac","subject":"use withArrayLen to avoid a second list traversal","message":"use withArrayLen to avoid a second list traversal\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module\/Base.chs","new_file":"Foreign\/CUDA\/Driver\/Module\/Base.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module.Base\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Module loading for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module.Base (\n\n -- * Module Management\n Module(..),\n JITOption(..), JITTarget(..), JITResult(..), JITFallback(..),\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload,\n\n -- Internal\n jitOptionUnpack, jitTargetOfCompute,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\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\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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 , CU_PREFER_PTX as PTX }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n\n--------------------------------------------------------------------------------\n-- Module management\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--\n-- \n--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n let logSize = 2048\n\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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))\n ]\n ++\n map jitOptionUnpack options\n\n withArrayLen (map cFromEnum opt) $ \\i p_opts -> do\n withArray (map unsafeCoerce val) $ \\ p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img i p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context.\n--\n-- \n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n\n{-# INLINE jitOptionUnpack #-}\njitOptionUnpack :: JITOption -> (JITOptionInternal, Int)\njitOptionUnpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\njitOptionUnpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\njitOptionUnpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\njitOptionUnpack (Target x) = (JIT_TARGET, fromEnum (jitTargetOfCompute x))\njitOptionUnpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\njitOptionUnpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\njitOptionUnpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\njitOptionUnpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n#else\njitOptionUnpack GenerateDebugInfo = requireSDK 'GenerateDebugInfo 5.5\njitOptionUnpack GenerateLineInfo = requireSDK 'GenerateLineInfo 5.5\njitOptionUnpack Verbose = requireSDK 'Verbose 5.5\n#endif\n\n\n{-# INLINE jitTargetOfCompute #-}\njitTargetOfCompute :: Compute -> JITTarget\njitTargetOfCompute (Compute 1 0) = Compute10\njitTargetOfCompute (Compute 1 1) = Compute11\njitTargetOfCompute (Compute 1 2) = Compute12\njitTargetOfCompute (Compute 1 3) = Compute13\njitTargetOfCompute (Compute 2 0) = Compute20\njitTargetOfCompute (Compute 2 1) = Compute21\njitTargetOfCompute (Compute 3 0) = Compute30\njitTargetOfCompute (Compute 3 5) = Compute35\n#if CUDA_VERSION >= 6000\njitTargetOfCompute (Compute 3 2) = Compute32\njitTargetOfCompute (Compute 5 0) = Compute50\n#endif\n#if CUDA_VERSION >= 6050\njitTargetOfCompute (Compute 3 7) = Compute37\n#endif\n#if CUDA_VERSION >= 7000\njitTargetOfCompute (Compute 5 2) = Compute52\n#endif\njitTargetOfCompute compute = error (\"Unknown JIT Target for Compute \" ++ show compute)\n\n\n{-# INLINE c_strnlen' #-}\n#if defined(WIN32)\nc_strnlen' :: CString -> CSize -> IO CSize\nc_strnlen' str size = do\n str' <- peekCStringLen (str, fromIntegral size)\n return $ stringLen 0 str'\n where\n stringLen acc [] = acc\n stringLen acc ('\\0':_) = acc\n stringLen acc (_:xs) = stringLen (acc+1) xs\n#else\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n#endif\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module.Base\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Module loading for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module.Base (\n\n -- * Module Management\n Module(..),\n JITOption(..), JITTarget(..), JITResult(..), JITFallback(..),\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload,\n\n -- Internal\n jitOptionUnpack, jitTargetOfCompute,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\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\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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 , CU_PREFER_PTX as PTX }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n\n--------------------------------------------------------------------------------\n-- Module management\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--\n-- \n--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n let logSize = 2048\n\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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))\n ]\n ++\n map jitOptionUnpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context.\n--\n-- \n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n\n{-# INLINE jitOptionUnpack #-}\njitOptionUnpack :: JITOption -> (JITOptionInternal, Int)\njitOptionUnpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\njitOptionUnpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\njitOptionUnpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\njitOptionUnpack (Target x) = (JIT_TARGET, fromEnum (jitTargetOfCompute x))\njitOptionUnpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\njitOptionUnpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\njitOptionUnpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\njitOptionUnpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n#else\njitOptionUnpack GenerateDebugInfo = requireSDK 'GenerateDebugInfo 5.5\njitOptionUnpack GenerateLineInfo = requireSDK 'GenerateLineInfo 5.5\njitOptionUnpack Verbose = requireSDK 'Verbose 5.5\n#endif\n\n\n{-# INLINE jitTargetOfCompute #-}\njitTargetOfCompute :: Compute -> JITTarget\njitTargetOfCompute (Compute 1 0) = Compute10\njitTargetOfCompute (Compute 1 1) = Compute11\njitTargetOfCompute (Compute 1 2) = Compute12\njitTargetOfCompute (Compute 1 3) = Compute13\njitTargetOfCompute (Compute 2 0) = Compute20\njitTargetOfCompute (Compute 2 1) = Compute21\njitTargetOfCompute (Compute 3 0) = Compute30\njitTargetOfCompute (Compute 3 5) = Compute35\n#if CUDA_VERSION >= 6000\njitTargetOfCompute (Compute 3 2) = Compute32\njitTargetOfCompute (Compute 5 0) = Compute50\n#endif\n#if CUDA_VERSION >= 6050\njitTargetOfCompute (Compute 3 7) = Compute37\n#endif\n#if CUDA_VERSION >= 7000\njitTargetOfCompute (Compute 5 2) = Compute52\n#endif\njitTargetOfCompute compute = error (\"Unknown JIT Target for Compute \" ++ show compute)\n\n\n{-# INLINE c_strnlen' #-}\n#if defined(WIN32)\nc_strnlen' :: CString -> CSize -> IO CSize\nc_strnlen' str size = do\n str' <- peekCStringLen (str, fromIntegral size)\n return $ stringLen 0 str'\n where\n stringLen acc [] = acc\n stringLen acc ('\\0':_) = acc\n stringLen acc (_:xs) = stringLen (acc+1) xs\n#else\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n#endif\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9248cf0a8b35fe5c5076b3008715817b0634b0a6","subject":"Add function sourceCompletionShow","message":"Add function sourceCompletionShow\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionGetInfoWindow,\n sourceCompletionCreateContext,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\nsourceCompletionShow :: SourceCompletionClass sc => sc\n -> [SourceCompletionProvider] -- ^ @providers@ A list of 'SourceCompletionProvider' \n -> SourceCompletionContext -- ^ @context@ The 'SourceCompletionContext' with which to start the completion\n -> IO Bool -- ^ returns 'True' if it was possible to the show completion window. \nsourceCompletionShow sc providers context =\n liftM toBool $\n withForeignPtrs (map unSourceCompletionProvider providers) $ \\providersPtr ->\n withGList providersPtr $ \\glist ->\n {#call gtk_source_completion_show #}\n (toSourceCompletion sc)\n glist\n context\n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | The info widget is the window where the completion displays optional extra information of the\n-- proposal.\nsourceCompletionGetInfoWindow :: SourceCompletionClass sc => sc -> IO SourceCompletionInfo\nsourceCompletionGetInfoWindow sc =\n makeNewObject mkSourceCompletionInfo $\n {#call gtk_source_completion_get_info_window #}\n (toSourceCompletion sc)\n\n-- | Create a new 'SourceCompletionContext' for completion. The position at which the completion using\n-- the new context will consider completion can be provider by position. If position is 'Nothing', the\n-- current cursor position will be used.\nsourceCompletionCreateContext :: SourceCompletionClass sc => sc\n -> Maybe TextIter\n -> IO SourceCompletionContext\nsourceCompletionCreateContext sc iter = \n makeNewGObject mkSourceCompletionContext $\n {#call gtk_source_completion_create_context #}\n (toSourceCompletion sc)\n (fromMaybe (TextIter nullForeignPtr) iter)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate_proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move_cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move_page\"\n\n-- | Emitted just before starting to populate the completion with providers. You can use this signal to\n-- add additional attributes in the context.\nsourceCompletionPopulateContext :: SourceCompletionClass sc => Signal sc (SourceCompletionContext -> IO ())\nsourceCompletionPopulateContext = Signal $ connect_OBJECT__NONE \"populate_context\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n -- sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionGetInfoWindow,\n sourceCompletionCreateContext,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\n-- sourceCompletionShow :: SourceCompletionClass sc => sc\n-- -> [SourceCompletionProvider]\n-- -> \n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | The info widget is the window where the completion displays optional extra information of the\n-- proposal.\nsourceCompletionGetInfoWindow :: SourceCompletionClass sc => sc -> IO SourceCompletionInfo\nsourceCompletionGetInfoWindow sc =\n makeNewObject mkSourceCompletionInfo $\n {#call gtk_source_completion_get_info_window #}\n (toSourceCompletion sc)\n\n-- | Create a new 'SourceCompletionContext' for completion. The position at which the completion using\n-- the new context will consider completion can be provider by position. If position is 'Nothing', the\n-- current cursor position will be used.\nsourceCompletionCreateContext :: SourceCompletionClass sc => sc\n -> Maybe TextIter\n -> IO SourceCompletionContext\nsourceCompletionCreateContext sc iter = \n makeNewGObject mkSourceCompletionContext $\n {#call gtk_source_completion_create_context #}\n (toSourceCompletion sc)\n (fromMaybe (TextIter nullForeignPtr) iter)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate_proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move_cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move_page\"\n\n-- | Emitted just before starting to populate the completion with providers. You can use this signal to\n-- add additional attributes in the context.\nsourceCompletionPopulateContext :: SourceCompletionClass sc => Signal sc (SourceCompletionContext -> IO ())\nsourceCompletionPopulateContext = Signal $ connect_OBJECT__NONE \"populate_context\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0779ce2072ed6b555a9a000e10d7a7cbed45ebde","subject":"Export CLMapFlag and constructors.","message":"Export CLMapFlag and constructors.\n","repos":"Delan90\/opencl,IFCA\/opencl,Delan90\/opencl,IFCA\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.chs","new_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.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.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), CLMapFlag(..),\n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\n clEnqueueUnmapMemObject,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n \n{-| Enqueues a command to unmap a previously mapped region of a memory object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\nReads or writes from the host using the pointer returned by 'clEnqueueMapBuffer'\nor 'clEnqueueMapImage' are considered to be complete.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' increments the mapped count of the\nmemory object. The initial mapped count value of a memory object is\nzero. Multiple calls to 'clEnqueueMapBuffer' or 'clEnqueueMapImage' on the same\nmemory object will increment this mapped count by appropriate number of\ncalls. 'clEnqueueUnmapMemObject' decrements the mapped count of the memory\nobject.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' act as synchronization points for a\nregion of the memory object being mapped.\n\n'clEnqueueUnmapMemObject' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\n\n * CL_INVALID_COMMAND_QUEUE if command_queue is not a valid command-queue.\n\n * CL_INVALID_MEM_OBJECT if memobj is not a valid memory object.\n\n * CL_INVALID_VALUE if mapped_ptr is not a valid pointer returned by\n'clEnqueueMapBuffer' or 'clEnqueueMapImage' for memobj.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n * CL_INVALID_CONTEXT if the context associated with command_queue and memobj\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n-}\nclEnqueueUnmapMemObject :: CLCommandQueue \n -> CLMem -- ^ A valid memory object. The OpenCL\n -- context associated with command_queue and\n -- memobj must be the same.\n -> Ptr () -- ^ The host address returned by a\n -- previous call to 'clEnqueueMapBuffer' or\n -- 'clEnqueueMapImage' for memobj.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before\n -- 'clEnqueueUnmapMemObject' can be\n -- executed. If event_wait_list is\n -- empty, then 'clEnqueueUnmapMemObject'\n -- does not wait on any event to\n -- complete. The events specified in\n -- event_wait_list act as\n -- synchronization points. The context\n -- associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n\n -> IO CLEvent\nclEnqueueUnmapMemObject cq mem pp = clEnqueue (raw_clEnqueueUnmapMemObject cq mem pp)\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (map fromIntegral lws) $ \\plws -> do\n clEnqueue (raw_clEnqueueNDRangeKernel cq krn num nullPtr pgws plws) events\n where\n num = fromIntegral $ length gws\n withMaybeArray [] = ($ nullPtr)\n withMaybeArray xs = withArray xs\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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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":"{- 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.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, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\n clEnqueueUnmapMemObject,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n \n{-| Enqueues a command to unmap a previously mapped region of a memory object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\nReads or writes from the host using the pointer returned by 'clEnqueueMapBuffer'\nor 'clEnqueueMapImage' are considered to be complete.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' increments the mapped count of the\nmemory object. The initial mapped count value of a memory object is\nzero. Multiple calls to 'clEnqueueMapBuffer' or 'clEnqueueMapImage' on the same\nmemory object will increment this mapped count by appropriate number of\ncalls. 'clEnqueueUnmapMemObject' decrements the mapped count of the memory\nobject.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' act as synchronization points for a\nregion of the memory object being mapped.\n\n'clEnqueueUnmapMemObject' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\n\n * CL_INVALID_COMMAND_QUEUE if command_queue is not a valid command-queue.\n\n * CL_INVALID_MEM_OBJECT if memobj is not a valid memory object.\n\n * CL_INVALID_VALUE if mapped_ptr is not a valid pointer returned by\n'clEnqueueMapBuffer' or 'clEnqueueMapImage' for memobj.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n * CL_INVALID_CONTEXT if the context associated with command_queue and memobj\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n-}\nclEnqueueUnmapMemObject :: CLCommandQueue \n -> CLMem -- ^ A valid memory object. The OpenCL\n -- context associated with command_queue and\n -- memobj must be the same.\n -> Ptr () -- ^ The host address returned by a\n -- previous call to 'clEnqueueMapBuffer' or\n -- 'clEnqueueMapImage' for memobj.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before\n -- 'clEnqueueUnmapMemObject' can be\n -- executed. If event_wait_list is\n -- empty, then 'clEnqueueUnmapMemObject'\n -- does not wait on any event to\n -- complete. The events specified in\n -- event_wait_list act as\n -- synchronization points. The context\n -- associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n\n -> IO CLEvent\nclEnqueueUnmapMemObject cq mem pp = clEnqueue (raw_clEnqueueUnmapMemObject cq mem pp)\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (map fromIntegral lws) $ \\plws -> do\n clEnqueue (raw_clEnqueueNDRangeKernel cq krn num nullPtr pgws plws) events\n where\n num = fromIntegral $ length gws\n withMaybeArray [] = ($ nullPtr)\n withMaybeArray xs = withArray xs\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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d7d892ce9cfdb9f8b3a228f677474ee4d29de764","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","repos":"vincenthz\/webkit","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":"c235e85f13e9e914eeb7b7dcf4d5b4b9ceab91de","subject":"[project @ 2003-01-18 17:44:07 by as49]","message":"[project @ 2003-01-18 17:44:07 by as49]\n\nMove Plug.chs to ..\/embedding. It makes more sense and makes building on\nWindows easier.\n\ndarcs-hash:20030118174407-d90cf-b42a502af30d333171ad80bbd941e958ac6c0920.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/windows\/Plug.chs","new_file":"gtk\/windows\/Plug.chs","new_contents":"","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Plug@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/08\/05 16:41:35 $\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-- * Plug is a window that is to be attached to the window of another\n-- application. If you have managed to receive the @ref type XID@ from\n-- the inviting application you can construct the Plug and add your widgets\n-- to it.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Plug(\n Plug,\n PlugClass,\n castToPlug,\n XID,\n plugNew\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs\t(XID)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\nplugNew :: XID -> IO Plug\nplugNew nw = makeNewObject mkPlug $ liftM castPtr $\n {#call unsafe plug_new#} nw\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"85ca1afac9a327ef472f9d9a72a02455c503b59c","subject":"[project @ 2002-07-17 16:09:05 by juhp] Bind entryGetText.","message":"[project @ 2002-07-17 16:09:05 by juhp]\nBind entryGetText.\n","repos":"vincenthz\/webkit","old_file":"gtk\/entry\/Entry.chs","new_file":"gtk\/entry\/Entry.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Entry@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 16:09:05 $\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 lets the user enter a single line of text.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * A couple of signals are not bound because I could not figure out what\n-- they mean. Some of them do not seem to be emitted at all.\n--\nmodule Entry(\n Entry,\n EntryClass,\n castToEntry,\n entrySelectRegion,\n entryGetSelectionBounds,\n entryInsertText,\n entryDeleteText,\n entryGetChars,\n entryCutClipboard,\n entryCopyClipboard,\n entryPasteClipboard,\n entryDeleteSelection,\n entrySetEditable,\n entryNew,\n entrySetText,\n entryGetText,\n entryAppendText,\n entryPrependText,\n entrySetVisibility,\n entrySetInvisibleChar,\n entrySetMaxLength,\n entryGetActivatesDefault,\n entrySetActivatesDefault,\n entryGetHasFrame,\n entrySetHasFrame,\n entryGetWidthChars,\n entrySetWidthChars,\n onEntryActivate,\n afterEntryActivate,\n onEntryChanged,\n afterEntryChanged,\n onCopyClipboard,\n afterCopyClipboard,\n onCutClipboard,\n afterCutClipboard,\n onPasteClipboard,\n afterPasteClipboard,\n onDeleteText,\n afterDeleteText,\n onInsertAtCursor,\n afterInsertAtCursor,\n onToggleOverwrite,\n afterToggleOverwrite\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Char\t(ord)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods originating in the Editable base class which is not really a base\n-- class of in the Gtk Hierarchy (it is non-existant). I renamed\n{#pointer *Editable foreign#}\n\ntoEditable :: EntryClass ed => ed -> Editable\ntoEditable = castForeignPtr.unEntry.toEntry\n\n-- @method entrySelectRegion@ Select a span of text.\n--\n-- * A negative @ref arg end@ position will make the selection extend to the\n-- end of the buffer.\n--\n-- * Calling this function with @ref arg start@=1 and @ref arg end@=4 it will\n-- mark \"ask\" in the string \"Haskell\". (FIXME: verify)\n--\nentrySelectRegion :: EntryClass ed => ed -> Int -> Int -> IO ()\nentrySelectRegion ed start end = {#call editable_select_region#}\n (toEditable ed) (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetSelectionBounds@ Get the span of the current selection.\n--\n-- * The returned tuple is not ordered. The second index represents the\n-- position of the cursor. The first index is the other end of the\n-- selection. If both numbers are equal there is in fact no selection.\n--\nentryGetSelectionBounds :: EntryClass ed => ed -> IO (Int,Int)\nentryGetSelectionBounds ed = alloca $ \\startPtr -> alloca $ \\endPtr -> do\n {#call unsafe editable_get_selection_bounds#} (toEditable ed) startPtr endPtr\n start <- liftM fromIntegral $ peek startPtr\n end\t<- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- @method entryInsertText@ Insert new text at the specified position.\n--\n-- * If the position is invalid the text will be inserted at the end of the\n-- buffer. The returned value reflects the actual insertion point.\n--\nentryInsertText :: EntryClass ed => ed -> String -> Int -> IO Int\nentryInsertText ed str pos = withObject (fromIntegral pos) $ \\posPtr ->\n withCStringLen str $ \\(strPtr,len) -> do\n {#call editable_insert_text#} (toEditable ed) strPtr (fromIntegral len) \n posPtr\n liftM fromIntegral $ peek posPtr\n\n-- @method entryDeleteText@ Delete a given range of text.\n--\n-- * If the @ref arg end@ position is invalid, it is set to the lenght of the\n-- buffer.\n--\n-- * @ref arg start@ is restricted to 0..@end.\n--\nentryDeleteText :: EntryClass ed => ed -> Int -> Int -> IO ()\nentryDeleteText ed start end = {#call editable_delete_text#} (toEditable ed)\n (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetChars@ Retrieve a range of characters.\n--\n-- * Set @ref arg end@ to a negative value to reach the end of the buffer.\n--\nentryGetChars :: EntryClass ed => ed -> Int -> Int -> IO String\nentryGetChars ed start end = do\n strPtr <- {#call unsafe editable_get_chars#} (toEditable ed) \n (fromIntegral start) (fromIntegral end)\n str <- peekCString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n-- @method entryCutClipboard@ Cut the selected characters to the Clipboard.\n--\nentryCutClipboard :: EntryClass ed => ed -> IO ()\nentryCutClipboard = {#call editable_cut_clipboard#}.toEditable\n\n-- @method entryCopyClipboard@ Copy the selected characters to the Clipboard.\n--\nentryCopyClipboard :: EntryClass ed => ed -> IO ()\nentryCopyClipboard = {#call editable_copy_clipboard#}.toEditable\n\n-- @method entryPasteClipboard@ Paste the selected characters to the\n-- Clipboard.\n--\nentryPasteClipboard :: EntryClass ed => ed -> IO ()\nentryPasteClipboard = {#call editable_paste_clipboard#}.toEditable\n\n-- @method entryDeleteSelection@ Delete the current selection.\n--\nentryDeleteSelection :: EntryClass ed => ed -> IO ()\nentryDeleteSelection = {#call editable_delete_selection#}.toEditable\n\n-- @method entrySetPosition@ Set the cursor to a specific position.\n--\nentrySetPosition :: EntryClass ed => ed -> Int -> IO ()\nentrySetPosition ed pos = \n {#call editable_set_position#} (toEditable ed) (fromIntegral pos)\n\n-- @method entryGetPosition@ Get the current cursor position.\n--\nentryGetPosition :: EntryClass ed => ed -> IO Int\nentryGetPosition ed = liftM fromIntegral $\n {#call unsafe editable_get_position#} (toEditable ed)\n\n-- @method entrySetEditable@ Make an @ref type Entry@ insensitive.\n--\n-- * Called with False will make the text uneditable.\n--\nentrySetEditable :: EntryClass ed => ed -> Bool -> IO ()\nentrySetEditable ed isEditable = {#call editable_set_editable#}\n (toEditable ed) (fromBool isEditable)\n\n\n-- methods\n\n-- @constructor entryNew@ Create a new @ref type Entry@ widget.\n--\nentryNew :: IO Entry\nentryNew = makeNewObject mkEntry $ liftM castPtr $ {#call unsafe entry_new#}\n\n-- @method entrySetText@ Set the text of the @ref type Entry@ widget.\n--\nentrySetText :: EntryClass ec => ec -> String -> IO ()\nentrySetText ec str = withCString str $ {#call entry_set_text#} (toEntry ec)\n\n-- @method entryGetText@ Get the text of the @ref type Entry@ widget.\n--\nentryGetText :: EntryClass ec => ec -> IO String\nentryGetText ec = {#call entry_get_text#} (toEntry ec) >>= peekCString\n\n-- @method entryAppendText@ Append to the text of the @ref type Entry@ widget.\n--\nentryAppendText :: EntryClass ec => ec -> String -> IO ()\nentryAppendText ec str = \n withCString str $ {#call entry_append_text#} (toEntry ec)\n\n-- @method entryPrependText@ Prepend the text of the @ref type Entry@ widget.\n--\nentryPrependText :: EntryClass ec => ec -> String -> IO ()\nentryPrependText ec str = \n withCString str $ {#call entry_prepend_text#} (toEntry ec)\n\n-- @method entrySetVisibility@ Set whether to use password mode (display stars\n-- instead of the text).\n--\n-- * The replacement character can be changed with\n-- @ref method entrySetInvisibleChar@.\n--\nentrySetVisibility :: EntryClass ec => ec -> Bool -> IO ()\nentrySetVisibility ec visible =\n {#call entry_set_visibility#} (toEntry ec) (fromBool visible)\n\n-- @method entrySetInvisibleChar@ Set the replacement character for invisible\n-- text.\n--\nentrySetInvisibleChar :: EntryClass ec => ec -> Char -> IO ()\nentrySetInvisibleChar ec ch =\n {#call unsafe entry_set_invisible_char#} (toEntry ec) ((fromIntegral.ord) ch)\n\n-- @method entrySetMaxLength@ Sets a maximum length the text may grow to.\n--\n-- * A negative number resets the restriction.\n--\nentrySetMaxLength :: EntryClass ec => ec -> Int -> IO ()\nentrySetMaxLength ec max = \n {#call entry_set_max_length#} (toEntry ec) (fromIntegral max)\n\n-- @method entryGetActivatesDefault@ Query whether pressing return will\n-- activate the default widget.\n--\nentryGetActivatesDefault :: EntryClass ec => ec -> IO Bool\nentryGetActivatesDefault ec = liftM toBool $\n {#call unsafe entry_get_activates_default#} (toEntry ec)\n\n-- @method entrySetActivatesDefault@ Specify if pressing return will activate\n-- the default widget.\n--\n-- * This setting is useful in @ref arg Dialog@ boxes where enter should press\n-- the default button.\n--\nentrySetActivatesDefault :: EntryClass ec => ec -> Bool -> IO ()\nentrySetActivatesDefault ec setting = {#call entry_set_activates_default#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetHasFrame@ Query if the text @ref type Entry@ is displayed\n-- with a frame around it.\n--\nentryGetHasFrame :: EntryClass ec => ec -> IO Bool\nentryGetHasFrame ec = liftM toBool $\n {#call unsafe entry_get_has_frame#} (toEntry ec)\n\n-- @method entrySetHasFrame@ Specifies whehter the @ref type Entry@ should be\n-- in an etched-in frame.\n--\nentrySetHasFrame :: EntryClass ec => ec -> Bool -> IO ()\nentrySetHasFrame ec setting = {#call entry_set_has_frame#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetWidthChars@ Retrieve the number of characters the widget\n-- should ask for.\n--\nentryGetWidthChars :: EntryClass ec => ec -> IO Int\nentryGetWidthChars ec = liftM fromIntegral $ \n {#call unsafe entry_get_width_chars#} (toEntry ec)\n\n-- @method entrySetWidthChars@ Specifies how large the @ref type Entry@ should\n-- be in characters.\n--\n-- * This setting is only considered when the widget formulates its size\n-- request. Make sure that it is not mapped (shown) before you change this\n-- value.\n--\nentrySetWidthChars :: EntryClass ec => ec -> Int -> IO ()\nentrySetWidthChars ec setting = {#call entry_set_width_chars#}\n (toEntry ec) (fromIntegral setting)\n\n\n-- signals\n\n-- @signal connectToEntryActivate@ Emitted when the user presses return within\n-- the @ref arg Entry@ field.\n--\nonEntryActivate, afterEntryActivate :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryActivate = connect_NONE__NONE \"activate\" False\nafterEntryActivate = connect_NONE__NONE \"activate\" True\n\n-- @signal connectToEntryChanged@ Emitted when the settings of the\n-- @ref arg Entry@ widget changes.\n--\nonEntryChanged, afterEntryChanged :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryChanged = connect_NONE__NONE \"changed\" False\nafterEntryChanged = connect_NONE__NONE \"changed\" True\n\n-- @signal connectToCopyClipboard@ Emitted when the current selection has been\n-- copied to the clipboard.\n--\nonCopyClipboard, afterCopyClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCopyClipboard = connect_NONE__NONE \"copy_clipboard\" False\nafterCopyClipboard = connect_NONE__NONE \"copy_clipboard\" True\n\n-- @signal connectToCutClipboard@ Emitted when the current selection has been\n-- cut to the clipboard.\n--\nonCutClipboard, afterCutClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCutClipboard = connect_NONE__NONE \"cut_clipboard\" False\nafterCutClipboard = connect_NONE__NONE \"cut_clipboard\" True\n\n-- @signal connectToPasteClipboard@ Emitted when the current selection has\n-- been pasted from the clipboard.\n--\nonPasteClipboard, afterPasteClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonPasteClipboard = connect_NONE__NONE \"paste_clipboard\" False\nafterPasteClipboard = connect_NONE__NONE \"paste_clipboard\" True\n\n-- @signal connectToDeleteText@ Emitted when a piece of text is deleted from\n-- the @ref arg Entry@.\n--\nonDeleteText, afterDeleteText :: EntryClass ec => ec ->\n (Int -> Int -> IO ()) -> IO (ConnectId ec)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- @signal connectToInsertAtCursor@ Emitted when a piece of text is inserted\n-- at the cursor position.\n--\nonInsertAtCursor, afterInsertAtCursor :: EntryClass ec => ec ->\n (String -> IO ()) ->\n IO (ConnectId ec)\nonInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" False\nafterInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" True\n\n-- @signal connectToToggleOverwrite@ Emitted when the user changes from\n-- overwriting to inserting.\n--\nonToggleOverwrite, afterToggleOverwrite :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" False\nafterToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" True\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Entry@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/05\/24 09:43:24 $\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 lets the user enter a single line of text.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * A couple of signals are not bound because I could not figure out what\n-- they mean. Some of them do not seem to be emitted at all.\n--\nmodule Entry(\n Entry,\n EntryClass,\n castToEntry,\n entrySelectRegion,\n entryGetSelectionBounds,\n entryInsertText,\n entryDeleteText,\n entryGetChars,\n entryCutClipboard,\n entryCopyClipboard,\n entryPasteClipboard,\n entryDeleteSelection,\n entrySetEditable,\n entryNew,\n entrySetText,\n entryAppendText,\n entryPrependText,\n entrySetVisibility,\n entrySetInvisibleChar,\n entrySetMaxLength,\n entryGetActivatesDefault,\n entrySetActivatesDefault,\n entryGetHasFrame,\n entrySetHasFrame,\n entryGetWidthChars,\n entrySetWidthChars,\n onEntryActivate,\n afterEntryActivate,\n onEntryChanged,\n afterEntryChanged,\n onCopyClipboard,\n afterCopyClipboard,\n onCutClipboard,\n afterCutClipboard,\n onPasteClipboard,\n afterPasteClipboard,\n onDeleteText,\n afterDeleteText,\n onInsertAtCursor,\n afterInsertAtCursor,\n onToggleOverwrite,\n afterToggleOverwrite\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Char\t(ord)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods originating in the Editable base class which is not really a base\n-- class of in the Gtk Hierarchy (it is non-existant). I renamed\n{#pointer *Editable foreign#}\n\ntoEditable :: EntryClass ed => ed -> Editable\ntoEditable = castForeignPtr.unEntry.toEntry\n\n-- @method entrySelectRegion@ Select a span of text.\n--\n-- * A negative @ref arg end@ position will make the selection extend to the\n-- end of the buffer.\n--\n-- * Calling this function with @ref arg start@=1 and @ref arg end@=4 it will\n-- mark \"ask\" in the string \"Haskell\". (FIXME: verify)\n--\nentrySelectRegion :: EntryClass ed => ed -> Int -> Int -> IO ()\nentrySelectRegion ed start end = {#call editable_select_region#}\n (toEditable ed) (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetSelectionBounds@ Get the span of the current selection.\n--\n-- * The returned tuple is not ordered. The second index represents the\n-- position of the cursor. The first index is the other end of the\n-- selection. If both numbers are equal there is in fact no selection.\n--\nentryGetSelectionBounds :: EntryClass ed => ed -> IO (Int,Int)\nentryGetSelectionBounds ed = alloca $ \\startPtr -> alloca $ \\endPtr -> do\n {#call unsafe editable_get_selection_bounds#} (toEditable ed) startPtr endPtr\n start <- liftM fromIntegral $ peek startPtr\n end\t<- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- @method entryInsertText@ Insert new text at the specified position.\n--\n-- * If the position is invalid the text will be inserted at the end of the\n-- buffer. The returned value reflects the actual insertion point.\n--\nentryInsertText :: EntryClass ed => ed -> String -> Int -> IO Int\nentryInsertText ed str pos = withObject (fromIntegral pos) $ \\posPtr ->\n withCStringLen str $ \\(strPtr,len) -> do\n {#call editable_insert_text#} (toEditable ed) strPtr (fromIntegral len) \n posPtr\n liftM fromIntegral $ peek posPtr\n\n-- @method entryDeleteText@ Delete a given range of text.\n--\n-- * If the @ref arg end@ position is invalid, it is set to the lenght of the\n-- buffer.\n--\n-- * @ref arg start@ is restricted to 0..@end.\n--\nentryDeleteText :: EntryClass ed => ed -> Int -> Int -> IO ()\nentryDeleteText ed start end = {#call editable_delete_text#} (toEditable ed)\n (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetChars@ Retrieve a range of characters.\n--\n-- * Set @ref arg end@ to a negative value to reach the end of the buffer.\n--\nentryGetChars :: EntryClass ed => ed -> Int -> Int -> IO String\nentryGetChars ed start end = do\n strPtr <- {#call unsafe editable_get_chars#} (toEditable ed) \n (fromIntegral start) (fromIntegral end)\n str <- peekCString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n-- @method entryCutClipboard@ Cut the selected characters to the Clipboard.\n--\nentryCutClipboard :: EntryClass ed => ed -> IO ()\nentryCutClipboard = {#call editable_cut_clipboard#}.toEditable\n\n-- @method entryCopyClipboard@ Copy the selected characters to the Clipboard.\n--\nentryCopyClipboard :: EntryClass ed => ed -> IO ()\nentryCopyClipboard = {#call editable_copy_clipboard#}.toEditable\n\n-- @method entryPasteClipboard@ Paste the selected characters to the\n-- Clipboard.\n--\nentryPasteClipboard :: EntryClass ed => ed -> IO ()\nentryPasteClipboard = {#call editable_paste_clipboard#}.toEditable\n\n-- @method entryDeleteSelection@ Delete the current selection.\n--\nentryDeleteSelection :: EntryClass ed => ed -> IO ()\nentryDeleteSelection = {#call editable_delete_selection#}.toEditable\n\n-- @method entrySetPosition@ Set the cursor to a specific position.\n--\nentrySetPosition :: EntryClass ed => ed -> Int -> IO ()\nentrySetPosition ed pos = \n {#call editable_set_position#} (toEditable ed) (fromIntegral pos)\n\n-- @method entryGetPosition@ Get the current cursor position.\n--\nentryGetPosition :: EntryClass ed => ed -> IO Int\nentryGetPosition ed = liftM fromIntegral $\n {#call unsafe editable_get_position#} (toEditable ed)\n\n-- @method entrySetEditable@ Make an @ref type Entry@ insensitive.\n--\n-- * Called with False will make the text uneditable.\n--\nentrySetEditable :: EntryClass ed => ed -> Bool -> IO ()\nentrySetEditable ed isEditable = {#call editable_set_editable#}\n (toEditable ed) (fromBool isEditable)\n\n\n-- methods\n\n-- @constructor entryNew@ Create a new @ref type Entry@ widget.\n--\nentryNew :: IO Entry\nentryNew = makeNewObject mkEntry $ liftM castPtr $ {#call unsafe entry_new#}\n\n\n\n-- @method entrySetText@ Set the text of the @ref type Entry@ widget.\n--\nentrySetText :: EntryClass ec => ec -> String -> IO ()\nentrySetText ec str = withCString str $ {#call entry_set_text#} (toEntry ec)\n\n-- @method entryAppendText@ Append to the text of the @ref type Entry@ widget.\n--\nentryAppendText :: EntryClass ec => ec -> String -> IO ()\nentryAppendText ec str = \n withCString str $ {#call entry_append_text#} (toEntry ec)\n\n-- @method entryPrependText@ Prepend the text of the @ref type Entry@ widget.\n--\nentryPrependText :: EntryClass ec => ec -> String -> IO ()\nentryPrependText ec str = \n withCString str $ {#call entry_prepend_text#} (toEntry ec)\n\n-- @method entrySetVisibility@ Set whether to use password mode (display stars\n-- instead of the text).\n--\n-- * The replacement character can be changed with\n-- @ref method entrySetInvisibleChar@.\n--\nentrySetVisibility :: EntryClass ec => ec -> Bool -> IO ()\nentrySetVisibility ec visible =\n {#call entry_set_visibility#} (toEntry ec) (fromBool visible)\n\n-- @method entrySetInvisibleChar@ Set the replacement character for invisible\n-- text.\n--\nentrySetInvisibleChar :: EntryClass ec => ec -> Char -> IO ()\nentrySetInvisibleChar ec ch =\n {#call unsafe entry_set_invisible_char#} (toEntry ec) ((fromIntegral.ord) ch)\n\n-- @method entrySetMaxLength@ Sets a maximum length the text may grow to.\n--\n-- * A negative number resets the restriction.\n--\nentrySetMaxLength :: EntryClass ec => ec -> Int -> IO ()\nentrySetMaxLength ec max = \n {#call entry_set_max_length#} (toEntry ec) (fromIntegral max)\n\n-- @method entryGetActivatesDefault@ Query whether pressing return will\n-- activate the default widget.\n--\nentryGetActivatesDefault :: EntryClass ec => ec -> IO Bool\nentryGetActivatesDefault ec = liftM toBool $\n {#call unsafe entry_get_activates_default#} (toEntry ec)\n\n-- @method entrySetActivatesDefault@ Specify if pressing return will activate\n-- the default widget.\n--\n-- * This setting is useful in @ref arg Dialog@ boxes where enter should press\n-- the default button.\n--\nentrySetActivatesDefault :: EntryClass ec => ec -> Bool -> IO ()\nentrySetActivatesDefault ec setting = {#call entry_set_activates_default#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetHasFrame@ Query if the text @ref type Entry@ is displayed\n-- with a frame around it.\n--\nentryGetHasFrame :: EntryClass ec => ec -> IO Bool\nentryGetHasFrame ec = liftM toBool $\n {#call unsafe entry_get_has_frame#} (toEntry ec)\n\n-- @method entrySetHasFrame@ Specifies whehter the @ref type Entry@ should be\n-- in an etched-in frame.\n--\nentrySetHasFrame :: EntryClass ec => ec -> Bool -> IO ()\nentrySetHasFrame ec setting = {#call entry_set_has_frame#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetWidthChars@ Retrieve the number of characters the widget\n-- should ask for.\n--\nentryGetWidthChars :: EntryClass ec => ec -> IO Int\nentryGetWidthChars ec = liftM fromIntegral $ \n {#call unsafe entry_get_width_chars#} (toEntry ec)\n\n-- @method entrySetWidthChars@ Specifies how large the @ref type Entry@ should\n-- be in characters.\n--\n-- * This setting is only considered when the widget formulates its size\n-- request. Make sure that it is not mapped (shown) before you change this\n-- value.\n--\nentrySetWidthChars :: EntryClass ec => ec -> Int -> IO ()\nentrySetWidthChars ec setting = {#call entry_set_width_chars#}\n (toEntry ec) (fromIntegral setting)\n\n\n-- signals\n\n-- @signal connectToEntryActivate@ Emitted when the user presses return within\n-- the @ref arg Entry@ field.\n--\nonEntryActivate, afterEntryActivate :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryActivate = connect_NONE__NONE \"activate\" False\nafterEntryActivate = connect_NONE__NONE \"activate\" True\n\n-- @signal connectToEntryChanged@ Emitted when the settings of the\n-- @ref arg Entry@ widget changes.\n--\nonEntryChanged, afterEntryChanged :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryChanged = connect_NONE__NONE \"changed\" False\nafterEntryChanged = connect_NONE__NONE \"changed\" True\n\n-- @signal connectToCopyClipboard@ Emitted when the current selection has been\n-- copied to the clipboard.\n--\nonCopyClipboard, afterCopyClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCopyClipboard = connect_NONE__NONE \"copy_clipboard\" False\nafterCopyClipboard = connect_NONE__NONE \"copy_clipboard\" True\n\n-- @signal connectToCutClipboard@ Emitted when the current selection has been\n-- cut to the clipboard.\n--\nonCutClipboard, afterCutClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCutClipboard = connect_NONE__NONE \"cut_clipboard\" False\nafterCutClipboard = connect_NONE__NONE \"cut_clipboard\" True\n\n-- @signal connectToPasteClipboard@ Emitted when the current selection has\n-- been pasted from the clipboard.\n--\nonPasteClipboard, afterPasteClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonPasteClipboard = connect_NONE__NONE \"paste_clipboard\" False\nafterPasteClipboard = connect_NONE__NONE \"paste_clipboard\" True\n\n-- @signal connectToDeleteText@ Emitted when a piece of text is deleted from\n-- the @ref arg Entry@.\n--\nonDeleteText, afterDeleteText :: EntryClass ec => ec ->\n (Int -> Int -> IO ()) -> IO (ConnectId ec)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- @signal connectToInsertAtCursor@ Emitted when a piece of text is inserted\n-- at the cursor position.\n--\nonInsertAtCursor, afterInsertAtCursor :: EntryClass ec => ec ->\n (String -> IO ()) ->\n IO (ConnectId ec)\nonInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" False\nafterInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" True\n\n-- @signal connectToToggleOverwrite@ Emitted when the user changes from\n-- overwriting to inserting.\n--\nonToggleOverwrite, afterToggleOverwrite :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" False\nafterToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"68e4c9428c6da2e0912ecc321cff353f087c3bee","subject":"Declare exports in ByteBuffer module.","message":"Declare exports in ByteBuffer module.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Lib\/ByteBuffer.chs","new_file":"src\/Network\/Grpc\/Lib\/ByteBuffer.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 StandaloneDeriving, ForeignFunctionInterface, OverloadedStrings #-}\nmodule Network.Grpc.Lib.ByteBuffer\n ( CByteBuffer\n , fromByteString\n , addBBFinalizer\n , toLazyByteString\n\n , CByteBufferReader\n ) where\n\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\n\nimport Control.Exception (bracket)\n\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport qualified Data.ByteString.Lazy as L\n\n#include \n#include \n#include \"hs_byte_buffer.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata CByteBuffer\n{#pointer *byte_buffer as ByteBuffer foreign -> CByteBuffer#}\ndata CByteBufferReader\n{#pointer *byte_buffer_reader as ByteBufferReader -> CByteBufferReader#}\n\ndata CSlice\n{#pointer *gpr_slice as Slice -> CSlice#}\n\nfromByteString :: ByteString -> IO ByteBuffer\nfromByteString = hsRawByteBufferCreate\n\nwithByteString :: ByteString -> ((Ptr CChar, CULong) -> IO a) -> IO a\nwithByteString bs act = do\n let (fPtr, offset, len) = B.toForeignPtr bs\n withForeignPtr fPtr $ \\ptr -> act (ptr `plusPtr` offset, fromIntegral len)\n\n{#fun unsafe hs_raw_byte_buffer_create as ^\n {withByteString* `ByteString'&} -> `ByteBuffer' addBBFinalizer* #}\n\naddBBFinalizer :: Ptr CByteBuffer -> IO ByteBuffer\naddBBFinalizer bb = newForeignPtr grpc_byte_buffer_destroy bb\n\nforeign import ccall \"Network\/Grpc\/Core\/ByteBuffer.chs.h &grpc_byte_buffer_destroy\"\n grpc_byte_buffer_destroy :: FinalizerPtr CByteBuffer\n\ntoByteString :: Slice -> IO ByteString\ntoByteString slice = do\n refcount <- {#get gpr_slice->refcount#} slice\n if refcount == nullPtr\n then fromInlined\n else fromRefcounted\n where\n fromInlined = do\n len <- {#get gpr_slice->data.inlined.length#} slice\n ptr <- {#get gpr_slice->data.inlined.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n fromRefcounted = do\n len <- {#get gpr_slice->data.refcounted.length#} slice\n ptr <- {#get gpr_slice->data.refcounted.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n\ntoLazyByteString :: ByteBuffer -> IO L.ByteString\ntoLazyByteString bb =\n bracket\n (byteBufferReaderInit bb)\n (byteBufferReaderDestroy)\n (\\bbr -> L.fromChunks <$> go bbr [])\n where\n go bbr acc = do\n (tag, slice) <- byteBufferReaderNext bbr\n case tag of\n 0 -> return $ reverse acc\n _ -> do\n bs <- toByteString slice\n go bbr (bs:acc)\n\n{#fun unsafe byte_buffer_reader_init as ^\n {allocaByteBufferReader- `ByteBufferReader' id, `ByteBuffer'} -> `()' #}\n\nallocaSlice :: (Slice -> IO a) -> IO a\nallocaSlice act = do\n allocaBytes {#sizeof gpr_slice#} $ \\p -> act p\n\nallocaByteBufferReader :: (ByteBufferReader -> IO a) -> IO a\nallocaByteBufferReader act = do\n allocaBytes {#sizeof grpc_byte_buffer_reader#} $ \\p -> act p\n\n{#fun unsafe byte_buffer_reader_next as ^\n {`ByteBufferReader', allocaSlice- `Slice' id} -> `Int' fromIntegral#}\n\n{#fun unsafe byte_buffer_reader_destroy as ^\n {`ByteBufferReader'} -> `()'#}\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 StandaloneDeriving, ForeignFunctionInterface, OverloadedStrings #-}\nmodule Network.Grpc.Lib.ByteBuffer where\n\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\n\nimport Control.Exception (bracket)\n\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport qualified Data.ByteString.Lazy as L\n\n#include \n#include \n#include \"hs_byte_buffer.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata CByteBuffer\n{#pointer *byte_buffer as ByteBuffer foreign -> CByteBuffer#}\ndata CByteBufferReader\n{#pointer *byte_buffer_reader as ByteBufferReader -> CByteBufferReader#}\n\ndata CSlice\n{#pointer *gpr_slice as Slice -> CSlice#}\n\nfromByteString :: ByteString -> IO ByteBuffer\nfromByteString = hsRawByteBufferCreate\n\nwithByteString :: ByteString -> ((Ptr CChar, CULong) -> IO a) -> IO a\nwithByteString bs act = do\n let (fPtr, offset, len) = B.toForeignPtr bs\n withForeignPtr fPtr $ \\ptr -> act (ptr `plusPtr` offset, fromIntegral len)\n\n{#fun unsafe hs_raw_byte_buffer_create as ^\n {withByteString* `ByteString'&} -> `ByteBuffer' addBBFinalizer* #}\n\naddBBFinalizer :: Ptr CByteBuffer -> IO ByteBuffer\naddBBFinalizer bb = newForeignPtr grpc_byte_buffer_destroy bb\n\nforeign import ccall \"Network\/Grpc\/Core\/ByteBuffer.chs.h &grpc_byte_buffer_destroy\"\n grpc_byte_buffer_destroy :: FinalizerPtr CByteBuffer\n\ntoByteString :: Slice -> IO ByteString\ntoByteString slice = do\n refcount <- {#get gpr_slice->refcount#} slice\n if refcount == nullPtr\n then fromInlined\n else fromRefcounted\n where\n fromInlined = do\n len <- {#get gpr_slice->data.inlined.length#} slice\n ptr <- {#get gpr_slice->data.inlined.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n fromRefcounted = do\n len <- {#get gpr_slice->data.refcounted.length#} slice\n ptr <- {#get gpr_slice->data.refcounted.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n\ntoLazyByteString :: ByteBuffer -> IO L.ByteString\ntoLazyByteString bb =\n bracket\n (byteBufferReaderInit bb)\n (byteBufferReaderDestroy)\n (\\bbr -> L.fromChunks <$> go bbr [])\n where\n go bbr acc = do\n (tag, slice) <- byteBufferReaderNext bbr\n case tag of\n 0 -> return $ reverse acc\n _ -> do\n bs <- toByteString slice\n go bbr (bs:acc)\n\n{#fun unsafe byte_buffer_reader_init as ^\n {allocaByteBufferReader- `ByteBufferReader' id, `ByteBuffer'} -> `()' #}\n\nallocaSlice :: (Slice -> IO a) -> IO a\nallocaSlice act = do\n allocaBytes {#sizeof gpr_slice#} $ \\p -> act p\n\nallocaByteBufferReader :: (ByteBufferReader -> IO a) -> IO a\nallocaByteBufferReader act = do\n allocaBytes {#sizeof grpc_byte_buffer_reader#} $ \\p -> act p\n\n{#fun unsafe byte_buffer_reader_next as ^\n {`ByteBufferReader', allocaSlice- `Slice' id} -> `Int' fromIntegral#}\n\n{#fun unsafe byte_buffer_reader_destroy as ^\n {`ByteBufferReader'} -> `()'#}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"11d1b4d0ee11d7ff8e48ad2d716184c1c671a4ad","subject":"[project @ 2004-12-18 20:45:50 by duncan_coutts]","message":"[project @ 2004-12-18 20:45:50 by duncan_coutts]\n\ntidy up module header\n\ndarcs-hash:20041218204550-d6ff7-7e19ee70f68095c60f429d83c90a00fe8536141c.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"mozembed\/Graphics\/UI\/Gtk\/MozEmbed.chs","new_file":"mozembed\/Graphics\/UI\/Gtk\/MozEmbed.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget embedding the Mozilla browser engine (Gecko)\n--\n-- Author : Jonas Svensson\n--\n-- Created: 26 February 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2004\/12\/18 20:45:50 $\n--\n-- Copyright (c) 2002 Jonas Svensson\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-- Modified 2004 by Scott West for basic use in gtk2hs\n--\n-- Further modified 2004 by Wolfram Kahl:\n-- * ported to gtk2hs\/c2hs\n-- * added additional interface functions\n-- * circumvented render_data problem\n--\n-- | This widgets embeds Mozilla's browser engine (Gecko) into a GTK+ widget.\n-- See for an API reference.\n--\nmodule Graphics.UI.Gtk.MozEmbed (\n MozEmbed, MozEmbedClass,\n\n mozEmbedNew, mozEmbedSetCompPath,\n\n mozEmbedRenderData,\n mozEmbedOpenStream, mozEmbedAppendData, mozEmbedCloseStream,\n\n onOpenURI,\n\n mozEmbedLoadUrl,\n\n -- the functions below are untested.\n\n onKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut,\n\n mozEmbedSetProfilePath,\n mozEmbedStopLoad, mozEmbedGoBack, mozEmbedGoForward, mozEmbedGetLinkMessage,\n mozEmbedGetJsStatus, mozEmbedGetTitle, mozEmbedGetLocation,\n mozEmbedCanGoBack, mozEmbedCanGoForward, mozEmbedPushStartup,\n mozEmbedPopStartup\n) where\n\nimport Monad\t\t(liftM)\nimport FFI\nimport ForeignPtr\nimport Foreign.Marshal.Utils (toBool)\n\n{#import Object#} (makeNewObject)\n{#import Signal#} (ConnectId, connect_STRING__BOOL, connect_PTR__INT)\n{#import Graphics.UI.Gtk.MozEmbedType #}\nimport Widget (Widget)\n\n{#context lib=\"gtkembedmoz\" prefix =\"gtk\"#}\n\n-- operations\n-- ----------\n\n-- | Create a new MozEmbed\n--\nmozEmbedNew :: IO MozEmbed\nmozEmbedNew = makeNewObject mkMozEmbed $ liftM castPtr {#call moz_embed_new#}\n\nmozEmbedSetCompPath :: String -> IO ()\nmozEmbedSetCompPath str =\n withCString str $ \\strPtr ->\n {#call moz_embed_set_comp_path#}\n strPtr\n\nmozEmbedSetProfilePath :: String -> String -> IO ()\nmozEmbedSetProfilePath dir name =\n withCString dir $ \\dirPtr ->\n withCString name $ \\namePtr ->\n {#call moz_embed_set_profile_path#} dirPtr namePtr\n \nmozEmbedLoadUrl :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedLoadUrl m url =\n withCString url $ \\urlPtr ->\n {#call moz_embed_load_url#}\n (toMozEmbed m)\n urlPtr\n\nmozEmbedStopLoad :: MozEmbedClass m => m -> IO ()\nmozEmbedStopLoad m = \n {#call moz_embed_stop_load#} (toMozEmbed m)\n\nmozEmbedGoBack :: MozEmbedClass m => m -> IO ()\nmozEmbedGoBack m =\n {#call moz_embed_go_back#} (toMozEmbed m)\n\nmozEmbedGoForward :: MozEmbedClass m => m -> IO ()\nmozEmbedGoForward m =\n {#call moz_embed_go_forward#} (toMozEmbed m)\n\nmozEmbedGetLinkMessage :: MozEmbedClass m => m -> IO String\nmozEmbedGetLinkMessage m = \n do\n str <- {#call moz_embed_get_link_message#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetJsStatus :: MozEmbedClass m => m -> IO String\nmozEmbedGetJsStatus m =\n do\n str <- {#call moz_embed_get_js_status#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetTitle :: MozEmbedClass m => m -> IO String\nmozEmbedGetTitle m = \n do\n str <- {#call moz_embed_get_title#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetLocation :: MozEmbedClass m => m -> IO String\nmozEmbedGetLocation m = \n do\n str <- {#call moz_embed_get_location#} (toMozEmbed m)\n peekCString str\n\nmozEmbedCanGoBack :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoBack m =\n liftM toBool $ \n {#call moz_embed_can_go_back#} (toMozEmbed m)\n\nmozEmbedCanGoForward :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoForward m =\n liftM toBool $ \n {#call moz_embed_can_go_forward#} (toMozEmbed m)\n\nmozEmbedPushStartup :: IO ()\nmozEmbedPushStartup =\n {#call moz_embed_push_startup#}\n\nmozEmbedPopStartup :: IO ()\nmozEmbedPopStartup =\n {#call moz_embed_pop_startup#}\n\n{-\nvoid gtk_moz_embed_open_stream (GtkMozEmbed *embed,\n\t\t\t\t\t const char *base_uri,\n\t\t\t\t\t const char *mime_type);\nvoid gtk_moz_embed_append_data (GtkMozEmbed *embed,\n\t\t\t\t\t const char *data, guint32 len);\nvoid gtk_moz_embed_close_stream (GtkMozEmbed *embed);\n-}\n\nmozEmbedOpenStream :: MozEmbedClass m => m -> String -> String -> IO ()\nmozEmbedOpenStream m baseURI mimeType =\n withCString baseURI $ \\ basePtr ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_open_stream#} (toMozEmbed m) basePtr mtPtr\n\nmozEmbedAppendDataInternal :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendDataInternal m contents =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged?\n let len' = fromIntegral len in\n {#call gtk_moz_embed_append_data#} (toMozEmbed m) dataPtr len'\n-- >> free dataPtr\n\nmozEmbedCloseStream :: MozEmbedClass m => m -> IO ()\nmozEmbedCloseStream m =\n {#call gtk_moz_embed_close_stream#} (toMozEmbed m)\n\nmozEmbedAppendData :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendData m contents =\n mapM_ (mozEmbedAppendDataInternal m) (chunks 32768 contents)\n\nmozEmbedRenderData :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderData m contents baseURI mimeType = do\n mozEmbedOpenStream m baseURI mimeType\n mozEmbedAppendData m contents\n mozEmbedCloseStream m\n\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = let (ys, zs) = splitAt n xs in ys : chunks n zs\n\n{-\nvoid gtk_moz_embed_render_data (GtkMozEmbed *embed, \n const char *data,\n guint32 len,\n const char *base_uri, \n const char *mime_type)\n-}\n-- -- mozEmbedRenderDataInternal does not work for len' > 2^16\nmozEmbedRenderDataInternal :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderDataInternal m contents baseURI mimeType =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged\n let len' = fromIntegral len in\n-- hPutStrLn stderr (\"mozEmbedRenderData: \" ++ shows len' \" bytes\") >>= \\ _ ->\n withCString baseURI $ \\ basePrt ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_render_data#} (toMozEmbed m) dataPtr len' basePrt mtPtr\n-- >> free dataPtr\n\n{-\nstruct _GtkMozEmbedClass\n{\n [...]\n gint (* open_uri) (GtkMozEmbed *embed, const char *aURI);\n [...]\n}\n-}\n\nonOpenURI :: MozEmbedClass m => m -> (String -> IO Bool) -> IO (ConnectId m)\nonOpenURI = connect_STRING__BOOL \"open_uri\" after\n where\n-- Specify if the handler is to run before (False) or after (True) the\n-- default handler.\n after = False\n\n\n{-\nMore signals to investigate:\n\n gint (* dom_key_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_press) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_dbl_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_over) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_out) (GtkMozEmbed *embed, gpointer dom_event);\n\nUnfortunateley these are not documented on\n\nhttp:\/\/www.mozilla.org\/unix\/gtk-embedding.html\n\n-}\n\nonKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut\n :: (Num n, Integral n, MozEmbedClass m)\n => m -> (Ptr a -> IO n) -> IO (ConnectId m)\nonKeyDown = connect_PTR__INT \"dom_key_down\" False\nonKeyPress = connect_PTR__INT \"dom_key_press\" False\nonKeyUp = connect_PTR__INT \"dom_key_up\" False\nonMouseDown = connect_PTR__INT \"dom_mouse_down\" False\nonMouseUp = connect_PTR__INT \"dom_mouse_up\" False\nonMouseClick = connect_PTR__INT \"dom_mouse_click\" False\nonMouseDoubleClick = connect_PTR__INT \"dom_mouse_dbl_click\" False\nonMouseOver = connect_PTR__INT \"dom_mouse_over\" False\nonMouseOut = connect_PTR__INT \"dom_mouse_out\" False\n\n","old_contents":"-- |GIMP Toolkit (GTK) Binding for Haskell: widget embedding the -*-haskell-*-\n-- Mozilla browser engine (Gecko)\n--\n-- Author : Jonas Svensson\n-- Created: 26 February 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2004\/12\/17 21:21:44 $\n--\n-- Copyright (c) 2002 Jonas Svensson\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--\n-- Modified 2004 by Scott West for basic use in gtk2hs\n--\n-- Further modified 2004 by Wolfram Kahl:\n-- * ported to gtk2hs\/c2hs\n-- * added additional interface functions\n-- * circumvented render_data problem\n--\n--\n--- DESCRIPTION ---------------------------------------------------------------\n--\n-- This widgets embeds Mozilla's browser engine (Gecko) into a GTK+ widget.\n--\n--- DOCU ----------------------------------------------------------------------\n--\n-- Language: Haskell 98 Binding Module\n--\n--- TODO ----------------------------------------------------------------------\n--\n\nmodule Graphics.UI.Gtk.MozEmbed (\n MozEmbed, MozEmbedClass,\n\n mozEmbedNew, mozEmbedSetCompPath,\n\n mozEmbedRenderData,\n mozEmbedOpenStream, mozEmbedAppendData, mozEmbedCloseStream,\n\n onOpenURI,\n\n mozEmbedLoadUrl,\n\n -- the functions below are untested.\n\n onKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut,\n\n mozEmbedSetProfilePath,\n mozEmbedStopLoad, mozEmbedGoBack, mozEmbedGoForward, mozEmbedGetLinkMessage,\n mozEmbedGetJsStatus, mozEmbedGetTitle, mozEmbedGetLocation,\n mozEmbedCanGoBack, mozEmbedCanGoForward, mozEmbedPushStartup,\n mozEmbedPopStartup\n) where\n\nimport Monad\t\t(liftM)\nimport FFI\nimport ForeignPtr\nimport Foreign.Marshal.Utils (toBool)\n\n{#import Object#} (makeNewObject)\n{#import Signal#} (ConnectId, connect_STRING__BOOL, connect_PTR__INT)\n{#import Graphics.UI.Gtk.MozEmbedType #}\nimport Widget (Widget)\n\n{#context lib=\"gtkembedmoz\" prefix =\"gtk\"#}\n\n-- operations\n-- ----------\n\n-- | Create a new MozEmbed\n--\nmozEmbedNew :: IO MozEmbed\nmozEmbedNew = makeNewObject mkMozEmbed $ liftM castPtr {#call moz_embed_new#}\n\nmozEmbedSetCompPath :: String -> IO ()\nmozEmbedSetCompPath str =\n withCString str $ \\strPtr ->\n {#call moz_embed_set_comp_path#}\n strPtr\n\nmozEmbedSetProfilePath :: String -> String -> IO ()\nmozEmbedSetProfilePath dir name =\n withCString dir $ \\dirPtr ->\n withCString name $ \\namePtr ->\n {#call moz_embed_set_profile_path#} dirPtr namePtr\n \nmozEmbedLoadUrl :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedLoadUrl m url =\n withCString url $ \\urlPtr ->\n {#call moz_embed_load_url#}\n (toMozEmbed m)\n urlPtr\n\nmozEmbedStopLoad :: MozEmbedClass m => m -> IO ()\nmozEmbedStopLoad m = \n {#call moz_embed_stop_load#} (toMozEmbed m)\n\nmozEmbedGoBack :: MozEmbedClass m => m -> IO ()\nmozEmbedGoBack m =\n {#call moz_embed_go_back#} (toMozEmbed m)\n\nmozEmbedGoForward :: MozEmbedClass m => m -> IO ()\nmozEmbedGoForward m =\n {#call moz_embed_go_forward#} (toMozEmbed m)\n\nmozEmbedGetLinkMessage :: MozEmbedClass m => m -> IO String\nmozEmbedGetLinkMessage m = \n do\n str <- {#call moz_embed_get_link_message#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetJsStatus :: MozEmbedClass m => m -> IO String\nmozEmbedGetJsStatus m =\n do\n str <- {#call moz_embed_get_js_status#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetTitle :: MozEmbedClass m => m -> IO String\nmozEmbedGetTitle m = \n do\n str <- {#call moz_embed_get_title#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetLocation :: MozEmbedClass m => m -> IO String\nmozEmbedGetLocation m = \n do\n str <- {#call moz_embed_get_location#} (toMozEmbed m)\n peekCString str\n\nmozEmbedCanGoBack :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoBack m =\n liftM toBool $ \n {#call moz_embed_can_go_back#} (toMozEmbed m)\n\nmozEmbedCanGoForward :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoForward m =\n liftM toBool $ \n {#call moz_embed_can_go_forward#} (toMozEmbed m)\n\nmozEmbedPushStartup :: IO ()\nmozEmbedPushStartup =\n {#call moz_embed_push_startup#}\n\nmozEmbedPopStartup :: IO ()\nmozEmbedPopStartup =\n {#call moz_embed_pop_startup#}\n\n{-\nvoid gtk_moz_embed_open_stream (GtkMozEmbed *embed,\n\t\t\t\t\t const char *base_uri,\n\t\t\t\t\t const char *mime_type);\nvoid gtk_moz_embed_append_data (GtkMozEmbed *embed,\n\t\t\t\t\t const char *data, guint32 len);\nvoid gtk_moz_embed_close_stream (GtkMozEmbed *embed);\n-}\n\nmozEmbedOpenStream :: MozEmbedClass m => m -> String -> String -> IO ()\nmozEmbedOpenStream m baseURI mimeType =\n withCString baseURI $ \\ basePtr ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_open_stream#} (toMozEmbed m) basePtr mtPtr\n\nmozEmbedAppendDataInternal :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendDataInternal m contents =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged?\n let len' = fromIntegral len in\n {#call gtk_moz_embed_append_data#} (toMozEmbed m) dataPtr len'\n-- >> free dataPtr\n\nmozEmbedCloseStream :: MozEmbedClass m => m -> IO ()\nmozEmbedCloseStream m =\n {#call gtk_moz_embed_close_stream#} (toMozEmbed m)\n\nmozEmbedAppendData :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendData m contents =\n mapM_ (mozEmbedAppendDataInternal m) (chunks 32768 contents)\n\nmozEmbedRenderData :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderData m contents baseURI mimeType = do\n mozEmbedOpenStream m baseURI mimeType\n mozEmbedAppendData m contents\n mozEmbedCloseStream m\n\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = let (ys, zs) = splitAt n xs in ys : chunks n zs\n\n{-\nvoid gtk_moz_embed_render_data (GtkMozEmbed *embed, \n const char *data,\n guint32 len,\n const char *base_uri, \n const char *mime_type)\n-}\n-- -- mozEmbedRenderDataInternal does not work for len' > 2^16\nmozEmbedRenderDataInternal :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderDataInternal m contents baseURI mimeType =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged\n let len' = fromIntegral len in\n-- hPutStrLn stderr (\"mozEmbedRenderData: \" ++ shows len' \" bytes\") >>= \\ _ ->\n withCString baseURI $ \\ basePrt ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_render_data#} (toMozEmbed m) dataPtr len' basePrt mtPtr\n-- >> free dataPtr\n\n{-\nstruct _GtkMozEmbedClass\n{\n [...]\n gint (* open_uri) (GtkMozEmbed *embed, const char *aURI);\n [...]\n}\n-}\n\nonOpenURI :: MozEmbedClass m => m -> (String -> IO Bool) -> IO (ConnectId m)\nonOpenURI = connect_STRING__BOOL \"open_uri\" after\n where\n-- Specify if the handler is to run before (False) or after (True) the\n-- default handler.\n after = False\n\n\n{-\nMore signals to investigate:\n\n gint (* dom_key_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_press) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_dbl_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_over) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_out) (GtkMozEmbed *embed, gpointer dom_event);\n\nUnfortunateley these are not documented on\n\nhttp:\/\/www.mozilla.org\/unix\/gtk-embedding.html\n\n-}\n\nonKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut\n :: (Num n, Integral n, MozEmbedClass m)\n => m -> (Ptr a -> IO n) -> IO (ConnectId m)\nonKeyDown = connect_PTR__INT \"dom_key_down\" False\nonKeyPress = connect_PTR__INT \"dom_key_press\" False\nonKeyUp = connect_PTR__INT \"dom_key_up\" False\nonMouseDown = connect_PTR__INT \"dom_mouse_down\" False\nonMouseUp = connect_PTR__INT \"dom_mouse_up\" False\nonMouseClick = connect_PTR__INT \"dom_mouse_click\" False\nonMouseDoubleClick = connect_PTR__INT \"dom_mouse_dbl_click\" False\nonMouseOver = connect_PTR__INT \"dom_mouse_over\" False\nonMouseOut = connect_PTR__INT \"dom_mouse_out\" False\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"62ecbb01896fd7b53749f3145b0bcb79cf53b7e7","subject":"More haddock for Internals.chs","message":"More haddock for Internals.chs\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-- | 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\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\"\nimport \"Control.Parallel.MPI.Storable\"\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 sendReduce commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ recvReduce 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\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-- | 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{-\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ecd9af3f4ded1a1aa1b561a6f09337d548b60e49","subject":"Trying CInt instead of Int to fix anySource\/anyTag on 64 bit host","message":"Trying CInt instead of Int to fix anySource\/anyTag on 64 bit host\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 (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","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 :: 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\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 = 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,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 :: 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":"1869e45f25b542fcf0c2f3340ce8e4d198b11f6c","subject":"gstreamer: M.S.G.Core.Types.chs: staticPadTemplateGet: Control.Monad.>=> not available before ghc 6.8; don't export StaticPadTemplate constructors","message":"gstreamer: M.S.G.Core.Types.chs: staticPadTemplateGet: Control.Monad.>=> not available before ghc 6.8; don't export StaticPadTemplate constructors\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate {-(..)-},\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet staticPadTemplate =\n {# call static_pad_template_get #} staticPadTemplate >>= takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate(..),\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet =\n {# call static_pad_template_get #} >=> takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"c00dc3897a19220ce529c9e14649cc3d20055637","subject":"[project @ 2004-12-18 20:45:50 by duncan_coutts] tidy up module header","message":"[project @ 2004-12-18 20:45:50 by duncan_coutts]\ntidy up module header\n","repos":"vincenthz\/webkit","old_file":"mozembed\/Graphics\/UI\/Gtk\/MozEmbed.chs","new_file":"mozembed\/Graphics\/UI\/Gtk\/MozEmbed.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget embedding the Mozilla browser engine (Gecko)\n--\n-- Author : Jonas Svensson\n--\n-- Created: 26 February 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2004\/12\/18 20:45:50 $\n--\n-- Copyright (c) 2002 Jonas Svensson\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-- Modified 2004 by Scott West for basic use in gtk2hs\n--\n-- Further modified 2004 by Wolfram Kahl:\n-- * ported to gtk2hs\/c2hs\n-- * added additional interface functions\n-- * circumvented render_data problem\n--\n-- | This widgets embeds Mozilla's browser engine (Gecko) into a GTK+ widget.\n-- See for an API reference.\n--\nmodule Graphics.UI.Gtk.MozEmbed (\n MozEmbed, MozEmbedClass,\n\n mozEmbedNew, mozEmbedSetCompPath,\n\n mozEmbedRenderData,\n mozEmbedOpenStream, mozEmbedAppendData, mozEmbedCloseStream,\n\n onOpenURI,\n\n mozEmbedLoadUrl,\n\n -- the functions below are untested.\n\n onKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut,\n\n mozEmbedSetProfilePath,\n mozEmbedStopLoad, mozEmbedGoBack, mozEmbedGoForward, mozEmbedGetLinkMessage,\n mozEmbedGetJsStatus, mozEmbedGetTitle, mozEmbedGetLocation,\n mozEmbedCanGoBack, mozEmbedCanGoForward, mozEmbedPushStartup,\n mozEmbedPopStartup\n) where\n\nimport Monad\t\t(liftM)\nimport FFI\nimport ForeignPtr\nimport Foreign.Marshal.Utils (toBool)\n\n{#import Object#} (makeNewObject)\n{#import Signal#} (ConnectId, connect_STRING__BOOL, connect_PTR__INT)\n{#import Graphics.UI.Gtk.MozEmbedType #}\nimport Widget (Widget)\n\n{#context lib=\"gtkembedmoz\" prefix =\"gtk\"#}\n\n-- operations\n-- ----------\n\n-- | Create a new MozEmbed\n--\nmozEmbedNew :: IO MozEmbed\nmozEmbedNew = makeNewObject mkMozEmbed $ liftM castPtr {#call moz_embed_new#}\n\nmozEmbedSetCompPath :: String -> IO ()\nmozEmbedSetCompPath str =\n withCString str $ \\strPtr ->\n {#call moz_embed_set_comp_path#}\n strPtr\n\nmozEmbedSetProfilePath :: String -> String -> IO ()\nmozEmbedSetProfilePath dir name =\n withCString dir $ \\dirPtr ->\n withCString name $ \\namePtr ->\n {#call moz_embed_set_profile_path#} dirPtr namePtr\n \nmozEmbedLoadUrl :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedLoadUrl m url =\n withCString url $ \\urlPtr ->\n {#call moz_embed_load_url#}\n (toMozEmbed m)\n urlPtr\n\nmozEmbedStopLoad :: MozEmbedClass m => m -> IO ()\nmozEmbedStopLoad m = \n {#call moz_embed_stop_load#} (toMozEmbed m)\n\nmozEmbedGoBack :: MozEmbedClass m => m -> IO ()\nmozEmbedGoBack m =\n {#call moz_embed_go_back#} (toMozEmbed m)\n\nmozEmbedGoForward :: MozEmbedClass m => m -> IO ()\nmozEmbedGoForward m =\n {#call moz_embed_go_forward#} (toMozEmbed m)\n\nmozEmbedGetLinkMessage :: MozEmbedClass m => m -> IO String\nmozEmbedGetLinkMessage m = \n do\n str <- {#call moz_embed_get_link_message#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetJsStatus :: MozEmbedClass m => m -> IO String\nmozEmbedGetJsStatus m =\n do\n str <- {#call moz_embed_get_js_status#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetTitle :: MozEmbedClass m => m -> IO String\nmozEmbedGetTitle m = \n do\n str <- {#call moz_embed_get_title#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetLocation :: MozEmbedClass m => m -> IO String\nmozEmbedGetLocation m = \n do\n str <- {#call moz_embed_get_location#} (toMozEmbed m)\n peekCString str\n\nmozEmbedCanGoBack :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoBack m =\n liftM toBool $ \n {#call moz_embed_can_go_back#} (toMozEmbed m)\n\nmozEmbedCanGoForward :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoForward m =\n liftM toBool $ \n {#call moz_embed_can_go_forward#} (toMozEmbed m)\n\nmozEmbedPushStartup :: IO ()\nmozEmbedPushStartup =\n {#call moz_embed_push_startup#}\n\nmozEmbedPopStartup :: IO ()\nmozEmbedPopStartup =\n {#call moz_embed_pop_startup#}\n\n{-\nvoid gtk_moz_embed_open_stream (GtkMozEmbed *embed,\n\t\t\t\t\t const char *base_uri,\n\t\t\t\t\t const char *mime_type);\nvoid gtk_moz_embed_append_data (GtkMozEmbed *embed,\n\t\t\t\t\t const char *data, guint32 len);\nvoid gtk_moz_embed_close_stream (GtkMozEmbed *embed);\n-}\n\nmozEmbedOpenStream :: MozEmbedClass m => m -> String -> String -> IO ()\nmozEmbedOpenStream m baseURI mimeType =\n withCString baseURI $ \\ basePtr ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_open_stream#} (toMozEmbed m) basePtr mtPtr\n\nmozEmbedAppendDataInternal :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendDataInternal m contents =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged?\n let len' = fromIntegral len in\n {#call gtk_moz_embed_append_data#} (toMozEmbed m) dataPtr len'\n-- >> free dataPtr\n\nmozEmbedCloseStream :: MozEmbedClass m => m -> IO ()\nmozEmbedCloseStream m =\n {#call gtk_moz_embed_close_stream#} (toMozEmbed m)\n\nmozEmbedAppendData :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendData m contents =\n mapM_ (mozEmbedAppendDataInternal m) (chunks 32768 contents)\n\nmozEmbedRenderData :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderData m contents baseURI mimeType = do\n mozEmbedOpenStream m baseURI mimeType\n mozEmbedAppendData m contents\n mozEmbedCloseStream m\n\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = let (ys, zs) = splitAt n xs in ys : chunks n zs\n\n{-\nvoid gtk_moz_embed_render_data (GtkMozEmbed *embed, \n const char *data,\n guint32 len,\n const char *base_uri, \n const char *mime_type)\n-}\n-- -- mozEmbedRenderDataInternal does not work for len' > 2^16\nmozEmbedRenderDataInternal :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderDataInternal m contents baseURI mimeType =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged\n let len' = fromIntegral len in\n-- hPutStrLn stderr (\"mozEmbedRenderData: \" ++ shows len' \" bytes\") >>= \\ _ ->\n withCString baseURI $ \\ basePrt ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_render_data#} (toMozEmbed m) dataPtr len' basePrt mtPtr\n-- >> free dataPtr\n\n{-\nstruct _GtkMozEmbedClass\n{\n [...]\n gint (* open_uri) (GtkMozEmbed *embed, const char *aURI);\n [...]\n}\n-}\n\nonOpenURI :: MozEmbedClass m => m -> (String -> IO Bool) -> IO (ConnectId m)\nonOpenURI = connect_STRING__BOOL \"open_uri\" after\n where\n-- Specify if the handler is to run before (False) or after (True) the\n-- default handler.\n after = False\n\n\n{-\nMore signals to investigate:\n\n gint (* dom_key_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_press) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_dbl_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_over) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_out) (GtkMozEmbed *embed, gpointer dom_event);\n\nUnfortunateley these are not documented on\n\nhttp:\/\/www.mozilla.org\/unix\/gtk-embedding.html\n\n-}\n\nonKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut\n :: (Num n, Integral n, MozEmbedClass m)\n => m -> (Ptr a -> IO n) -> IO (ConnectId m)\nonKeyDown = connect_PTR__INT \"dom_key_down\" False\nonKeyPress = connect_PTR__INT \"dom_key_press\" False\nonKeyUp = connect_PTR__INT \"dom_key_up\" False\nonMouseDown = connect_PTR__INT \"dom_mouse_down\" False\nonMouseUp = connect_PTR__INT \"dom_mouse_up\" False\nonMouseClick = connect_PTR__INT \"dom_mouse_click\" False\nonMouseDoubleClick = connect_PTR__INT \"dom_mouse_dbl_click\" False\nonMouseOver = connect_PTR__INT \"dom_mouse_over\" False\nonMouseOut = connect_PTR__INT \"dom_mouse_out\" False\n\n","old_contents":"-- |GIMP Toolkit (GTK) Binding for Haskell: widget embedding the -*-haskell-*-\n-- Mozilla browser engine (Gecko)\n--\n-- Author : Jonas Svensson\n-- Created: 26 February 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2004\/12\/17 21:21:44 $\n--\n-- Copyright (c) 2002 Jonas Svensson\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--\n-- Modified 2004 by Scott West for basic use in gtk2hs\n--\n-- Further modified 2004 by Wolfram Kahl:\n-- * ported to gtk2hs\/c2hs\n-- * added additional interface functions\n-- * circumvented render_data problem\n--\n--\n--- DESCRIPTION ---------------------------------------------------------------\n--\n-- This widgets embeds Mozilla's browser engine (Gecko) into a GTK+ widget.\n--\n--- DOCU ----------------------------------------------------------------------\n--\n-- Language: Haskell 98 Binding Module\n--\n--- TODO ----------------------------------------------------------------------\n--\n\nmodule Graphics.UI.Gtk.MozEmbed (\n MozEmbed, MozEmbedClass,\n\n mozEmbedNew, mozEmbedSetCompPath,\n\n mozEmbedRenderData,\n mozEmbedOpenStream, mozEmbedAppendData, mozEmbedCloseStream,\n\n onOpenURI,\n\n mozEmbedLoadUrl,\n\n -- the functions below are untested.\n\n onKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut,\n\n mozEmbedSetProfilePath,\n mozEmbedStopLoad, mozEmbedGoBack, mozEmbedGoForward, mozEmbedGetLinkMessage,\n mozEmbedGetJsStatus, mozEmbedGetTitle, mozEmbedGetLocation,\n mozEmbedCanGoBack, mozEmbedCanGoForward, mozEmbedPushStartup,\n mozEmbedPopStartup\n) where\n\nimport Monad\t\t(liftM)\nimport FFI\nimport ForeignPtr\nimport Foreign.Marshal.Utils (toBool)\n\n{#import Object#} (makeNewObject)\n{#import Signal#} (ConnectId, connect_STRING__BOOL, connect_PTR__INT)\n{#import Graphics.UI.Gtk.MozEmbedType #}\nimport Widget (Widget)\n\n{#context lib=\"gtkembedmoz\" prefix =\"gtk\"#}\n\n-- operations\n-- ----------\n\n-- | Create a new MozEmbed\n--\nmozEmbedNew :: IO MozEmbed\nmozEmbedNew = makeNewObject mkMozEmbed $ liftM castPtr {#call moz_embed_new#}\n\nmozEmbedSetCompPath :: String -> IO ()\nmozEmbedSetCompPath str =\n withCString str $ \\strPtr ->\n {#call moz_embed_set_comp_path#}\n strPtr\n\nmozEmbedSetProfilePath :: String -> String -> IO ()\nmozEmbedSetProfilePath dir name =\n withCString dir $ \\dirPtr ->\n withCString name $ \\namePtr ->\n {#call moz_embed_set_profile_path#} dirPtr namePtr\n \nmozEmbedLoadUrl :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedLoadUrl m url =\n withCString url $ \\urlPtr ->\n {#call moz_embed_load_url#}\n (toMozEmbed m)\n urlPtr\n\nmozEmbedStopLoad :: MozEmbedClass m => m -> IO ()\nmozEmbedStopLoad m = \n {#call moz_embed_stop_load#} (toMozEmbed m)\n\nmozEmbedGoBack :: MozEmbedClass m => m -> IO ()\nmozEmbedGoBack m =\n {#call moz_embed_go_back#} (toMozEmbed m)\n\nmozEmbedGoForward :: MozEmbedClass m => m -> IO ()\nmozEmbedGoForward m =\n {#call moz_embed_go_forward#} (toMozEmbed m)\n\nmozEmbedGetLinkMessage :: MozEmbedClass m => m -> IO String\nmozEmbedGetLinkMessage m = \n do\n str <- {#call moz_embed_get_link_message#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetJsStatus :: MozEmbedClass m => m -> IO String\nmozEmbedGetJsStatus m =\n do\n str <- {#call moz_embed_get_js_status#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetTitle :: MozEmbedClass m => m -> IO String\nmozEmbedGetTitle m = \n do\n str <- {#call moz_embed_get_title#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetLocation :: MozEmbedClass m => m -> IO String\nmozEmbedGetLocation m = \n do\n str <- {#call moz_embed_get_location#} (toMozEmbed m)\n peekCString str\n\nmozEmbedCanGoBack :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoBack m =\n liftM toBool $ \n {#call moz_embed_can_go_back#} (toMozEmbed m)\n\nmozEmbedCanGoForward :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoForward m =\n liftM toBool $ \n {#call moz_embed_can_go_forward#} (toMozEmbed m)\n\nmozEmbedPushStartup :: IO ()\nmozEmbedPushStartup =\n {#call moz_embed_push_startup#}\n\nmozEmbedPopStartup :: IO ()\nmozEmbedPopStartup =\n {#call moz_embed_pop_startup#}\n\n{-\nvoid gtk_moz_embed_open_stream (GtkMozEmbed *embed,\n\t\t\t\t\t const char *base_uri,\n\t\t\t\t\t const char *mime_type);\nvoid gtk_moz_embed_append_data (GtkMozEmbed *embed,\n\t\t\t\t\t const char *data, guint32 len);\nvoid gtk_moz_embed_close_stream (GtkMozEmbed *embed);\n-}\n\nmozEmbedOpenStream :: MozEmbedClass m => m -> String -> String -> IO ()\nmozEmbedOpenStream m baseURI mimeType =\n withCString baseURI $ \\ basePtr ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_open_stream#} (toMozEmbed m) basePtr mtPtr\n\nmozEmbedAppendDataInternal :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendDataInternal m contents =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged?\n let len' = fromIntegral len in\n {#call gtk_moz_embed_append_data#} (toMozEmbed m) dataPtr len'\n-- >> free dataPtr\n\nmozEmbedCloseStream :: MozEmbedClass m => m -> IO ()\nmozEmbedCloseStream m =\n {#call gtk_moz_embed_close_stream#} (toMozEmbed m)\n\nmozEmbedAppendData :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendData m contents =\n mapM_ (mozEmbedAppendDataInternal m) (chunks 32768 contents)\n\nmozEmbedRenderData :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderData m contents baseURI mimeType = do\n mozEmbedOpenStream m baseURI mimeType\n mozEmbedAppendData m contents\n mozEmbedCloseStream m\n\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = let (ys, zs) = splitAt n xs in ys : chunks n zs\n\n{-\nvoid gtk_moz_embed_render_data (GtkMozEmbed *embed, \n const char *data,\n guint32 len,\n const char *base_uri, \n const char *mime_type)\n-}\n-- -- mozEmbedRenderDataInternal does not work for len' > 2^16\nmozEmbedRenderDataInternal :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderDataInternal m contents baseURI mimeType =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged\n let len' = fromIntegral len in\n-- hPutStrLn stderr (\"mozEmbedRenderData: \" ++ shows len' \" bytes\") >>= \\ _ ->\n withCString baseURI $ \\ basePrt ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_render_data#} (toMozEmbed m) dataPtr len' basePrt mtPtr\n-- >> free dataPtr\n\n{-\nstruct _GtkMozEmbedClass\n{\n [...]\n gint (* open_uri) (GtkMozEmbed *embed, const char *aURI);\n [...]\n}\n-}\n\nonOpenURI :: MozEmbedClass m => m -> (String -> IO Bool) -> IO (ConnectId m)\nonOpenURI = connect_STRING__BOOL \"open_uri\" after\n where\n-- Specify if the handler is to run before (False) or after (True) the\n-- default handler.\n after = False\n\n\n{-\nMore signals to investigate:\n\n gint (* dom_key_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_press) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_dbl_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_over) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_out) (GtkMozEmbed *embed, gpointer dom_event);\n\nUnfortunateley these are not documented on\n\nhttp:\/\/www.mozilla.org\/unix\/gtk-embedding.html\n\n-}\n\nonKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut\n :: (Num n, Integral n, MozEmbedClass m)\n => m -> (Ptr a -> IO n) -> IO (ConnectId m)\nonKeyDown = connect_PTR__INT \"dom_key_down\" False\nonKeyPress = connect_PTR__INT \"dom_key_press\" False\nonKeyUp = connect_PTR__INT \"dom_key_up\" False\nonMouseDown = connect_PTR__INT \"dom_mouse_down\" False\nonMouseUp = connect_PTR__INT \"dom_mouse_up\" False\nonMouseClick = connect_PTR__INT \"dom_mouse_click\" False\nonMouseDoubleClick = connect_PTR__INT \"dom_mouse_dbl_click\" False\nonMouseOver = connect_PTR__INT \"dom_mouse_over\" False\nonMouseOut = connect_PTR__INT \"dom_mouse_out\" False\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b44e34121a59e453ce5f7fe15ce31032ff4934e2","subject":"Remove removed signals in the re-export module.","message":"Remove removed signals in the re-export module.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk.chs","new_file":"gtk\/Graphics\/UI\/Gtk.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n--\n-- Created: 9 April 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-- Everything that is marked as deprecated, vanishing or useless for\n-- applications is not bound.\n--\n-- The following modules are not bound:\n-- DialogMessage : has only one variadic function which cannot be bound.\n--\t\t The same functionality can be simulated with Dialog.\n-- Item :\t The only child of this abstract class is MenuItem. The\n--\t\t three signals Item defines are therefore bound in \n--\t\t MenuItem.\n--\n-- TODO\n--\n-- Every module that is commented out and not mentioned above.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This module gathers all publicly available functions from the Gtk binding.\n--\nmodule Graphics.UI.Gtk (\n -- * General things, initialization\n module Graphics.UI.Gtk.General.General,\n module Graphics.UI.Gtk.General.IconFactory,\n module Graphics.UI.Gtk.General.StockItems,\n module Graphics.UI.Gtk.General.Selection,\n module Graphics.UI.Gtk.General.Drag,\n module Graphics.UI.Gtk.Gdk.Keys,\n module Graphics.UI.Gtk.General.Style,\n module Graphics.UI.Gtk.General.RcStyle,\n module Graphics.UI.Gtk.General.Clipboard,\n\n -- * Drawing and other Low-Level Operations\n module Graphics.UI.Gtk.Gdk.Cursor,\n module Graphics.UI.Gtk.Gdk.Drawable,\n module Graphics.UI.Gtk.Gdk.DrawWindow,\n module Graphics.UI.Gtk.Gdk.Region,\n-- module Graphics.UI.Gtk.Gdk.GC,\n module Graphics.UI.Gtk.Gdk.EventM,\n module Graphics.UI.Gtk.Gdk.Pixbuf,\n module Graphics.UI.Gtk.Gdk.Pixmap,\n module Graphics.UI.Gtk.Gdk.Screen,\n module Graphics.UI.Gtk.Gdk.Display,\n module Graphics.UI.Gtk.Gdk.Gdk,\n -- ** cairo integration\n module Graphics.UI.Gtk.Cairo,\n -- * Windows\n module Graphics.UI.Gtk.Windows.Window,\n module Graphics.UI.Gtk.Windows.Invisible,\n module Graphics.UI.Gtk.Windows.Dialog,\n module Graphics.UI.Gtk.Windows.AboutDialog,\n module Graphics.UI.Gtk.Windows.MessageDialog,\n module Graphics.UI.Gtk.Windows.WindowGroup,\n -- * Display widgets,\n module Graphics.UI.Gtk.Display.AccelLabel,\n module Graphics.UI.Gtk.Display.Image,\n module Graphics.UI.Gtk.Display.Label,\n module Graphics.UI.Gtk.Display.ProgressBar,\n module Graphics.UI.Gtk.Display.Statusbar,\n module Graphics.UI.Gtk.Display.StatusIcon,\n -- * Buttons and toggles\n module Graphics.UI.Gtk.Buttons.Button,\n module Graphics.UI.Gtk.Buttons.CheckButton,\n module Graphics.UI.Gtk.Buttons.RadioButton,\n module Graphics.UI.Gtk.Buttons.ToggleButton,\n -- * Numeric\\\/text data entry\n module Graphics.UI.Gtk.Entry.Editable,\n module Graphics.UI.Gtk.Entry.Entry,\n module Graphics.UI.Gtk.Entry.EntryCompletion,\n module Graphics.UI.Gtk.Entry.HScale,\n module Graphics.UI.Gtk.Entry.VScale,\n module Graphics.UI.Gtk.Entry.SpinButton,\n -- * Multiline text editor\n module Graphics.UI.Gtk.Multiline.TextIter,\n module Graphics.UI.Gtk.Multiline.TextMark,\n module Graphics.UI.Gtk.Multiline.TextBuffer,\n module Graphics.UI.Gtk.Multiline.TextTag,\n module Graphics.UI.Gtk.Multiline.TextTagTable,\n module Graphics.UI.Gtk.Multiline.TextView,\n -- * Tree and list widget\n module Graphics.UI.Gtk.ModelView.CellLayout,\n module Graphics.UI.Gtk.ModelView.CellRenderer,\n module Graphics.UI.Gtk.ModelView.CellRendererCombo,\n module Graphics.UI.Gtk.ModelView.CellRendererPixbuf,\n module Graphics.UI.Gtk.ModelView.CellRendererProgress,\n module Graphics.UI.Gtk.ModelView.CellRendererText,\n module Graphics.UI.Gtk.ModelView.CellRendererToggle,\n module Graphics.UI.Gtk.ModelView.CellView,\n module Graphics.UI.Gtk.ModelView.CustomStore,\n module Graphics.UI.Gtk.ModelView.IconView,\n module Graphics.UI.Gtk.ModelView.ListStore,\n module Graphics.UI.Gtk.ModelView.TreeDrag,\n module Graphics.UI.Gtk.ModelView.TreeModel,\n module Graphics.UI.Gtk.ModelView.TreeModelSort,\n module Graphics.UI.Gtk.ModelView.TreeSortable,\n module Graphics.UI.Gtk.ModelView.TreeModelFilter,\n module Graphics.UI.Gtk.ModelView.TreeRowReference,\n module Graphics.UI.Gtk.ModelView.TreeSelection,\n module Graphics.UI.Gtk.ModelView.TreeStore,\n module Graphics.UI.Gtk.ModelView.TreeView,\n module Graphics.UI.Gtk.ModelView.TreeViewColumn,\n -- * Menus, combo box, toolbar\n module Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Combo,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBox,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry,\n module Graphics.UI.Gtk.MenuComboToolbar.Menu,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuBar,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuShell,\n module Graphics.UI.Gtk.MenuComboToolbar.OptionMenu,\n module Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Toolbar,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolItem,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem,\n-- * Action-based menus and toolbars\n module Graphics.UI.Gtk.ActionMenuToolbar.Action,\n module Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup,\n module Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.RadioAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.UIManager,\n -- * Selectors (file\\\/font\\\/color)\n module Graphics.UI.Gtk.Selectors.ColorSelection,\n module Graphics.UI.Gtk.Selectors.ColorSelectionDialog,\n module Graphics.UI.Gtk.Selectors.ColorButton,\n module Graphics.UI.Gtk.Selectors.FileSelection,\n module Graphics.UI.Gtk.Selectors.FontSelection,\n module Graphics.UI.Gtk.Selectors.FontSelectionDialog,\n module Graphics.UI.Gtk.Selectors.FontButton,\n-- module InputDialog,\n -- ** File chooser\n module Graphics.UI.Gtk.Selectors.FileChooser,\n module Graphics.UI.Gtk.Selectors.FileChooserDialog,\n module Graphics.UI.Gtk.Selectors.FileChooserWidget,\n module Graphics.UI.Gtk.Selectors.FileChooserButton,\n module Graphics.UI.Gtk.Selectors.FileFilter,\n -- * Layout containers\n module Graphics.UI.Gtk.Layout.Alignment,\n module Graphics.UI.Gtk.Layout.AspectFrame,\n module Graphics.UI.Gtk.Layout.HBox,\n module Graphics.UI.Gtk.Layout.HButtonBox,\n module Graphics.UI.Gtk.Layout.Fixed,\n module Graphics.UI.Gtk.Layout.HPaned,\n module Graphics.UI.Gtk.Layout.Layout,\n module Graphics.UI.Gtk.Layout.Notebook,\n module Graphics.UI.Gtk.Layout.Expander,\n module Graphics.UI.Gtk.Layout.Table,\n module Graphics.UI.Gtk.Layout.VBox,\n module Graphics.UI.Gtk.Layout.VButtonBox,\n module Graphics.UI.Gtk.Layout.VPaned,\n -- * Ornaments\n module Graphics.UI.Gtk.Ornaments.Frame,\n module Graphics.UI.Gtk.Ornaments.HSeparator,\n module Graphics.UI.Gtk.Ornaments.VSeparator,\n -- * Scrolling\n module Graphics.UI.Gtk.Scrolling.HScrollbar,\n module Graphics.UI.Gtk.Scrolling.ScrolledWindow,\n module Graphics.UI.Gtk.Scrolling.VScrollbar,\n -- * Miscellaneous\n module Graphics.UI.Gtk.Misc.Adjustment,\n module Graphics.UI.Gtk.Misc.Arrow,\n module Graphics.UI.Gtk.Misc.Calendar,\n module Graphics.UI.Gtk.Misc.DrawingArea,\n module Graphics.UI.Gtk.Misc.EventBox,\n module Graphics.UI.Gtk.Misc.HandleBox,\n module Graphics.UI.Gtk.Misc.IMMulticontext,\n module Graphics.UI.Gtk.Misc.SizeGroup,\n module Graphics.UI.Gtk.Misc.Tooltips,\n module Graphics.UI.Gtk.Misc.Viewport,\n -- * Abstract base classes\n module Graphics.UI.Gtk.Abstract.Box,\n module Graphics.UI.Gtk.Abstract.ButtonBox,\n module Graphics.UI.Gtk.Abstract.Container,\n module Graphics.UI.Gtk.Abstract.Bin,\n module Graphics.UI.Gtk.Abstract.Misc,\n module Graphics.UI.Gtk.Abstract.IMContext,\n module Graphics.UI.Gtk.Abstract.Object,\n module Graphics.UI.Gtk.Abstract.Paned,\n module Graphics.UI.Gtk.Abstract.Range,\n module Graphics.UI.Gtk.Abstract.Scale,\n module Graphics.UI.Gtk.Abstract.Scrollbar,\n module Graphics.UI.Gtk.Abstract.Separator,\n module Graphics.UI.Gtk.Abstract.Widget,\n -- * Cross-process embedding\n module Graphics.UI.Gtk.Embedding.Plug,\n module Graphics.UI.Gtk.Embedding.Socket,\n -- * Non-widgets\n module System.Glib.Signals,\n module System.Glib.Attributes,\n module System.Glib.GObject,\n module Graphics.UI.Gtk.Builder,\n\n -- * Pango text layout modules\n module Graphics.Rendering.Pango.Context,\n module Graphics.Rendering.Pango.Markup,\n module Graphics.Rendering.Pango.Layout,\n module Graphics.Rendering.Pango.Rendering,\n module Graphics.Rendering.Pango.Font,\n module Graphics.Rendering.Pango.Enums\n ) where\n\n-- general things, initialization\nimport Graphics.UI.Gtk.General.General\nimport Graphics.UI.Gtk.General.IconFactory\nimport Graphics.UI.Gtk.General.StockItems\nimport Graphics.UI.Gtk.General.Selection\nimport Graphics.UI.Gtk.General.Drag\nimport Graphics.UI.Gtk.General.Clipboard\n-- drawing\nimport Graphics.UI.Gtk.Gdk.Keys\nimport Graphics.UI.Gtk.General.Style\nimport Graphics.UI.Gtk.General.RcStyle\nimport Graphics.UI.Gtk.Gdk.Cursor\nimport Graphics.UI.Gtk.Gdk.Drawable\nimport Graphics.UI.Gtk.Gdk.DrawWindow\nimport Graphics.UI.Gtk.Gdk.Region\t\thiding (makeNewRegion)\n--import Graphics.UI.Gtk.Gdk.GC\nimport Graphics.UI.Gtk.Gdk.EventM\nimport Graphics.UI.Gtk.Gdk.Pixbuf\nimport Graphics.UI.Gtk.Gdk.Pixmap\nimport Graphics.UI.Gtk.Gdk.Screen\nimport Graphics.UI.Gtk.Gdk.Display\nimport Graphics.UI.Gtk.Gdk.Gdk\n-- cairo integration\nimport Graphics.UI.Gtk.Cairo\n-- windows\nimport Graphics.UI.Gtk.Windows.Dialog\nimport Graphics.UI.Gtk.Windows.Window\nimport Graphics.UI.Gtk.Windows.Invisible\nimport Graphics.UI.Gtk.Windows.AboutDialog\nimport Graphics.UI.Gtk.Windows.MessageDialog\nimport Graphics.UI.Gtk.Windows.WindowGroup\n-- display widgets\nimport Graphics.UI.Gtk.Display.AccelLabel\nimport Graphics.UI.Gtk.Display.Image\nimport Graphics.UI.Gtk.Display.Label\nimport Graphics.UI.Gtk.Display.ProgressBar\nimport Graphics.UI.Gtk.Display.Statusbar\n#if GTK_CHECK_VERSION(2,10,0) && !DISABLE_DEPRECATED\nimport Graphics.UI.Gtk.Display.StatusIcon hiding (onActivate,afterActivate,onPopupMenu,afterPopupMenu)\n#else\nimport Graphics.UI.Gtk.Display.StatusIcon\n#endif\n-- buttons and toggles\nimport Graphics.UI.Gtk.Buttons.Button\nimport Graphics.UI.Gtk.Buttons.CheckButton\nimport Graphics.UI.Gtk.Buttons.RadioButton\nimport Graphics.UI.Gtk.Buttons.ToggleButton\n-- numeric\\\/text data entry\nimport Graphics.UI.Gtk.Entry.Editable\nimport Graphics.UI.Gtk.Entry.Entry\nimport Graphics.UI.Gtk.Entry.EntryCompletion\nimport Graphics.UI.Gtk.Entry.HScale\nimport Graphics.UI.Gtk.Entry.VScale\nimport Graphics.UI.Gtk.Entry.SpinButton\n-- multiline text editor\nimport Graphics.UI.Gtk.Multiline.TextIter\nimport Graphics.UI.Gtk.Multiline.TextMark\nimport Graphics.UI.Gtk.Multiline.TextBuffer\nimport Graphics.UI.Gtk.Multiline.TextTag\nimport Graphics.UI.Gtk.Multiline.TextTagTable\nimport qualified Graphics.UI.Gtk.Multiline.TextView\nimport Graphics.UI.Gtk.Multiline.TextView\n-- tree and list widget\nimport Graphics.UI.Gtk.ModelView.CellLayout\nimport Graphics.UI.Gtk.ModelView.CellRenderer\nimport Graphics.UI.Gtk.ModelView.CellRendererCombo\nimport Graphics.UI.Gtk.ModelView.CellRendererPixbuf\nimport Graphics.UI.Gtk.ModelView.CellRendererProgress\nimport Graphics.UI.Gtk.ModelView.CellRendererText\nimport Graphics.UI.Gtk.ModelView.CellRendererToggle\nimport Graphics.UI.Gtk.ModelView.CellView\nimport Graphics.UI.Gtk.ModelView.CustomStore\nimport Graphics.UI.Gtk.ModelView.IconView\nimport Graphics.UI.Gtk.ModelView.ListStore\nimport Graphics.UI.Gtk.ModelView.TreeDrag\nimport Graphics.UI.Gtk.ModelView.TreeModel\nimport Graphics.UI.Gtk.ModelView.TreeModelSort\nimport Graphics.UI.Gtk.ModelView.TreeSortable\nimport Graphics.UI.Gtk.ModelView.TreeModelFilter\nimport Graphics.UI.Gtk.ModelView.TreeRowReference\nimport Graphics.UI.Gtk.ModelView.TreeSelection\nimport Graphics.UI.Gtk.ModelView.TreeStore\nimport Graphics.UI.Gtk.ModelView.TreeView\nimport Graphics.UI.Gtk.ModelView.TreeViewColumn\n-- menus, combo box, toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.Combo\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBox\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry\n-- import ItemFactory\nimport Graphics.UI.Gtk.MenuComboToolbar.Menu\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuBar\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuShell\nimport Graphics.UI.Gtk.MenuComboToolbar.OptionMenu\nimport Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.Toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolItem\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem\n-- action based menus and toolbars\nimport Graphics.UI.Gtk.ActionMenuToolbar.Action\nimport Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup\nimport Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.RadioAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.UIManager\n-- selectors (file\\\/font\\\/color\\\/input device)\nimport Graphics.UI.Gtk.Selectors.ColorSelection\nimport Graphics.UI.Gtk.Selectors.ColorSelectionDialog\nimport Graphics.UI.Gtk.Selectors.ColorButton\nimport Graphics.UI.Gtk.Selectors.FileSelection\nimport Graphics.UI.Gtk.Selectors.FileChooser\nimport Graphics.UI.Gtk.Selectors.FileChooserDialog\nimport Graphics.UI.Gtk.Selectors.FileChooserWidget\nimport Graphics.UI.Gtk.Selectors.FileChooserButton\nimport Graphics.UI.Gtk.Selectors.FileFilter\nimport Graphics.UI.Gtk.Selectors.FontSelection\nimport Graphics.UI.Gtk.Selectors.FontSelectionDialog\nimport Graphics.UI.Gtk.Selectors.FontButton\n--import InputDialog\n-- layout containers\nimport Graphics.UI.Gtk.Layout.Alignment\nimport Graphics.UI.Gtk.Layout.AspectFrame\nimport Graphics.UI.Gtk.Layout.HBox\nimport Graphics.UI.Gtk.Layout.VBox\nimport Graphics.UI.Gtk.Layout.HButtonBox\nimport Graphics.UI.Gtk.Layout.VButtonBox\nimport Graphics.UI.Gtk.Layout.Fixed\nimport Graphics.UI.Gtk.Layout.HPaned\nimport Graphics.UI.Gtk.Layout.VPaned\nimport Graphics.UI.Gtk.Layout.Layout\nimport Graphics.UI.Gtk.Layout.Notebook\nimport Graphics.UI.Gtk.Layout.Expander\nimport Graphics.UI.Gtk.Layout.Table\n-- ornaments\nimport Graphics.UI.Gtk.Ornaments.Frame\nimport Graphics.UI.Gtk.Ornaments.HSeparator\nimport Graphics.UI.Gtk.Ornaments.VSeparator\n-- scrolling\nimport Graphics.UI.Gtk.Scrolling.HScrollbar\nimport Graphics.UI.Gtk.Scrolling.VScrollbar\nimport Graphics.UI.Gtk.Scrolling.ScrolledWindow\n-- miscellaneous\nimport Graphics.UI.Gtk.Misc.Adjustment\nimport Graphics.UI.Gtk.Misc.Arrow\nimport Graphics.UI.Gtk.Misc.Calendar\nimport Graphics.UI.Gtk.Misc.DrawingArea\nimport Graphics.UI.Gtk.Misc.EventBox\nimport Graphics.UI.Gtk.Misc.HandleBox\nimport Graphics.UI.Gtk.Misc.IMMulticontext\nimport Graphics.UI.Gtk.Misc.SizeGroup\nimport Graphics.UI.Gtk.Misc.Tooltips\nimport Graphics.UI.Gtk.Misc.Viewport\n--import Accessible\n-- abstract base classes\nimport Graphics.UI.Gtk.Abstract.Box\nimport Graphics.UI.Gtk.Abstract.ButtonBox\nimport Graphics.UI.Gtk.Abstract.Container\nimport Graphics.UI.Gtk.Abstract.Bin\nimport Graphics.UI.Gtk.Abstract.Misc\nimport Graphics.UI.Gtk.Abstract.IMContext\nimport Graphics.UI.Gtk.Abstract.Object (\n Object,\n ObjectClass,\n castToObject,\n toObject,\n GWeakNotify,\n objectWeakref,\n objectWeakunref,\n objectDestroy )\nimport Graphics.UI.Gtk.Abstract.Paned\nimport Graphics.UI.Gtk.Abstract.Range\nimport Graphics.UI.Gtk.Abstract.Scale\nimport Graphics.UI.Gtk.Abstract.Scrollbar\nimport Graphics.UI.Gtk.Abstract.Separator\nimport Graphics.UI.Gtk.Abstract.Widget\n-- cross-process embedding\nimport Graphics.UI.Gtk.Embedding.Plug\nimport Graphics.UI.Gtk.Embedding.Socket\n\n-- non widgets\nimport System.Glib.Signals\n{- do eport 'on' and 'after'\n\t\t(ConnectId, disconnect,\n\t\t\t\t\t signalDisconnect,\n\t\t\t\t\t signalBlock,\n\t\t\t\t\t signalUnblock)\n-}\nimport System.Glib.Attributes\nimport System.Glib.GObject (\n GObject,\n GObjectClass,\n toGObject,\n castToGObject,\n quarkFromString,\n objectCreateAttribute,\n objectSetAttribute,\n objectGetAttributeUnsafe,\n isA\n )\nimport Graphics.UI.Gtk.Builder\n \n-- pango modules\nimport Graphics.Rendering.Pango.Context\nimport Graphics.Rendering.Pango.Markup\nimport Graphics.Rendering.Pango.Layout\nimport Graphics.Rendering.Pango.Rendering\nimport Graphics.Rendering.Pango.Font\nimport Graphics.Rendering.Pango.Enums\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n--\n-- Created: 9 April 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-- Everything that is marked as deprecated, vanishing or useless for\n-- applications is not bound.\n--\n-- The following modules are not bound:\n-- DialogMessage : has only one variadic function which cannot be bound.\n--\t\t The same functionality can be simulated with Dialog.\n-- Item :\t The only child of this abstract class is MenuItem. The\n--\t\t three signals Item defines are therefore bound in \n--\t\t MenuItem.\n--\n-- TODO\n--\n-- Every module that is commented out and not mentioned above.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This module gathers all publicly available functions from the Gtk binding.\n--\nmodule Graphics.UI.Gtk (\n -- * General things, initialization\n module Graphics.UI.Gtk.General.General,\n module Graphics.UI.Gtk.General.IconFactory,\n module Graphics.UI.Gtk.General.StockItems,\n module Graphics.UI.Gtk.General.Selection,\n module Graphics.UI.Gtk.General.Drag,\n module Graphics.UI.Gtk.Gdk.Keys,\n module Graphics.UI.Gtk.General.Style,\n module Graphics.UI.Gtk.General.RcStyle,\n module Graphics.UI.Gtk.General.Clipboard,\n\n -- * Drawing and other Low-Level Operations\n module Graphics.UI.Gtk.Gdk.Cursor,\n module Graphics.UI.Gtk.Gdk.Drawable,\n module Graphics.UI.Gtk.Gdk.DrawWindow,\n module Graphics.UI.Gtk.Gdk.Region,\n-- module Graphics.UI.Gtk.Gdk.GC,\n module Graphics.UI.Gtk.Gdk.EventM,\n module Graphics.UI.Gtk.Gdk.Pixbuf,\n module Graphics.UI.Gtk.Gdk.Pixmap,\n module Graphics.UI.Gtk.Gdk.Screen,\n module Graphics.UI.Gtk.Gdk.Display,\n module Graphics.UI.Gtk.Gdk.Gdk,\n -- ** cairo integration\n module Graphics.UI.Gtk.Cairo,\n -- * Windows\n module Graphics.UI.Gtk.Windows.Window,\n module Graphics.UI.Gtk.Windows.Invisible,\n module Graphics.UI.Gtk.Windows.Dialog,\n module Graphics.UI.Gtk.Windows.AboutDialog,\n module Graphics.UI.Gtk.Windows.MessageDialog,\n module Graphics.UI.Gtk.Windows.WindowGroup,\n -- * Display widgets,\n module Graphics.UI.Gtk.Display.AccelLabel,\n module Graphics.UI.Gtk.Display.Image,\n module Graphics.UI.Gtk.Display.Label,\n module Graphics.UI.Gtk.Display.ProgressBar,\n module Graphics.UI.Gtk.Display.Statusbar,\n module Graphics.UI.Gtk.Display.StatusIcon,\n -- * Buttons and toggles\n module Graphics.UI.Gtk.Buttons.Button,\n module Graphics.UI.Gtk.Buttons.CheckButton,\n module Graphics.UI.Gtk.Buttons.RadioButton,\n module Graphics.UI.Gtk.Buttons.ToggleButton,\n -- * Numeric\\\/text data entry\n module Graphics.UI.Gtk.Entry.Editable,\n module Graphics.UI.Gtk.Entry.Entry,\n module Graphics.UI.Gtk.Entry.EntryCompletion,\n module Graphics.UI.Gtk.Entry.HScale,\n module Graphics.UI.Gtk.Entry.VScale,\n module Graphics.UI.Gtk.Entry.SpinButton,\n -- * Multiline text editor\n module Graphics.UI.Gtk.Multiline.TextIter,\n module Graphics.UI.Gtk.Multiline.TextMark,\n module Graphics.UI.Gtk.Multiline.TextBuffer,\n module Graphics.UI.Gtk.Multiline.TextTag,\n module Graphics.UI.Gtk.Multiline.TextTagTable,\n module Graphics.UI.Gtk.Multiline.TextView,\n -- * Tree and list widget\n module Graphics.UI.Gtk.ModelView.CellLayout,\n module Graphics.UI.Gtk.ModelView.CellRenderer,\n module Graphics.UI.Gtk.ModelView.CellRendererCombo,\n module Graphics.UI.Gtk.ModelView.CellRendererPixbuf,\n module Graphics.UI.Gtk.ModelView.CellRendererProgress,\n module Graphics.UI.Gtk.ModelView.CellRendererText,\n module Graphics.UI.Gtk.ModelView.CellRendererToggle,\n module Graphics.UI.Gtk.ModelView.CellView,\n module Graphics.UI.Gtk.ModelView.CustomStore,\n module Graphics.UI.Gtk.ModelView.IconView,\n module Graphics.UI.Gtk.ModelView.ListStore,\n module Graphics.UI.Gtk.ModelView.TreeDrag,\n module Graphics.UI.Gtk.ModelView.TreeModel,\n module Graphics.UI.Gtk.ModelView.TreeModelSort,\n module Graphics.UI.Gtk.ModelView.TreeSortable,\n module Graphics.UI.Gtk.ModelView.TreeModelFilter,\n module Graphics.UI.Gtk.ModelView.TreeRowReference,\n module Graphics.UI.Gtk.ModelView.TreeSelection,\n module Graphics.UI.Gtk.ModelView.TreeStore,\n module Graphics.UI.Gtk.ModelView.TreeView,\n module Graphics.UI.Gtk.ModelView.TreeViewColumn,\n -- * Menus, combo box, toolbar\n module Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Combo,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBox,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry,\n module Graphics.UI.Gtk.MenuComboToolbar.Menu,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuBar,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuShell,\n module Graphics.UI.Gtk.MenuComboToolbar.OptionMenu,\n module Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Toolbar,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolItem,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem,\n-- * Action-based menus and toolbars\n module Graphics.UI.Gtk.ActionMenuToolbar.Action,\n module Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup,\n module Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.RadioAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.UIManager,\n -- * Selectors (file\\\/font\\\/color)\n module Graphics.UI.Gtk.Selectors.ColorSelection,\n module Graphics.UI.Gtk.Selectors.ColorSelectionDialog,\n module Graphics.UI.Gtk.Selectors.ColorButton,\n module Graphics.UI.Gtk.Selectors.FileSelection,\n module Graphics.UI.Gtk.Selectors.FontSelection,\n module Graphics.UI.Gtk.Selectors.FontSelectionDialog,\n module Graphics.UI.Gtk.Selectors.FontButton,\n-- module InputDialog,\n -- ** File chooser\n module Graphics.UI.Gtk.Selectors.FileChooser,\n module Graphics.UI.Gtk.Selectors.FileChooserDialog,\n module Graphics.UI.Gtk.Selectors.FileChooserWidget,\n module Graphics.UI.Gtk.Selectors.FileChooserButton,\n module Graphics.UI.Gtk.Selectors.FileFilter,\n -- * Layout containers\n module Graphics.UI.Gtk.Layout.Alignment,\n module Graphics.UI.Gtk.Layout.AspectFrame,\n module Graphics.UI.Gtk.Layout.HBox,\n module Graphics.UI.Gtk.Layout.HButtonBox,\n module Graphics.UI.Gtk.Layout.Fixed,\n module Graphics.UI.Gtk.Layout.HPaned,\n module Graphics.UI.Gtk.Layout.Layout,\n module Graphics.UI.Gtk.Layout.Notebook,\n module Graphics.UI.Gtk.Layout.Expander,\n module Graphics.UI.Gtk.Layout.Table,\n module Graphics.UI.Gtk.Layout.VBox,\n module Graphics.UI.Gtk.Layout.VButtonBox,\n module Graphics.UI.Gtk.Layout.VPaned,\n -- * Ornaments\n module Graphics.UI.Gtk.Ornaments.Frame,\n module Graphics.UI.Gtk.Ornaments.HSeparator,\n module Graphics.UI.Gtk.Ornaments.VSeparator,\n -- * Scrolling\n module Graphics.UI.Gtk.Scrolling.HScrollbar,\n module Graphics.UI.Gtk.Scrolling.ScrolledWindow,\n module Graphics.UI.Gtk.Scrolling.VScrollbar,\n -- * Miscellaneous\n module Graphics.UI.Gtk.Misc.Adjustment,\n module Graphics.UI.Gtk.Misc.Arrow,\n module Graphics.UI.Gtk.Misc.Calendar,\n module Graphics.UI.Gtk.Misc.DrawingArea,\n module Graphics.UI.Gtk.Misc.EventBox,\n module Graphics.UI.Gtk.Misc.HandleBox,\n module Graphics.UI.Gtk.Misc.IMMulticontext,\n module Graphics.UI.Gtk.Misc.SizeGroup,\n module Graphics.UI.Gtk.Misc.Tooltips,\n module Graphics.UI.Gtk.Misc.Viewport,\n -- * Abstract base classes\n module Graphics.UI.Gtk.Abstract.Box,\n module Graphics.UI.Gtk.Abstract.ButtonBox,\n module Graphics.UI.Gtk.Abstract.Container,\n module Graphics.UI.Gtk.Abstract.Bin,\n module Graphics.UI.Gtk.Abstract.Misc,\n module Graphics.UI.Gtk.Abstract.IMContext,\n module Graphics.UI.Gtk.Abstract.Object,\n module Graphics.UI.Gtk.Abstract.Paned,\n module Graphics.UI.Gtk.Abstract.Range,\n module Graphics.UI.Gtk.Abstract.Scale,\n module Graphics.UI.Gtk.Abstract.Scrollbar,\n module Graphics.UI.Gtk.Abstract.Separator,\n module Graphics.UI.Gtk.Abstract.Widget,\n -- * Cross-process embedding\n module Graphics.UI.Gtk.Embedding.Plug,\n module Graphics.UI.Gtk.Embedding.Socket,\n -- * Non-widgets\n module System.Glib.Signals,\n module System.Glib.Attributes,\n module System.Glib.GObject,\n module Graphics.UI.Gtk.Builder,\n\n -- * Pango text layout modules\n module Graphics.Rendering.Pango.Context,\n module Graphics.Rendering.Pango.Markup,\n module Graphics.Rendering.Pango.Layout,\n module Graphics.Rendering.Pango.Rendering,\n module Graphics.Rendering.Pango.Font,\n module Graphics.Rendering.Pango.Enums\n ) where\n\n-- general things, initialization\nimport Graphics.UI.Gtk.General.General\nimport Graphics.UI.Gtk.General.IconFactory\nimport Graphics.UI.Gtk.General.StockItems\nimport Graphics.UI.Gtk.General.Selection\nimport Graphics.UI.Gtk.General.Drag\nimport Graphics.UI.Gtk.General.Clipboard\n-- drawing\nimport Graphics.UI.Gtk.Gdk.Keys\nimport Graphics.UI.Gtk.General.Style\nimport Graphics.UI.Gtk.General.RcStyle\nimport Graphics.UI.Gtk.Gdk.Cursor\nimport Graphics.UI.Gtk.Gdk.Drawable\nimport Graphics.UI.Gtk.Gdk.DrawWindow\nimport Graphics.UI.Gtk.Gdk.Region\t\thiding (makeNewRegion)\n--import Graphics.UI.Gtk.Gdk.GC\nimport Graphics.UI.Gtk.Gdk.EventM\nimport Graphics.UI.Gtk.Gdk.Pixbuf\nimport Graphics.UI.Gtk.Gdk.Pixmap\nimport Graphics.UI.Gtk.Gdk.Screen\nimport Graphics.UI.Gtk.Gdk.Display\nimport Graphics.UI.Gtk.Gdk.Gdk\n-- cairo integration\nimport Graphics.UI.Gtk.Cairo\n-- windows\nimport Graphics.UI.Gtk.Windows.Dialog\nimport Graphics.UI.Gtk.Windows.Window\nimport Graphics.UI.Gtk.Windows.Invisible\nimport Graphics.UI.Gtk.Windows.AboutDialog\nimport Graphics.UI.Gtk.Windows.MessageDialog\nimport Graphics.UI.Gtk.Windows.WindowGroup\n-- display widgets\nimport Graphics.UI.Gtk.Display.AccelLabel\nimport Graphics.UI.Gtk.Display.Image\nimport Graphics.UI.Gtk.Display.Label\nimport Graphics.UI.Gtk.Display.ProgressBar\nimport Graphics.UI.Gtk.Display.Statusbar\n#if GTK_CHECK_VERSION(2,10,0) && !DISABLE_DEPRECATED\nimport Graphics.UI.Gtk.Display.StatusIcon hiding (onActivate,afterActivate,onPopupMenu,afterPopupMenu)\n#else\nimport Graphics.UI.Gtk.Display.StatusIcon\n#endif\n-- buttons and toggles\nimport Graphics.UI.Gtk.Buttons.Button\nimport Graphics.UI.Gtk.Buttons.CheckButton\nimport Graphics.UI.Gtk.Buttons.RadioButton\nimport Graphics.UI.Gtk.Buttons.ToggleButton\n-- numeric\\\/text data entry\nimport Graphics.UI.Gtk.Entry.Editable\nimport Graphics.UI.Gtk.Entry.Entry\nimport Graphics.UI.Gtk.Entry.EntryCompletion\nimport Graphics.UI.Gtk.Entry.HScale\nimport Graphics.UI.Gtk.Entry.VScale\nimport Graphics.UI.Gtk.Entry.SpinButton\n-- multiline text editor\nimport Graphics.UI.Gtk.Multiline.TextIter\nimport Graphics.UI.Gtk.Multiline.TextMark\nimport Graphics.UI.Gtk.Multiline.TextBuffer\nimport Graphics.UI.Gtk.Multiline.TextTag\nimport Graphics.UI.Gtk.Multiline.TextTagTable\nimport qualified Graphics.UI.Gtk.Multiline.TextView\nimport Graphics.UI.Gtk.Multiline.TextView\n#ifndef DISABLE_DEPRECATED\n hiding (afterSetScrollAdjustments,\n\t\tonSetScrollAdjustments, afterCopyClipboard, onCopyClipboard,\n\t\tafterCutClipboard, onCutClipboard, afterInsertAtCursor,\n\t\tonInsertAtCursor, afterPasteClipboard, onPasteClipboard,\n\t\tafterToggleOverwrite, onToggleOverwrite, setScrollAdjustments)\n#endif\n-- tree and list widget\nimport Graphics.UI.Gtk.ModelView.CellLayout\nimport Graphics.UI.Gtk.ModelView.CellRenderer\nimport Graphics.UI.Gtk.ModelView.CellRendererCombo\nimport Graphics.UI.Gtk.ModelView.CellRendererPixbuf\nimport Graphics.UI.Gtk.ModelView.CellRendererProgress\nimport Graphics.UI.Gtk.ModelView.CellRendererText\nimport Graphics.UI.Gtk.ModelView.CellRendererToggle\nimport Graphics.UI.Gtk.ModelView.CellView\nimport Graphics.UI.Gtk.ModelView.CustomStore\nimport Graphics.UI.Gtk.ModelView.IconView\nimport Graphics.UI.Gtk.ModelView.ListStore\nimport Graphics.UI.Gtk.ModelView.TreeDrag\nimport Graphics.UI.Gtk.ModelView.TreeModel\nimport Graphics.UI.Gtk.ModelView.TreeModelSort\nimport Graphics.UI.Gtk.ModelView.TreeSortable\nimport Graphics.UI.Gtk.ModelView.TreeModelFilter\nimport Graphics.UI.Gtk.ModelView.TreeRowReference\nimport Graphics.UI.Gtk.ModelView.TreeSelection\nimport Graphics.UI.Gtk.ModelView.TreeStore\nimport Graphics.UI.Gtk.ModelView.TreeView\nimport Graphics.UI.Gtk.ModelView.TreeViewColumn\n-- menus, combo box, toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.Combo\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBox\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry\n-- import ItemFactory\nimport Graphics.UI.Gtk.MenuComboToolbar.Menu\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuBar\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuShell\nimport Graphics.UI.Gtk.MenuComboToolbar.OptionMenu\nimport Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.Toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolItem\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem\n-- action based menus and toolbars\nimport Graphics.UI.Gtk.ActionMenuToolbar.Action\nimport Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup\nimport Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.RadioAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.UIManager\n-- selectors (file\\\/font\\\/color\\\/input device)\nimport Graphics.UI.Gtk.Selectors.ColorSelection\nimport Graphics.UI.Gtk.Selectors.ColorSelectionDialog\nimport Graphics.UI.Gtk.Selectors.ColorButton\nimport Graphics.UI.Gtk.Selectors.FileSelection\nimport Graphics.UI.Gtk.Selectors.FileChooser\nimport Graphics.UI.Gtk.Selectors.FileChooserDialog\nimport Graphics.UI.Gtk.Selectors.FileChooserWidget\nimport Graphics.UI.Gtk.Selectors.FileChooserButton\nimport Graphics.UI.Gtk.Selectors.FileFilter\nimport Graphics.UI.Gtk.Selectors.FontSelection\nimport Graphics.UI.Gtk.Selectors.FontSelectionDialog\nimport Graphics.UI.Gtk.Selectors.FontButton\n--import InputDialog\n-- layout containers\nimport Graphics.UI.Gtk.Layout.Alignment\nimport Graphics.UI.Gtk.Layout.AspectFrame\nimport Graphics.UI.Gtk.Layout.HBox\nimport Graphics.UI.Gtk.Layout.VBox\nimport Graphics.UI.Gtk.Layout.HButtonBox\nimport Graphics.UI.Gtk.Layout.VButtonBox\nimport Graphics.UI.Gtk.Layout.Fixed\nimport Graphics.UI.Gtk.Layout.HPaned\nimport Graphics.UI.Gtk.Layout.VPaned\nimport Graphics.UI.Gtk.Layout.Layout\nimport Graphics.UI.Gtk.Layout.Notebook\nimport Graphics.UI.Gtk.Layout.Expander\nimport Graphics.UI.Gtk.Layout.Table\n-- ornaments\nimport Graphics.UI.Gtk.Ornaments.Frame\nimport Graphics.UI.Gtk.Ornaments.HSeparator\nimport Graphics.UI.Gtk.Ornaments.VSeparator\n-- scrolling\nimport Graphics.UI.Gtk.Scrolling.HScrollbar\nimport Graphics.UI.Gtk.Scrolling.VScrollbar\nimport Graphics.UI.Gtk.Scrolling.ScrolledWindow\n-- miscellaneous\nimport Graphics.UI.Gtk.Misc.Adjustment\nimport Graphics.UI.Gtk.Misc.Arrow\nimport Graphics.UI.Gtk.Misc.Calendar\nimport Graphics.UI.Gtk.Misc.DrawingArea\nimport Graphics.UI.Gtk.Misc.EventBox\nimport Graphics.UI.Gtk.Misc.HandleBox\nimport Graphics.UI.Gtk.Misc.IMMulticontext\nimport Graphics.UI.Gtk.Misc.SizeGroup\nimport Graphics.UI.Gtk.Misc.Tooltips\nimport Graphics.UI.Gtk.Misc.Viewport\n--import Accessible\n-- abstract base classes\nimport Graphics.UI.Gtk.Abstract.Box\nimport Graphics.UI.Gtk.Abstract.ButtonBox\nimport Graphics.UI.Gtk.Abstract.Container\nimport Graphics.UI.Gtk.Abstract.Bin\nimport Graphics.UI.Gtk.Abstract.Misc\nimport Graphics.UI.Gtk.Abstract.IMContext\nimport Graphics.UI.Gtk.Abstract.Object (\n Object,\n ObjectClass,\n castToObject,\n toObject,\n GWeakNotify,\n objectWeakref,\n objectWeakunref,\n objectDestroy )\nimport Graphics.UI.Gtk.Abstract.Paned\nimport Graphics.UI.Gtk.Abstract.Range\nimport Graphics.UI.Gtk.Abstract.Scale\nimport Graphics.UI.Gtk.Abstract.Scrollbar\nimport Graphics.UI.Gtk.Abstract.Separator\nimport Graphics.UI.Gtk.Abstract.Widget\n-- cross-process embedding\nimport Graphics.UI.Gtk.Embedding.Plug\nimport Graphics.UI.Gtk.Embedding.Socket\n\n-- non widgets\nimport System.Glib.Signals\n{- do eport 'on' and 'after'\n\t\t(ConnectId, disconnect,\n\t\t\t\t\t signalDisconnect,\n\t\t\t\t\t signalBlock,\n\t\t\t\t\t signalUnblock)\n-}\nimport System.Glib.Attributes\nimport System.Glib.GObject (\n GObject,\n GObjectClass,\n toGObject,\n castToGObject,\n quarkFromString,\n objectCreateAttribute,\n objectSetAttribute,\n objectGetAttributeUnsafe,\n isA\n )\nimport Graphics.UI.Gtk.Builder\n \n-- pango modules\nimport Graphics.Rendering.Pango.Context\nimport Graphics.Rendering.Pango.Markup\nimport Graphics.Rendering.Pango.Layout\nimport Graphics.Rendering.Pango.Rendering\nimport Graphics.Rendering.Pango.Font\nimport Graphics.Rendering.Pango.Enums\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fbb316c4344e83796ef6eb4cd82ab6def6968949","subject":"Make the TreeList\/Types module work with haddock","message":"Make the TreeList\/Types module work with haddock\n\ndarcs-hash:20060813180226-b4c10-b66b1df6c1e283f80609f2aa1a83095246014d4e.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"15246d1b77057fc1cfb9102b0814f57aa0817d04","subject":"gstreamer: M.S.G.Core.Types code cleanups","message":"gstreamer: M.S.G.Core.Types code cleanups\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"69c3ffbeeaf681105a79f0cb6f924df90165dd78","subject":"Convert to Either","message":"Convert to Either\n","repos":"norm2782\/hgit2","old_file":"git2.chs","new_file":"git2.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.Primitive\nimport Foreign\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = undefined -- git_repository_open\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.Primitive\nimport Foreign\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: Repository -> String -> IO ()\nopenRepo repo path = undefined -- git_repository_open\n\nopenRepoObjDir :: Repository -> String -> String -> String -> String -> IO (Maybe GitError)\nopenRepoObjDir repo dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: Repository -> String -> ObjDB -> String -> String -> IO (Maybe GitError)\nopenRepoObjDb repo dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> String -> Bool -> String -> IO (Maybe GitError)\ndiscover path startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Index -> Repository -> IO (Maybe GitError)\nindex idx repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d340d75402212cdef44c5fc13cba9bc6aa6d0195","subject":"Adjust webResourceGetFrameName.","message":"Adjust webResourceGetFrameName.","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1a09dfa84d85c48ad33b6ca1200242298be338cd","subject":"openRepoObjDb && discover","message":"openRepoObjDb && discover\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\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 undefined spStr (fromBool acrossFs) cdsStr\n if res == 0\n then undefined\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Index) $ peek idx\n else return . Left . toEnum . fromIntegral $ res\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\n-- TODO: Refactor some bits\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else 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","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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\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 if res == 0\n then fmap (Right . Index) $ peek idx\n else return . Left . toEnum . fromIntegral $ res\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\n-- TODO: Refactor some bits\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1bc25fd87a1b2e0482bba03244867a5e859dbef6","subject":"Removed need for -XDatatypeContexts at Histogram.hs.","message":"Removed need for -XDatatypeContexts at Histogram.hs.\n","repos":"BeautifulDestinations\/CV,TomMD\/CV,aleator\/CV,aleator\/CV","old_file":"CV\/Histogram.chs","new_file":"CV\/Histogram.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\n\nhistogram imageBins accumulate mask = unsafePerformIO $\n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds\n withPtrList (map imageFPTR images) $ \\ptrs ->\n case mask of\n Just m -> do\n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where\n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype (Num a) => HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\n\nhistogram imageBins accumulate mask = unsafePerformIO $\n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds\n withPtrList (map imageFPTR images) $ \\ptrs ->\n case mask of\n Just m -> do\n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where\n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"306a107e384f73733cf32d913e6288b7d9824c22","subject":"Make return types the base versions of widget and window.","message":"Make return types the base versions of widget and window.\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 WidgetBase))\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 WindowBase))\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 WindowBase))\nnextWindow currWindow = withRef currWindow (\\ptr -> nextWindow' ptr >>= toMaybeRef)\n\n{# fun Fl_modal as modal' { } -> `Ptr ()' #}\nmodal :: IO (Maybe (Ref WidgetBase))\nmodal = modal' >>= toMaybeRef\n\n{# fun Fl_grab as grab' { } -> `Ptr ()' #}\ngrab :: IO (Maybe (Ref WidgetBase))\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 WidgetBase))\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 WidgetBase))\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 WidgetBase))\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 WindowBase] -> Maybe (Ref WindowBase) -> IO [Ref WindowBase]\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_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","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"6847be13fab785c99152522f11ef3f206b27ac82","subject":"Check for null writer","message":"Check for null writer","repos":"aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV,aleator\/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\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","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\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 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":"5558aef3381b2e95b38c8e3d0d66f0842f4ed668","subject":"Fix typo","message":"Fix typo\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 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","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\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","returncode":0,"stderr":"","license":"isc","lang":"C2hs Haskell"} {"commit":"893e148303a7df65c7f7263c9bbe68b5855b34cf","subject":"Beautified type of errorString. Added MPI error code to MPIError (otherwise there is no sense in exporting errorClass and errorString).","message":"Beautified type of errorString. Added MPI error code to MPIError (otherwise there is no sense in exporting errorClass and errorString).\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 #}\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 , mpiErrorCode :: CInt\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 code\n\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 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"552f2ca76f3f08e5363913359ee3e4cbf40de3b9","subject":"Add signal sourceCompletionPopulateContext","message":"Add signal sourceCompletionPopulateContext\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"c2506c28fd33a7d41e99c9b8316fe3457a9af6db","subject":"Adjust webResourceGetEncoding.","message":"Adjust webResourceGetEncoding.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0eb19116a443d6fa8328a3072be13bb29c79bf0b","subject":"Added HasMedianFiltering for grayscale d32","message":"Added HasMedianFiltering for grayscale d32\n","repos":"aleator\/CV,aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV","old_file":"CV\/Filters.chs","new_file":"CV\/Filters.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, TypeFamilies, FlexibleInstances#-}\n#include \"cvWrapLEO.h\"\n{-#OPTIONS_GHC -fwarn-unused-imports#-}\n\n-- | This module is a collection of various image filters\nmodule CV.Filters(\n gaussian,gaussianOp\n ,blurOp,blur,blurNS\n ,bilateral\n ,HasMedianFiltering,median\n ,susan,getCentralMoment,getAbsCentralMoment\n ,getMoment,secondMomentBinarize,secondMomentBinarizeOp\n ,secondMomentAdaptiveBinarize,secondMomentAdaptiveBinarizeOp\n ,selectiveAvg,convolve2D,convolve2DI,haar,haarAt\n ,IntegralImage(),integralImage,verticalAverage) where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.Marshal.Utils\nimport CV.Bindings.ImgProc\n\nimport Utils.GeometryClass\nimport CV.Matrix (Matrix,withMatPtr)\nimport CV.ImageOp\n\nimport System.IO.Unsafe\n\n--import C2HSTools\n{#import CV.Image#}\n\n-- Low level wrapper for Susan filtering:\n-- IplImage* susanSmooth(IplImage *src, int w, int h\n-- ,double t, double sigma); \n\n-- | SUSAN adaptive smoothing filter, see \nsusan :: (Int, Int) -> Double -> Double\n -> Image GrayScale D32 -> Image GrayScale D32\nsusan (w,h) t sigma image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call susanSmooth#} img (fromIntegral w) (fromIntegral h) \n (realToFrac t) (realToFrac sigma))\n-- TODO: ADD checks above!\n\n-- | A selective average filter is an edge preserving noise reduction filter.\n-- It is a standard gaussian filter which ignores pixel values\n-- that are more than a given threshold away from the filtered pixel value.\nselectiveAvg :: (Int, Int) -> Double \n -> Image GrayScale D32 -> Image GrayScale D32\nselectiveAvg (w,h) t image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call selectiveAvgFilter#} \n img (realToFrac t) (fromIntegral w) (fromIntegral h))\n-- TODO: ADD checks above!\n\ngetCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthCentralMoment#} img n w h)\n\ngetAbsCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthAbsCentralMoment#} img n w h)\n\ngetMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthMoment#} img n w h)\n-- TODO: ADD checks above!\n\nsecondMomentBinarizeOp t = ImgOp $ \\image -> \n withGenImage image (flip {#call smb#} $ t)\nsecondMomentBinarize t i = unsafeOperate (secondMomentBinarizeOp t) i\n\nsecondMomentAdaptiveBinarizeOp w h t = ImgOp $ \\image -> \n withGenImage image \n (\\i-> {#call smab#} i w h t)\nsecondMomentAdaptiveBinarize w h t i = unsafeOperate (secondMomentAdaptiveBinarizeOp w h t) i\n\n#c\nenum SmoothType {\n BlurNoScale = CV_BLUR_NO_SCALE,\n Blur = CV_BLUR,\n Gaussian = CV_GAUSSIAN,\n Median = CV_MEDIAN ,\n Bilateral = CV_BILATERAL \n};\n#endc\n{#enum SmoothType {}#}\n\n{#fun cvSmooth as smooth' \n {withGenImage* `Image GrayScale D32'\n ,withGenImage* `Image GrayScale D32'\n ,`Int',`Int',`Int',`Float',`Float'}\n -> `()'#}\n\n\n-- | Image operation which applies gaussian or unifarm smoothing with a given window size to the image.\ngaussianOp,blurOp,blurNSOp :: (Int, Int) -> ImageOperation GrayScale D32\ngaussianOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum Gaussian) w h 0 0\nblurOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum Blur) w h 0 0\nblurNSOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum BlurNoScale) w h 0 0\n\n-- | Create a new image by applying gaussian, or uniform smoothing.\ngaussian,blur,blurNS :: (Int, Int) -> Image GrayScale D32 -> Image GrayScale D32\ngaussian = unsafeOperate . gaussianOp\nblur = unsafeOperate . blurOp\nblurNS = unsafeOperate . blurNSOp\n\nwithMask (w,h) op \n | maskIsOk (w,h) = ImgOp $ op (w,h)\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\n\n\n-- | Apply bilateral filtering \nbilateral :: (Int,Int) -> (Int,Int) -> Image a D8 -> Image a D8\nbilateral (w,h) (s1,s2) img = unsafePerformIO $ \n withClone img $ \\clone ->\n withGenImage img $ \\cimg ->\n withGenImage clone $ \\ccln -> do\n {#call cvSmooth#} cimg ccln (fromIntegral $ fromEnum Bilateral)\n (fromIntegral w) (fromIntegral h) \n (realToFrac s1) (realToFrac s2) \n\n\nclass HasMedianFiltering a where\n median :: (Int,Int) -> a -> a\n\ninstance HasMedianFiltering (Image GrayScale D8) where\n median = median'\n\ninstance HasMedianFiltering (Image GrayScale D32) where\n median a = unsafeImageTo32F . median' a . unsafeImageTo8Bit\n\ninstance HasMedianFiltering (Image RGB D8) where\n median = median'\n\n-- |\u00a0Perform median filtering on an eight bit image.\nmedian' :: (Int,Int) -> Image c D8 -> Image c D8\nmedian' (w,h) img \n | maskIsOk (w,h) = unsafePerformIO $ do\n clone2 <- cloneImage img\n withGenImage img $ \\c1 -> \n withGenImage clone2 $ \\c2 -> \n {#call cvSmooth#} c1 c2 (fromIntegral $ fromEnum Median) \n (fromIntegral w) (fromIntegral h) 0 0\n return clone2\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\nmaskIsOk (w,h) = odd w && odd h && w >0 && h>0\n\n\n-- General 2D comvolutions\n-- Convolve image with specified kernel stored in flat list.\n-- Kernel must have dimensions (w,h) and specified anchor point\n-- (x,y) within (0,0) and (w,h)\nconvolve2D :: (Point2D anchor, ELP anchor ~ Int) => \n Matrix D32 -> anchor -> Image GrayScale D32 -> Image GrayScale D32\nconvolve2D kernel anchor image = unsafePerformIO $ \n let result = emptyCopy image\n in withGenImage image $ \\c_img->\n withGenImage result $ \\c_res->\n withMatPtr kernel $ \\c_mat ->\n with (convertPt anchor) $ \\c_pt ->\n c'wrapFilter2 c_img c_res c_mat c_pt\n >> return result\n \nconvolve2DI (x,y) kernel image = unsafePerformIO $ \n withImage image $ \\img->\n withImage kernel $ \\k ->\n creatingImage $\n {#call wrapFilter2DImg#} \n img k x y\n\n-- | Replace pixel values by the average of the row. \nverticalAverage :: Image GrayScale D32 -> Image GrayScale D32\nverticalAverage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w,h) \n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call vertical_average#} i sum \n return s\n\n-- |\u00a0A type for storing integral images. Integral image stores for every pixel the sum of pixels\n-- above and left of it. Such images are used for significantly accelerating the calculation of\n-- area averages. \nnewtype IntegralImage = IntegralImage (Image GrayScale D64)\ninstance Sized IntegralImage where\n type Size IntegralImage = (Int,Int)\n getSize (IntegralImage i) = getSize i\n\ninstance GetPixel IntegralImage where\n type P IntegralImage = Double\n getPixel = getPixel\n\n-- |\u00a0Calculate the integral image from the given image.\nintegralImage :: Image GrayScale D32 -> IntegralImage\nintegralImage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w+1,h+1)\n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call cvIntegral#} i sum nullPtr nullPtr\n return $ IntegralImage s\n\n\n-- |Filter the image with box shaped averaging mask.\nhaar :: IntegralImage -> (Int,Int,Int,Int) -> Image GrayScale D32\nhaar (IntegralImage image) (a',b',c',d') = unsafePerformIO $ do\n let (w,h) = getSize image\n let [a,b,c,d] = map fromIntegral [a',b',c',d']\n r <- create (w,h)\n withImage image $ \\sum ->\n withImage r $ \\res -> do\n {#call haarFilter#} sum \n (min a c) \n (max b d)\n (max a c)\n (min b d) \n res\n return r\n\n-- | Get an average of a given region.\nhaarAt :: IntegralImage -> (Int,Int,Int,Int) -> Double\n\nhaarAt (IntegralImage ii) (a,b,w,h) = realToFrac $ unsafePerformIO $ withImage ii $ \\i -> \n {#call haar_at#} i (f a) (f b) (f w) (f h)\n where f = fromIntegral \n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, TypeFamilies, FlexibleInstances#-}\n#include \"cvWrapLEO.h\"\n{-#OPTIONS_GHC -fwarn-unused-imports#-}\n\n-- | This module is a collection of various image filters\nmodule CV.Filters(\n gaussian,gaussianOp\n ,blurOp,blur,blurNS\n ,bilateral\n ,HasMedianFiltering,median\n ,susan,getCentralMoment,getAbsCentralMoment\n ,getMoment,secondMomentBinarize,secondMomentBinarizeOp\n ,secondMomentAdaptiveBinarize,secondMomentAdaptiveBinarizeOp\n ,selectiveAvg,convolve2D,convolve2DI,haar,haarAt\n ,IntegralImage(),integralImage,verticalAverage) where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.Marshal.Utils\nimport CV.Bindings.ImgProc\n\nimport Utils.GeometryClass\nimport CV.Matrix (Matrix,withMatPtr)\nimport CV.ImageOp\n\nimport System.IO.Unsafe\n\n--import C2HSTools\n{#import CV.Image#}\n\n-- Low level wrapper for Susan filtering:\n-- IplImage* susanSmooth(IplImage *src, int w, int h\n-- ,double t, double sigma); \n\n-- | SUSAN adaptive smoothing filter, see \nsusan :: (Int, Int) -> Double -> Double\n -> Image GrayScale D32 -> Image GrayScale D32\nsusan (w,h) t sigma image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call susanSmooth#} img (fromIntegral w) (fromIntegral h) \n (realToFrac t) (realToFrac sigma))\n-- TODO: ADD checks above!\n\n-- | A selective average filter is an edge preserving noise reduction filter.\n-- It is a standard gaussian filter which ignores pixel values\n-- that are more than a given threshold away from the filtered pixel value.\nselectiveAvg :: (Int, Int) -> Double \n -> Image GrayScale D32 -> Image GrayScale D32\nselectiveAvg (w,h) t image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call selectiveAvgFilter#} \n img (realToFrac t) (fromIntegral w) (fromIntegral h))\n-- TODO: ADD checks above!\n\ngetCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthCentralMoment#} img n w h)\n\ngetAbsCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthAbsCentralMoment#} img n w h)\n\ngetMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthMoment#} img n w h)\n-- TODO: ADD checks above!\n\nsecondMomentBinarizeOp t = ImgOp $ \\image -> \n withGenImage image (flip {#call smb#} $ t)\nsecondMomentBinarize t i = unsafeOperate (secondMomentBinarizeOp t) i\n\nsecondMomentAdaptiveBinarizeOp w h t = ImgOp $ \\image -> \n withGenImage image \n (\\i-> {#call smab#} i w h t)\nsecondMomentAdaptiveBinarize w h t i = unsafeOperate (secondMomentAdaptiveBinarizeOp w h t) i\n\n#c\nenum SmoothType {\n BlurNoScale = CV_BLUR_NO_SCALE,\n Blur = CV_BLUR,\n Gaussian = CV_GAUSSIAN,\n Median = CV_MEDIAN ,\n Bilateral = CV_BILATERAL \n};\n#endc\n{#enum SmoothType {}#}\n\n{#fun cvSmooth as smooth' \n {withGenImage* `Image GrayScale D32'\n ,withGenImage* `Image GrayScale D32'\n ,`Int',`Int',`Int',`Float',`Float'}\n -> `()'#}\n\n\n-- | Image operation which applies gaussian or unifarm smoothing with a given window size to the image.\ngaussianOp,blurOp,blurNSOp :: (Int, Int) -> ImageOperation GrayScale D32\ngaussianOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum Gaussian) w h 0 0\nblurOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum Blur) w h 0 0\nblurNSOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum BlurNoScale) w h 0 0\n\n-- | Create a new image by applying gaussian, or uniform smoothing.\ngaussian,blur,blurNS :: (Int, Int) -> Image GrayScale D32 -> Image GrayScale D32\ngaussian = unsafeOperate . gaussianOp\nblur = unsafeOperate . blurOp\nblurNS = unsafeOperate . blurNSOp\n\nwithMask (w,h) op \n | maskIsOk (w,h) = ImgOp $ op (w,h)\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\n\n\n-- | Apply bilateral filtering \nbilateral :: (Int,Int) -> (Int,Int) -> Image a D8 -> Image a D8\nbilateral (w,h) (s1,s2) img = unsafePerformIO $ \n withClone img $ \\clone ->\n withGenImage img $ \\cimg ->\n withGenImage clone $ \\ccln -> do\n {#call cvSmooth#} cimg ccln (fromIntegral $ fromEnum Bilateral)\n (fromIntegral w) (fromIntegral h) \n (realToFrac s1) (realToFrac s2) \n\n\nclass HasMedianFiltering a where\n median :: (Int,Int) -> a -> a\n\ninstance HasMedianFiltering (Image GrayScale D8) where\n median = median'\n\ninstance HasMedianFiltering (Image RGB D8) where\n median = median'\n\n-- |\u00a0Perform median filtering on an eight bit image.\nmedian' :: (Int,Int) -> Image c D8 -> Image c D8\nmedian' (w,h) img \n | maskIsOk (w,h) = unsafePerformIO $ do\n clone2 <- cloneImage img\n withGenImage img $ \\c1 -> \n withGenImage clone2 $ \\c2 -> \n {#call cvSmooth#} c1 c2 (fromIntegral $ fromEnum Median) \n (fromIntegral w) (fromIntegral h) 0 0\n return clone2\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\nmaskIsOk (w,h) = odd w && odd h && w >0 && h>0\n\n\n-- General 2D comvolutions\n-- Convolve image with specified kernel stored in flat list.\n-- Kernel must have dimensions (w,h) and specified anchor point\n-- (x,y) within (0,0) and (w,h)\nconvolve2D :: (Point2D anchor, ELP anchor ~ Int) => \n Matrix D32 -> anchor -> Image GrayScale D32 -> Image GrayScale D32\nconvolve2D kernel anchor image = unsafePerformIO $ \n let result = emptyCopy image\n in withGenImage image $ \\c_img->\n withGenImage result $ \\c_res->\n withMatPtr kernel $ \\c_mat ->\n with (convertPt anchor) $ \\c_pt ->\n c'wrapFilter2 c_img c_res c_mat c_pt\n >> return result\n \nconvolve2DI (x,y) kernel image = unsafePerformIO $ \n withImage image $ \\img->\n withImage kernel $ \\k ->\n creatingImage $\n {#call wrapFilter2DImg#} \n img k x y\n\n-- | Replace pixel values by the average of the row. \nverticalAverage :: Image GrayScale D32 -> Image GrayScale D32\nverticalAverage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w,h) \n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call vertical_average#} i sum \n return s\n\n-- |\u00a0A type for storing integral images. Integral image stores for every pixel the sum of pixels\n-- above and left of it. Such images are used for significantly accelerating the calculation of\n-- area averages. \nnewtype IntegralImage = IntegralImage (Image GrayScale D64)\ninstance Sized IntegralImage where\n type Size IntegralImage = (Int,Int)\n getSize (IntegralImage i) = getSize i\n\ninstance GetPixel IntegralImage where\n type P IntegralImage = Double\n getPixel = getPixel\n\n-- |\u00a0Calculate the integral image from the given image.\nintegralImage :: Image GrayScale D32 -> IntegralImage\nintegralImage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w+1,h+1)\n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call cvIntegral#} i sum nullPtr nullPtr\n return $ IntegralImage s\n\n\n-- |Filter the image with box shaped averaging mask.\nhaar :: IntegralImage -> (Int,Int,Int,Int) -> Image GrayScale D32\nhaar (IntegralImage image) (a',b',c',d') = unsafePerformIO $ do\n let (w,h) = getSize image\n let [a,b,c,d] = map fromIntegral [a',b',c',d']\n r <- create (w,h)\n withImage image $ \\sum ->\n withImage r $ \\res -> do\n {#call haarFilter#} sum \n (min a c) \n (max b d)\n (max a c)\n (min b d) \n res\n return r\n\n-- | Get an average of a given region.\nhaarAt :: IntegralImage -> (Int,Int,Int,Int) -> Double\n\nhaarAt (IntegralImage ii) (a,b,w,h) = realToFrac $ unsafePerformIO $ withImage ii $ \\i -> \n {#call haar_at#} i (f a) (f b) (f w) (f h)\n where f = fromIntegral \n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"21eada3f387b3f9d1b9b78ad52eeea740194aa62","subject":"removed debug hPrint","message":"removed debug hPrint\n","repos":"albertov\/pg_schedule","old_file":"PGSchedule.chs","new_file":"PGSchedule.chs","new_contents":"module PGSchedule () where\n\nimport Data.Time\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Foreign.Marshal.Alloc (free)\nimport Foreign.Marshal.Array (newArray)\nimport Data.ByteString.Unsafe (unsafePackCString)\nimport qualified Data.Text.Encoding as T\nimport Sigym4.Dimension.CronSchedule\nimport Sigym4.Dimension\n\n#include \"postgres.h\"\n#include \"pgtime.h\"\n#include \"schedule.h\"\n\n{#enum PGScheduleError {} deriving (Eq,Show) #}\n\n\nnewtype PGTime = PGTime UTCTime deriving Show\n\n{#pointer * pg_tm as PGTime nocode#}\n\ninstance Storable PGTime where\n sizeOf _ = {#sizeof pg_tm #}\n alignment _ = {#alignof pg_tm #}\n peek = fmap PGTime . peekUTCTime\n where\n peekUTCTime p =\n UTCTime <$> peekDay p <*> (timeOfDayToTime <$> peekTimeOfDay p)\n peekDay p = do\n y <- (+1900) . fromIntegral <$> {#get pg_tm->tm_year#} p\n m <- (+1) . fromIntegral <$> {#get pg_tm->tm_mon#} p\n d <- fromIntegral <$> {#get pg_tm->tm_mday#} p\n return (fromGregorian y m d)\n peekTimeOfDay p = do\n h <- fromIntegral <$> {#get pg_tm->tm_hour#} p\n m <- fromIntegral <$> {#get pg_tm->tm_min#} p\n s <- fromIntegral <$> {#get pg_tm->tm_sec#} p\n return (TimeOfDay h m s)\n\n poke p (PGTime (UTCTime day time)) = do\n let (TimeOfDay h m s) = timeToTimeOfDay time\n {#set pg_tm->tm_sec#} p (round s)\n {#set pg_tm->tm_min#} p (fromIntegral m)\n {#set pg_tm->tm_hour#} p (fromIntegral h)\n let (y,mth,d) = toGregorian day\n {#set pg_tm->tm_mday#} p (fromIntegral d)\n {#set pg_tm->tm_mon#} p (fromIntegral mth - 1)\n {#set pg_tm->tm_year#} p (fromIntegral y - 1900)\n {#set pg_tm->tm_wday#} p 0\n {#set pg_tm->tm_yday#} p 0\n {#set pg_tm->tm_isdst#} p 0\n {#set pg_tm->tm_gmtoff#} p 0\n {#set pg_tm->tm_zone#} p nullPtr --We won't be able to free anything we allocate here so we dont\n\nreturnStatus :: PGScheduleError -> IO CInt\nreturnStatus = return . fromIntegral . fromEnum\n\npg_schedule_parse :: CString -> IO CInt\npg_schedule_parse s = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n returnStatus $ either (const INVALID_SCHEDULE_FORMAT) (const NO_ERROR) (mkCronSchedule t)\nforeign export ccall pg_schedule_parse :: CString -> IO CInt\n\nwithSchedule :: CString -> (CronSchedule -> IO PGScheduleError) -> IO CInt\nwithSchedule s f = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n case mkCronSchedule t of\n Right sched -> fromIntegral . fromEnum <$> f sched\n Left _ -> do\n -- Should not happen since type is 'schedule' so it has already been parsed\n -- properly by pg_schedule_parse\n returnStatus INVALID_SCHEDULE_FORMAT\n\npg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\npg_schedule_contains s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n poke resPtr (if idelem sched dt then 1 else 0)\n pure NO_ERROR\nforeign export ccall pg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\n\n\npg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_next s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idsucc sched =<< idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_previous s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idpred sched =<< idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_floor s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_ceiling s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\npg_schedule_series s fromPtr toPtr resPtr countPtr = withSchedule s $ \\sched -> do\n PGTime dtFrom <- peek fromPtr\n PGTime dtTo <- peek toPtr\n let series = map PGTime\n . takeWhile (<= dtTo)\n . map unQ\n $ idenumUp sched dtFrom\n poke resPtr =<< newArray series\n poke countPtr (fromIntegral (length series))\n return NO_ERROR\nforeign export ccall pg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\n\npg_schedule_free_series :: Ptr PGTime -> IO ()\npg_schedule_free_series = free\nforeign export ccall pg_schedule_free_series :: Ptr PGTime -> IO ()\n","old_contents":"module PGSchedule () where\n\nimport Data.Time\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Foreign.Marshal.Alloc (free)\nimport Foreign.Marshal.Array (newArray)\nimport Data.ByteString.Unsafe (unsafePackCString)\nimport qualified Data.Text.Encoding as T\nimport System.IO\nimport Sigym4.Dimension.CronSchedule\nimport Sigym4.Dimension\n\n#include \"postgres.h\"\n#include \"pgtime.h\"\n#include \"schedule.h\"\n\n{#enum PGScheduleError {} deriving (Eq,Show) #}\n\n\nnewtype PGTime = PGTime UTCTime deriving Show\n\n{#pointer * pg_tm as PGTime nocode#}\n\ninstance Storable PGTime where\n sizeOf _ = {#sizeof pg_tm #}\n alignment _ = {#alignof pg_tm #}\n peek = fmap PGTime . peekUTCTime\n where\n peekUTCTime p =\n UTCTime <$> peekDay p <*> (timeOfDayToTime <$> peekTimeOfDay p)\n peekDay p = do\n y <- (+1900) . fromIntegral <$> {#get pg_tm->tm_year#} p\n m <- (+1) . fromIntegral <$> {#get pg_tm->tm_mon#} p\n d <- fromIntegral <$> {#get pg_tm->tm_mday#} p\n return (fromGregorian y m d)\n peekTimeOfDay p = do\n h <- fromIntegral <$> {#get pg_tm->tm_hour#} p\n m <- fromIntegral <$> {#get pg_tm->tm_min#} p\n s <- fromIntegral <$> {#get pg_tm->tm_sec#} p\n return (TimeOfDay h m s)\n\n poke p (PGTime (UTCTime day time)) = do\n let (TimeOfDay h m s) = timeToTimeOfDay time\n {#set pg_tm->tm_sec#} p (round s)\n {#set pg_tm->tm_min#} p (fromIntegral m)\n {#set pg_tm->tm_hour#} p (fromIntegral h)\n let (y,mth,d) = toGregorian day\n {#set pg_tm->tm_mday#} p (fromIntegral d)\n {#set pg_tm->tm_mon#} p (fromIntegral mth - 1)\n {#set pg_tm->tm_year#} p (fromIntegral y - 1900)\n {#set pg_tm->tm_wday#} p 0\n {#set pg_tm->tm_yday#} p 0\n {#set pg_tm->tm_isdst#} p 0\n {#set pg_tm->tm_gmtoff#} p 0\n {#set pg_tm->tm_zone#} p nullPtr --We won't be able to free anything we allocate here so we dont\n\nreturnStatus :: PGScheduleError -> IO CInt\nreturnStatus = return . fromIntegral . fromEnum\n\npg_schedule_parse :: CString -> IO CInt\npg_schedule_parse s = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n returnStatus $ either (const INVALID_SCHEDULE_FORMAT) (const NO_ERROR) (mkCronSchedule t)\nforeign export ccall pg_schedule_parse :: CString -> IO CInt\n\nwithSchedule :: CString -> (CronSchedule -> IO PGScheduleError) -> IO CInt\nwithSchedule s f = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n case mkCronSchedule t of\n Right sched -> fromIntegral . fromEnum <$> f sched\n Left _ -> do\n -- Should not happen since type is 'schedule' so it has already been parsed\n -- properly by pg_schedule_parse\n returnStatus INVALID_SCHEDULE_FORMAT\n\npg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\npg_schedule_contains s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n poke resPtr (if idelem sched dt then 1 else 0)\n pure NO_ERROR\nforeign export ccall pg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\n\n\npg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_next s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idsucc sched =<< idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_previous s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idpred sched =<< idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_floor s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_ceiling s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\npg_schedule_series s fromPtr toPtr resPtr countPtr = withSchedule s $ \\sched -> do\n PGTime dtFrom <- peek fromPtr\n PGTime dtTo <- peek toPtr\n let series = map PGTime\n . takeWhile (<= dtTo)\n . map unQ\n $ idenumUp sched dtFrom\n hPrint stderr (dtFrom, dtTo, series)\n poke resPtr =<< newArray series\n poke countPtr (fromIntegral (length series))\n return NO_ERROR\nforeign export ccall pg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\n\npg_schedule_free_series :: Ptr PGTime -> IO ()\npg_schedule_free_series = free\nforeign export ccall pg_schedule_free_series :: Ptr PGTime -> IO ()\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"83df69650e8125210f5ab7a23548cbc8a88d17b9","subject":"[project @ 2005-02-13 16:59:11 by as49] Remove this file which was renamed to Image.chs.pp.","message":"[project @ 2005-02-13 16:59:11 by as49]\nRemove this file which was renamed to Image.chs.pp.\n","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Image.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Image.chs","new_contents":"","old_contents":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Image\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2005\/02\/13 16:25:56 $\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-- This widget displays an image.\n--\n--\n-- * Because Haskell is not the best language to modify large images directly\n-- only functions are bound that allow loading images from disc or by stock\n-- names.\n--\n-- * Another function for extracting the 'Pixbuf' is added for \n-- 'CellRenderer'.\n--\n-- TODO\n--\n-- * Figure out what other functions are useful within Haskell. Maybe we should\n-- support loading Pixmaps without exposing them.\n--\nmodule Graphics.UI.Gtk.Display.Image (\n Image,\n ImageClass,\n castToImage,\n imageNewFromFile,\n IconSize,\n iconSizeMenu,\n iconSizeSmallToolbar,\n iconSizeLargeToolbar,\n iconSizeButton,\n iconSizeDialog,\n imageNewFromStock,\n imageGetPixbuf,\n imageSetFromPixbuf,\n imageNewFromPixbuf\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(IconSize, iconSizeInvalid, iconSizeMenu,\n\t\t\t\t\t iconSizeSmallToolbar, iconSizeLargeToolbar,\n\t\t\t\t\t iconSizeButton, iconSizeDialog)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create an image by loading a file.\n--\nimageNewFromFile :: FilePath -> IO Image\nimageNewFromFile path = makeNewObject mkImage $ liftM castPtr $ \n\n\n\n withUTFString path {#call unsafe image_new_from_file#}\n\n\n-- | Create a set of images by specifying a stock\n-- object.\n--\nimageNewFromStock :: String -> IconSize -> IO Image\nimageNewFromStock stock ic = withUTFString stock $ \\strPtr -> \n makeNewObject mkImage $ liftM castPtr $ {#call unsafe image_new_from_stock#}\n strPtr (fromIntegral ic)\n\n-- | Extract the Pixbuf from the 'Image'.\n--\nimageGetPixbuf :: Image -> IO Pixbuf\nimageGetPixbuf img = makeNewGObject mkPixbuf $ liftM castPtr $\n throwIfNull \"Image.imageGetPixbuf: The image contains no Pixbuf object.\" $\n {#call unsafe image_get_pixbuf#} img\n\n\n-- | Overwrite the current content of the 'Image' with a new 'Pixbuf'.\n--\nimageSetFromPixbuf :: Image -> Pixbuf -> IO ()\nimageSetFromPixbuf img pb = {#call unsafe gtk_image_set_from_pixbuf#} img pb\n\n-- | Create an 'Image' from a \n-- 'Pixbuf'.\n--\nimageNewFromPixbuf :: Pixbuf -> IO Image\nimageNewFromPixbuf pbuf = makeNewObject mkImage $ liftM castPtr $\n {#call unsafe image_new_from_pixbuf#} pbuf\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f6f7dbd30e6578453e7453459d6bdc3467b3b418","subject":"Added support for sharing an OpenGL context with OpenCL.","message":"Added support for sharing an OpenGL context with OpenCL.\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#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","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#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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"57f4506e47fdd979e77c1b54579bedb21bb42962","subject":"Clean up Git2 module","message":"Clean up Git2 module\n","repos":"norm2782\/hgit2","old_file":"src\/Data\/HGit2\/Git2.chs","new_file":"src\/Data\/HGit2\/Git2.chs","new_contents":"module Data.HGit2.Git2 where\n\nimport Foreign\nimport Foreign.C.Types\n\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.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 CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"daa4702e38d91bb9b7b12eeddda9c6bfa548ab98","subject":"Use common sense with the array termination.","message":"Use common sense with the array termination.\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, RecordWildCards #-}\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, JPEGSaveSettings(..)\n, PNGSaveSettings(..)\n, SaveImageSettings\n, saveImage\n, saveBGRAImage\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, bgraTobgr8\n, bgrTobgra8\n, bgraToGray8\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\nimport Data.Default\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 bgrTobgra8 <$> unsafeloadUsing imageTo8Bit 1 fp\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\nbgraToGray8 :: Image BGRA D8 -> Image GrayScale D8\nbgraToGray8 = S . convert8UTo BGR2GRAY 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\nbgraTobgr8 :: Image BGRA D8 -> Image BGR D8\nbgraTobgr8 = S . convert8UTo BGRA2BGR 3 . unS\n\nbgrTobgra8 :: Image BGR D8 -> Image BGRA D8\nbgrTobgra8 = 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\ndata JPEGSaveSettings = JPEGSaveSettings { jpegQuality :: Maybe Int } deriving (Show, Eq)\n\ninstance Default JPEGSaveSettings where\n def = JPEGSaveSettings Nothing\n\ndata PNGSaveSettings = PNGSaveSettings\n { pngCompression :: Maybe Int\n , pngStrategy :: Maybe Int\n , pngBilevel :: Maybe Int\n , pngStrategyDefault :: Maybe Int\n , pngStrategyFiltered :: Maybe Int\n , pngStrategyHuffmanOnly :: Maybe Int\n , pngStrategyRLE:: Maybe Int\n , pngStrategyFixed :: Maybe Int\n } deriving (Eq, Show)\ninstance Default PNGSaveSettings where\n def = PNGSaveSettings Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n\n#c\nenum SaveImageCodes {\n SICJPEGQuality =CV_IMWRITE_JPEG_QUALITY,\n SICPNGCompression =CV_IMWRITE_PNG_COMPRESSION,\n SICPNGStrategy =CV_IMWRITE_PNG_STRATEGY,\n SICPNGBilevel =CV_IMWRITE_PNG_BILEVEL,\n SICPNGStrategyDefault =CV_IMWRITE_PNG_STRATEGY_DEFAULT,\n SICPNGStrategyFiltered =CV_IMWRITE_PNG_STRATEGY_FILTERED,\n SICPNGStrategyHuffmanOnly =CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY,\n SICPNGStrategyRLE =CV_IMWRITE_PNG_STRATEGY_RLE,\n SICPNGStrategyFixed =CV_IMWRITE_PNG_STRATEGY_FIXED,\n SICPXMBinary =CV_IMWRITE_PXM_BINARY\n };\n#endc\n\n{#enum SaveImageCodes {}#}\nderiving instance Show SaveImageCodes\n\nclass SaveImageSettings a where\n toParamList :: a -> [Int]\n\nwriteParam :: SaveImageCodes -> Maybe Int -> [Int] -> [Int]\nwriteParam code (Just value) = (++) [fromIntegral (fromEnum code), value]\nwriteParam _ _ = id\n\ninstance SaveImageSettings JPEGSaveSettings where\n toParamList JPEGSaveSettings{..} =\n writeParam SICJPEGQuality jpegQuality [0]\n\ninstance SaveImageSettings PNGSaveSettings where\n toParamList PNGSaveSettings{..} =\n writeParam SICPNGCompression pngCompression\n $ writeParam SICPNGStrategy pngStrategy\n $ writeParam SICPNGBilevel pngBilevel\n $ writeParam SICPNGStrategyDefault pngStrategyDefault\n $ writeParam SICPNGStrategyFiltered pngStrategyFiltered\n $ writeParam SICPNGStrategyHuffmanOnly pngStrategyHuffmanOnly\n $ writeParam SICPNGStrategyRLE pngStrategyRLE\n $ writeParam SICPNGStrategyFixed pngStrategyFixed [0]\n\ncheckDirectory :: FilePath -> IO ()\ncheckDirectory filename = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n checkDirectory filename\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\nprimitiveSave' :: SaveImageSettings a => FilePath -> BareImage -> a -> IO ()\nprimitiveSave' filename fpi saveParam = do\n let sp = map fromIntegral $ toParamList saveParam\n checkDirectory filename\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n allocaArray (length sp) (\\defs -> pokeArray defs sp >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n\n-- |Save an image\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\n-- Save Image BGRA D8 with compression settings\nsaveBGRAImage :: SaveImageSettings a => FilePath -> Image BGRA D8 -> a -> IO ()\nsaveBGRAImage filename image =\n primitiveSave' filename (unS $ image)\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\ninstance Blittable BGRA D8\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, RecordWildCards #-}\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, JPEGSaveSettings(..)\n, PNGSaveSettings(..)\n, SaveImageSettings\n, saveImage\n, saveBGRAImage\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, bgraTobgr8\n, bgrTobgra8\n, bgraToGray8\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\nimport Data.Default\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 bgrTobgra8 <$> unsafeloadUsing imageTo8Bit 1 fp\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\nbgraToGray8 :: Image BGRA D8 -> Image GrayScale D8\nbgraToGray8 = S . convert8UTo BGR2GRAY 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\nbgraTobgr8 :: Image BGRA D8 -> Image BGR D8\nbgraTobgr8 = S . convert8UTo BGRA2BGR 3 . unS\n\nbgrTobgra8 :: Image BGR D8 -> Image BGRA D8\nbgrTobgra8 = 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\ndata JPEGSaveSettings = JPEGSaveSettings { jpegQuality :: Maybe Int } deriving (Show, Eq)\n\ninstance Default JPEGSaveSettings where\n def = JPEGSaveSettings Nothing\n\ndata PNGSaveSettings = PNGSaveSettings\n { pngCompression :: Maybe Int\n , pngStrategy :: Maybe Int\n , pngBilevel :: Maybe Int\n , pngStrategyDefault :: Maybe Int\n , pngStrategyFiltered :: Maybe Int\n , pngStrategyHuffmanOnly :: Maybe Int\n , pngStrategyRLE:: Maybe Int\n , pngStrategyFixed :: Maybe Int\n } deriving (Eq, Show)\ninstance Default PNGSaveSettings where\n def = PNGSaveSettings Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n Nothing\n\n#c\nenum SaveImageCodes {\n SICJPEGQuality =CV_IMWRITE_JPEG_QUALITY,\n SICPNGCompression =CV_IMWRITE_PNG_COMPRESSION,\n SICPNGStrategy =CV_IMWRITE_PNG_STRATEGY,\n SICPNGBilevel =CV_IMWRITE_PNG_BILEVEL,\n SICPNGStrategyDefault =CV_IMWRITE_PNG_STRATEGY_DEFAULT,\n SICPNGStrategyFiltered =CV_IMWRITE_PNG_STRATEGY_FILTERED,\n SICPNGStrategyHuffmanOnly =CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY,\n SICPNGStrategyRLE =CV_IMWRITE_PNG_STRATEGY_RLE,\n SICPNGStrategyFixed =CV_IMWRITE_PNG_STRATEGY_FIXED,\n SICPXMBinary =CV_IMWRITE_PXM_BINARY\n };\n#endc\n\n{#enum SaveImageCodes {}#}\nderiving instance Show SaveImageCodes\n\nclass SaveImageSettings a where\n toParamList :: a -> [Int]\n\nwriteParam :: SaveImageCodes -> Maybe Int -> [Int] -> [Int]\nwriteParam code (Just value) = (++) [fromIntegral (fromEnum code), value, 0]\nwriteParam _ _ = id\n\ninstance SaveImageSettings JPEGSaveSettings where\n toParamList JPEGSaveSettings{..} =\n writeParam SICJPEGQuality jpegQuality []\n\ninstance SaveImageSettings PNGSaveSettings where\n toParamList PNGSaveSettings{..} =\n writeParam SICPNGCompression pngCompression\n $ writeParam SICPNGStrategy pngStrategy\n $ writeParam SICPNGBilevel pngBilevel\n $ writeParam SICPNGStrategyDefault pngStrategyDefault\n $ writeParam SICPNGStrategyFiltered pngStrategyFiltered\n $ writeParam SICPNGStrategyHuffmanOnly pngStrategyHuffmanOnly\n $ writeParam SICPNGStrategyRLE pngStrategyRLE\n $ writeParam SICPNGStrategyFixed pngStrategyFixed []\n\ncheckDirectory :: FilePath -> IO ()\ncheckDirectory filename = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n checkDirectory filename\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\nprimitiveSave' :: SaveImageSettings a => FilePath -> BareImage -> a -> IO ()\nprimitiveSave' filename fpi saveParam = do\n let sp = map fromIntegral $ toParamList saveParam\n checkDirectory filename\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n allocaArray (length sp) (\\defs -> pokeArray defs sp >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n\n-- |Save an image\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\n-- Save Image BGRA D8 with compression settings\nsaveBGRAImage :: SaveImageSettings a => FilePath -> Image BGRA D8 -> a -> IO ()\nsaveBGRAImage filename image =\n primitiveSave' filename (unS $ image)\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\ninstance Blittable BGRA D8\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":"7ecdf9c9bb1c66b5b9cd01599d30c5878aa10d16","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,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 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\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 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, 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 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":"6ccc7e822c95c95422f973d04d689f800d0c7535","subject":"gstreamer: M.S.G.Core.Element: document everything, use new signal types","message":"gstreamer: M.S.G.Core.Element: document everything, use new signal types\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Element.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 pipeline elements.\nmodule Media.Streaming.GStreamer.Core.Element (\n\n-- * Detail\n\n -- | 'Element' is the abstract base class needed to construct an\n -- element that can be used in a GStreamer pipeline.\n -- \n -- All elements have pads (of the type 'Pad'). These pads link to\n -- pads on other elements. 'Buffer's flow between these linked\n -- pads. An 'Element' has a 'Pad' for each input (or sink) and\n -- output (or source).\n -- \n -- An element's pad can be retrieved by name with\n -- 'elementGetStaticPad' or 'elementGetRequestPad'. An 'Iterator'\n -- over all an element's pads can be retrieved with\n -- 'elementIteratePads'.\n -- \n -- Elements can be linked through their pads. If the link is\n -- straightforward, use the 'elementLink' convenience function to\n -- link two elements. Use 'elementLinkFiltered' to link two\n -- elements constrained by a specified set of 'Caps'. For finer\n -- control, use 'elementLinkPads' and 'elementLinkPadsFiltered' to\n -- specify the pads to link on each element by name.\n -- \n -- Each element has a 'State'. You can get and set the state of an\n -- element with 'elementGetState' and 'elementSetState'. To get a\n -- string representation of a 'State', use 'elementStateGetName'.\n -- \n -- You can get and set a 'Clock' on an element using\n -- 'elementGetClock' and 'elementSetClock'. Some elements can\n -- provide a clock for the pipeline if 'elementProvidesClock'\n -- returns 'True'. With the 'elementProvideClock' method one can\n -- retrieve the clock provided by such an element. Not all\n -- elements require a clock to operate correctly. If\n -- 'elementRequiresClock' returns 'True', a clock should be set on\n -- the element with 'elementSetClock'.\n -- \n -- Note that clock slection and distribution is normally handled\n -- by the toplevel 'Pipeline' so the clock functions should only\n -- be used in very specific situations.\n\n-- * Types \n Element,\n ElementClass,\n castToElement,\n toElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n\n-- * Element Operations\n elementAddPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n elementNoMorePads,\n elementPadAdded,\n elementPadRemoved,\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on the element.\nelementGetFlags :: ElementClass elementT\n => elementT\n -> IO [ElementFlags]\nelementGetFlags = mkObjectGetFlags\n\n-- | Set the given flags on the element.\nelementSetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementSetFlags = mkObjectSetFlags\n\n-- | Unset the given flags on the element.\nelementUnsetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementUnsetFlags = mkObjectUnsetFlags\n\n-- | Add a pad (link point) to an element. The pad's parent will be set to\n-- @element@.\n-- \n-- Pads are not automatically activated so elements should perform\n-- the needed steps to activate the pad in case this pad is added in\n-- the 'StatePaused' or 'StatePlaying' state. See 'padSetActive' for\n-- more information about activating pads.\n-- \n-- This function will emit the 'elementPadAdded' signal on the\n-- element.\nelementAddPad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\n-- | Look for an unlinked pad to which the given pad can link. It is not\n-- guaranteed that linking the pads will work, though it should work in most\n-- cases.\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - the element for\n -- which a pad should be found\n -> padT -- ^ @pad@ - the pad to find\n -- a compatible one for\n -> Caps -- ^ @caps@ - the 'Caps' to\n -- use as a filter\n -> IO (Maybe Pad) -- ^ the compatible 'Pad', or\n -- 'Nothing' if none was found\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek takeObject\n\n-- | Retrieve a pad template from @element@ that is compatible with\n-- @padTemplate@. Pads from compatible templates can be linked\n-- together.\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT)\n => elementT -- ^ @element@ - \n -> padTemplateT -- ^ @padTemplate@ - \n -> IO (Maybe PadTemplate) -- ^ the compatible'PadTemplate',\n -- or 'Nothing' if none was found\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek takeObject\n\n-- | Retrieve a pad from the element by name. This version only\n-- retrieves request pads. The pad should be released with\n-- 'elementReleaseRequestPad'.\nelementGetRequestPad :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> String -- ^ @name@ - \n -> IO (Maybe Pad) -- ^ the requested 'Pad' if\n -- found, otherwise 'Nothing'.\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek peekObject\n\n-- | Retreive a pad from @element@ by name. This version only\n-- retrieves already-existing (i.e. \"static\") pads.\nelementGetStaticPad :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> String -- ^ @name@ - \n -> IO (Maybe Pad) -- ^ the requested 'Pad' if\n -- found, otherwise 'Nothing'.\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek takeObject\n\n-- | Release a request pad that was previously obtained with\n-- 'elementGetRequestPad'.\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\n-- | Remove @pad@ from @element@.\n-- \n-- This function is used by plugin developers and should not be used\n-- by applications. Pads that were dynamically requested from\n-- elements with 'elementGetRequestPad' should be released with the\n-- 'elementReleaseRequestPad' function instead.\n-- \n-- Pads are not automatically deactivated so elements should perform the needed\n-- steps to deactivate the pad in case this pad is removed in the PAUSED or\n-- PLAYING state. See 'padSetActive' for more information about\n-- deactivating pads.\n-- \n-- The pad and the element should be unlocked when calling this function.\n-- \n-- This function will emit the 'padRemoved' signal on the element.\n-- \n-- Returns: 'True' if the pad could be removed. Can return 'False' if the\n-- pad does not belong to the provided element.\nelementRemovePad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO Bool -- ^ 'True' if the pad was succcessfully\n -- removed, otherwise 'False'\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\n-- | Retrieve an 'Iterator' over @element@'s pads.\nelementIteratePads :: (ElementClass elementT)\n => elementT -- ^ @element@ - \n -> IO (Iterator Pad) -- ^ an iterator over the element's pads.\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= takeIterator\n\n\n-- | Retrieve an 'Iterator' over @element@'s sink pads.\nelementIterateSinkPads :: (ElementClass elementT)\n => elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\n-- | Retrieve an 'Iterator' over @element@'s src pads.\nelementIterateSrcPads :: (ElementClass elementT)\n => elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\n-- | Link @src@ to @sink@. The link must be from source to\n-- sink; the other direction will not be tried. The function\n-- looks for existing pads that aren't linked yet. It will request\n-- new pads if necessary. Such pads must be released manually (with\n-- 'elementReleaseRequestPad') when unlinking. If multiple links are\n-- possible, only one is established.\n-- \n-- Make sure you have added your elements to a 'Bin' or 'Pipeline'\n-- with 'binAdd' before trying to link them.\nelementLink :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> sinkT -- ^ @sink@ - \n -> IO Bool -- ^ 'True' if the pads could be linked,\n -- otherwise 'False'\nelementLink src sink =\n liftM toBool $ {# call element_link #} (toElement src) (toElement sink)\n\n-- | Unlink all source pads of the @src@ from all sink pads of the\n-- @sink@.\nelementUnlink :: (ElementClass srcT, ElementClass sinkT)\n => srcT\n -> sinkT\n -> IO ()\nelementUnlink src sink =\n {# call element_unlink #} (toElement src) (toElement sink)\n\n-- | Link the named pads of @src@ and @sink@.\nelementLinkPads :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - the element containing the source pad\n -> Maybe String -- ^ @srcPadName@ - the name of the source pad, or 'Nothing' for any pad\n -> sinkT -- ^ @sink@ - the element containing the sink pad\n -> Maybe String -- ^ @sinkPadName@ - the name of the sink pad, or 'Nothing' for any pad\n -> IO Bool -- ^ 'True' if the pads could be linked, otherwise 'False'\nelementLinkPads src srcPadName sink sinkPadName =\n maybeWith withUTFString sinkPadName $ \\cSinkPadName ->\n maybeWith withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement sink) cSinkPadName\n\n-- | Unlink the named pads of @src@ and @sink@.\nelementUnlinkPads :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> String -- ^ @srcPadName@ - \n -> sinkT -- ^ @sink@ - \n -> String -- ^ @sinkPadName@ - \n -> IO ()\nelementUnlinkPads src srcPadName sink sinkPadName =\n withUTFString sinkPadName $ \\cSinkPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement sink) cSinkPadName\n\n-- | Link the named pads of @src@ and @sink@. A side effect is that if\n-- one of the pads has no parent, it becomes a child of the parent\n-- of the other element. If they have different parents, the link\n-- will fail. If @caps@ is not 'Nothing', make sure that the 'Caps'\n-- of the link is a subset of @caps@.\nelementLinkPadsFiltered :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> Maybe String -- ^ @srcPadName@ - \n -> sinkT -- ^ @sink@ - \n -> Maybe String -- ^ @sinkPadName@ - \n -> Caps -- ^ @caps@ - \n -> IO Bool -- ^ 'True' if the pads could be\n -- linked, otherwise 'False'\nelementLinkPadsFiltered src srcPadName sink sinkPadName filter =\n maybeWith withUTFString sinkPadName $ \\cSinkPadName ->\n maybeWith withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement sink) cSinkPadName filter\n\n-- | Link @src@ to @dest@ using the given 'Caps' as a filter. The link\n-- must be from source to sink; the other direction will not be\n-- tried. The function looks for existing pads that aren't linked\n-- yet. If will request new pads if necessary. If multiple links are\n-- possible, only one is established.\n-- \n-- Make sure you have added your elements to a 'Bin' or 'Pipeline'\n-- with 'binAdd' before trying to link them.\nelementLinkFiltered :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> sinkT -- ^ @sink@ - \n -> Maybe Caps -- ^ @caps@ - \n -> IO Bool -- ^ 'True' if the pads could be\n -- linked, otherwise 'False'\nelementLinkFiltered src sink filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement src) (toElement sink) $\n fromMaybe (Caps nullForeignPtr) filter\n\n-- | Set the base time of @element@. See 'elementGetBaseTime' for more\n-- information.\nelementSetBaseTime :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> ClockTimeDiff -- ^ @time@ - \n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\n-- | Return the base time of @element@. The base time is the absolute\n-- time of the clock when this element was last set to\n-- 'StatePlaying'. Subtract the base time from the clock time to get\n-- the stream time of the element.\nelementGetBaseTime :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ClockTimeDiff -- ^ the base time of the element\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\n-- | Set the 'Bus' used by @element@. For internal use only, unless\n-- you're testing elements.\nelementSetBus :: (ElementClass elementT, BusClass busT)\n => elementT -- ^ @element@ - \n -> busT -- ^ @bus@ - \n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\n-- | Get the bus of @element@. Not that only a 'Pipeline' will\n-- provide a bus for the application.\nelementGetBus :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bus -- ^ the bus used by the element\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= takeObject\n\n-- | Get the factory used to create @element@.\nelementGetFactory :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ElementFactory -- ^ the factory that created @element@\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= peekObject\n\n-- | Set the 'Index' used by @element@.\nelementSetIndex :: (ElementClass elementT, IndexClass indexT)\n => elementT -- ^ @element@ - \n -> indexT -- ^ @index@ - \n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\n-- | Get the 'Index' used by @element@.\nelementGetIndex :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Index) -- ^ the index, or 'Nothing' if @element@ has none\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek takeObject\n\n-- | Determine whether @element@ can be indexed.\nelementIsIndexable :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element can be indexed\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\n-- | Determine whether @element@ requires a clock.\nelementRequiresClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element requires a clock\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\n-- | Set the 'Clock' used by @element@.\nelementSetClock :: (ElementClass elementT, ClockClass clockT)\n => elementT -- ^ @element@ - \n -> clockT -- ^ @clock@ - \n -> IO Bool -- ^ 'True' if the element accepted the clock\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\n-- | Get the 'Clock' used by @element@.\nelementGetClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Clock) -- ^ the clock, or 'Nothing' if @element@ has none\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek takeObject\n\n-- | Determine whether @element@ provides a clock. A 'Clock' provided\n-- by an element can be used as the global clock for a pipeline. An\n-- element that can provide a clock is only required to do so in the\n-- 'StatePaused' state, meaning that it is fully negotiated and has\n-- allocated the resources needed to operate the clock.\nelementProvidesClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element provides a clock\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\n-- | Get the 'Clock' provided by @element@.\n-- \n-- Note that an element is only required to provide a clock in the\n-- 'StatePaused' state. Some elements can provide a clock in other\n-- states.\nelementProvideClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Clock) -- ^ a 'Clock', or 'Nothing' if\n -- none could be provided\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek takeObject\n\n-- | Set the state of @element@ to @state@. This function will try to\n-- set the requested state by going through all the intermediary\n-- states and calling the class's state change function for each.\n-- \n-- This function can return 'StateChangeAsync', in which case the\n-- element will perform the remainder of the state change\n-- asynchronously in another thread. An application can use\n-- 'elementGetState' to wait for the completion of the state change\n-- or it can wait for a state change message on the bus.\nelementSetState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> State -- ^ @state@ - \n -> IO StateChangeReturn -- ^ the result of the state change\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\n-- | Get the state of @element@.\n-- \n-- For elements that performed an asynchronous state change, as\n-- reported by 'elementSetState', this function will block up to the\n-- specified timeout value for the state change to complete. If the\n-- element completes the state change or goes into an error, this\n-- function returns immediately with a return value of\n-- 'StateChangeSuccess' or 'StateChangeFailure', respectively.\n-- \n-- This function returns 'StateChangeNoPreroll' if the element\n-- successfully changed its state but is not able to provide data\n-- yet. This mostly happens for live sources that not only produce\n-- data in the 'StatePlaying' state. While the state change return\n-- is equivalent to 'StateChangeSuccess', it is returned to the\n-- application to signal that some sink elements might not be able\n-- to somplete their state change because an element is not\n-- producing data to complete the preroll. When setting the element\n-- to playing, the preroll will complete and playback will start.\nelementGetState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> ClockTime -- ^ @timeout@ - \n -> IO (StateChangeReturn, Maybe State, Maybe State)\n -- ^ the result of the state change, the current\n -- state, and the pending state\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do poke statePtr (-1) -- -1 is not use by any enum value\n poke pendingPtr (-1)\n result <- {# call element_get_state #} (toElement element)\n statePtr\n pendingPtr\n (fromIntegral timeout)\n state <- unmarshalState statePtr\n pending <- unmarshalState pendingPtr\n return (toEnum $ fromIntegral result, state, pending)\n where unmarshalState statePtr = do\n cState <- peek statePtr\n if cState \/= -1\n then return $ Just $ toEnum $ fromIntegral cState\n else return Nothing\n\n-- | Lock the state of @element@, so state changes in the parent don't\n-- affect this element any longer.\nelementSetLockedState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> Bool -- ^ @lockedState@ - 'True' for locked, 'False' for unlocked\n -> IO Bool -- ^ 'True' if the state was changed, 'False' if bad\n -- parameters were given or no change was needed\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\n-- | Determine whether @element@'s state is locked.\nelementIsLockedState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if @element@'s state is locked, 'False' otherwise\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\n-- | Abort @element@'s state change. This function is used by elements\n-- that do asynchronous state changes and find out something is wrong.\n-- \n-- This function should be called with the state lock held.\nelementAbortState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\n-- | Get a string representation of @state@.\nelementStateGetName :: State -- ^ @state@ - \n -> String -- ^ the name of @state@\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\n-- | Get a string representation of @stateRet@.\nelementStateChangeReturnGetName :: StateChangeReturn -- ^ @stateRet@ - \n -> String -- ^ the name of @stateRet@\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\n-- | Try to change the state of @element@ to the same as its\n-- parent. If this function returns 'False', the state of the\n-- element is undefined.\nelementSyncStateWithParent :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element's state could be\n -- synced with its parent's state\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\n-- | Perform a query on the given element.\n-- \n-- For elements that don't implement a query handler, this function\n-- forwards the query to a random srcpad or to the peer of a random\n-- linked sinkpad of this element.\nelementQuery :: (ElementClass element, QueryClass query)\n => element -- ^ @element@ - \n -> query -- ^ @query@ - \n -> IO Bool -- ^ 'True' if the query could be performed\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n fmap toBool $ {# call element_query #} (toElement element) $ Query query'\n\n-- | Query an element for the convertion of a value from one format to\n-- another.\nelementQueryConvert :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @srcFormat@ - the format to convert from\n -> Int64 -- ^ @srcVal@ - the value to convert\n -> Format -- ^ @destFormat@ - the format to convert to\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryConvert element srcFormat srcVal destFormat =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do poke destFormatPtr $ fromIntegral $ fromEnum destFormat\n success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\n-- | Query an element for its stream position.\nelementQueryPosition :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @format@ - the format requested\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryPosition element format =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\n-- | Query an element for its stream duration.\nelementQueryDuration :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @format@ - the format requested\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryDuration element format =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\n-- | Send an event to an element.\n-- \n-- If the element doesn't implement an event handler, the event will\n-- be pushed to a random linked sink pad for upstream events or a\n-- random linked source pad for downstream events.\nelementSendEvent :: (ElementClass element, EventClass event)\n => element -- ^ @element@ - the element to send the event to\n -> event -- ^ @event@ - the event to send\n -> IO Bool -- ^ 'True' if the event was handled\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\n-- | Perform a seek on the given element. This function only supports\n-- seeking to a position relative to the start of the stream. For\n-- more complex operations like segment seeks (such as for looping),\n-- or changing the playback rate, or seeking relative to the last\n-- configured playback segment you should use 'elementSeek'.\n-- \n-- In a completely prerolled pipeline in the 'StatePaused' or\n-- 'StatePlaying' states, seeking is always guaranteed to return\n-- 'True' on a seekable media type, or 'False' when the media type\n-- is certainly not seekable (such as a live stream).\n-- \n-- Some elements allow for seeking in the 'StateReady' state, in\n-- which case they will store the seek event and execute it when\n-- they are put into the 'StatePaused' state. If the element\n-- supports seek in \"StateReady\", it will always return 'True' when\n-- it recieves the event in the 'StateReady' state.\nelementSeekSimple :: ElementClass element\n => element -- ^ @element@ - the element to seek on\n -> Format -- ^ @format@ - the 'Format' to evecute the seek in,\n -- such as 'FormatTime'\n -> [SeekFlags] -- ^ @seekFlags@ - seek options; playback applications\n -- will usually want to use\n -- @['SeekFlagFlush','SeekFlagKeyUnit']@\n -> Int64 -- ^ @seekPos@ - the position to seek to, relative to\n -- start; if you are doing a seek in\n -- 'FormatTime' this value is in nanoseconds;\n -- see 'second', 'msecond', 'usecond', &\n -- 'nsecond'\n -> IO Bool -- ^ 'True' if the seek operation succeeded\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\n-- | Send a seek event to an element. See\n-- 'Media.Streaming.GStreamer.Core.Event.eventNewSeek' for the\n-- details of the parameters. The seek event is sent to the element\n-- using 'elementSendEvent'.\nelementSeek :: ElementClass element\n => element -- ^ @element@ - the element to seek on\n -> Double -- ^ @rate@ - the new playback rate\n -> Format -- ^ @format@ - the format of the seek values\n -> [SeekFlags] -- ^ @seekFlags@ - the options to use\n -> SeekType -- ^ @curType@ - type and flags for the new current position\n -> Int64 -- ^ @cur@ - the value of the new current position\n -> SeekType -- ^ @stopType@ - type and flags for the new stop position\n -> Int64 -- ^ @stop@ - the value of the new stop position\n -> IO Bool -- ^ 'True' if the event was handled\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\n-- | The signal emitted when an element will not generate more dynamic\n-- pads.\nelementNoMorePads :: (ElementClass element)\n => Signal element (IO ())\nelementNoMorePads =\n Signal $ connect_NONE__NONE \"no-more-pads\"\n\n-- | The signal emitted when a new 'Pad' has been added to the\n-- element.\nelementPadAdded :: (ElementClass element)\n => Signal element (Pad -> IO ())\nelementPadAdded =\n Signal $ connect_OBJECT__NONE \"pad-added\"\n\n-- | The signal emitted when a 'Pad' has been removed from the\n-- element.\nelementPadRemoved :: (ElementClass element)\n => Signal element (Pad -> IO ())\nelementPadRemoved =\n Signal $ connect_OBJECT__NONE \"pad-removed\"\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.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementGetFlags :: ElementClass elementT\n => elementT\n -> IO [ElementFlags]\nelementGetFlags = mkObjectGetFlags\n\nelementSetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementSetFlags = mkObjectSetFlags\n\nelementUnsetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementUnsetFlags = mkObjectUnsetFlags\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek takeObject\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek takeObject\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek takeObject\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek peekObject\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek takeObject\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= takeIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= takeObject\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= peekObject\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek takeObject\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek takeObject\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek takeObject\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM Just $ withForeignPtr query' $ takeMiniObject . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Word64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> Format\n -> IO (Maybe (Format, Word64))\nelementQueryPosition element format =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> Format\n -> IO (Maybe (Format, Word64))\nelementQueryDuration element format =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"aad6d2239ce0d7cc26affa904841bb22331eff2a","subject":"Switch on \"non-GNU\" option","message":"Switch on \"non-GNU\" option\n","repos":"ian-ross\/c2hs-macos-test,ian-ross\/c2hs-macos-test,ian-ross\/c2hs-macos-test","old_file":"issue-82\/Issue82.chs","new_file":"issue-82\/Issue82.chs","new_contents":"module Main where\n\n{# nonGNU #}\n#include \"string.h\"\n\nmain :: IO ()\nmain = putStrLn \"OK\"\n","old_contents":"module Main where\n\n#include \"string.h\"\n\nmain :: IO ()\nmain = putStrLn \"OK\"\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"295a28e05a9db762a07801ad1ce2a85086f29843","subject":"Fix signature of callbacks that may pass NULL objects.","message":"Fix signature of callbacks that may pass NULL objects.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Widget -> IO ())\nparentSet = Signal (connect_OBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Widget -> IO ())\nhierarchyChanged = Signal (connect_OBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7910426d8870ce1aeabaa092cf914695f6568de0","subject":"Fix an incorrect pattern in windowSetIcon.","message":"Fix an incorrect pattern in windowSetIcon.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow, gTypeWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\n{#import Graphics.UI.Gtk.Gdk.Keys#} (KeyVal)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this 'Window'. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO (Maybe Widget)\nwindowGetDefaultWidget self = \n maybeNull (makeNewObject mkWidget) $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- Enter in a dialog (for example). This function sets or unsets the default\n-- widget for a Window about. When setting (rather than unsetting) the\n-- default widget it's generally easier to call widgetGrabDefault on the\n-- widget. Before making a widget the default widget, you must set the\n-- 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n#endif\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ returns @(left, top, right, bottom)@. @left@ is the\n -- width of the frame at the left, @top@ is the height of the frame at the top, @right@\n -- is the width of the frame at the right, @bottom@ is the height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Maybe Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self Nothing =\n {# call gtk_window_set_icon #}\n (toWindow self)\n (Pixbuf nullForeignPtr)\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO (Maybe Pixbuf) -- ^ returns icon for window, or @Nothing@ if none was set\nwindowGetIcon self =\n maybeNull (makeNewGObject mkPixbuf) $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self (Maybe Pixbuf)\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame-event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys-changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set-focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set-focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set-focus\" True\n\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow, gTypeWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\n{#import Graphics.UI.Gtk.Gdk.Keys#} (KeyVal)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this 'Window'. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO (Maybe Widget)\nwindowGetDefaultWidget self = \n maybeNull (makeNewObject mkWidget) $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- Enter in a dialog (for example). This function sets or unsets the default\n-- widget for a Window about. When setting (rather than unsetting) the\n-- default widget it's generally easier to call widgetGrabDefault on the\n-- widget. Before making a widget the default widget, you must set the\n-- 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n#endif\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ returns @(left, top, right, bottom)@. @left@ is the\n -- width of the frame at the left, @top@ is the height of the frame at the top, @right@\n -- is the width of the frame at the right, @bottom@ is the height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Maybe Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n (Pixbuf nullForeignPtr)\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO (Maybe Pixbuf) -- ^ returns icon for window, or @Nothing@ if none was set\nwindowGetIcon self =\n maybeNull (makeNewGObject mkPixbuf) $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self (Maybe Pixbuf)\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame-event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys-changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set-focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set-focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set-focus\" True\n\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"86f38f8de039d4ff5f7cb207cd291f1713696643","subject":"add maximum registers per thread to device data table","message":"add maximum registers per thread to device data table\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 Warp -- Kepler GK11x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6b69044a6493726c5bcb7093af4aea9d75c23c9c","subject":"Work with ghc 7.4","message":"Work with ghc 7.4\n","repos":"travitch\/llvm-data-interop,travitch\/llvm-data-interop","old_file":"src\/Data\/LLVM\/Interop.chs","new_file":"src\/Data\/LLVM\/Interop.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes, OverloadedStrings #-}\nmodule Data.LLVM.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems )\nimport Data.Array.Unsafe ( unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Attributes\nimport Data.LLVM.Dwarf\nimport Data.LLVM.Identifiers\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\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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaFileFilename :: InternString m => MetaPtr -> m ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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\nclass MonadIO m => InternString m where\n internString :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes, OverloadedStrings #-}\nmodule Data.LLVM.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Attributes\nimport Data.LLVM.Dwarf\nimport Data.LLVM.Identifiers\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\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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaFileFilename :: InternString m => MetaPtr -> m ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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\nclass MonadIO m => InternString m where\n internString :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f1e31b03bc8a601f9744bd8ca18381d1af3e415e","subject":"[project @ 2005-10-30 11:56:30 by as49] Fix wrong link.","message":"[project @ 2005-10-30 11:56:30 by as49]\nFix wrong link.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte","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":"10a51e173e6388484279f4a811497cb168440d74","subject":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty","message":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty","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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"e6c97332350dc7e2448bf051c9f63ac606cfef49","subject":"Fix textView signals (rename `setScrollAdjustments` to `setTextViewScrollAdjustments`) and fix signal docs.","message":"Fix textView signals (rename `setScrollAdjustments` to `setTextViewScrollAdjustments`) and fix signal docs.","repos":"vincenthz\/webkit","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":"5667241782a2a9ce9d22e16c8600abbaed7fadde","subject":"Converted Datatype into abstract datatype","message":"Converted Datatype into abstract datatype\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 #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\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,\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare,\n isend, ibsend, issend, irecv, 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 (..),\n Group(MkGroup), 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 (..), StatusPtr,\n Tag, toTag, fromTag, tagVal, anyTag,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\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\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\ninitialized = {# call unsafe Initialized as initialized_ #}\nfinalized = {# call unsafe Finalized as finalized_ #}\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_ #}\ngetProcessorName = {# call unsafe Get_processor_name as getProcessorName_ #}\ngetVersion = {# call unsafe Get_version as getVersion_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #} <$> fromComm\ncommRank = {# call unsafe Comm_rank as commRank_ #} <$> fromComm\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #} <$> fromComm\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #} <$> fromComm\ncommCompare c1 c2 = {# call unsafe Comm_compare as commCompare_ #} (fromComm c1) (fromComm c2)\nprobe s t c = {# call Probe as probe_ #} s t (fromComm c)\nsend b cnt d r t c = {# call unsafe Send as send_ #} b cnt (fromDatatype d) r t (fromComm c)\nbsend b cnt d r t c = {# call unsafe Bsend as bsend_ #} b cnt (fromDatatype d) r t (fromComm c)\nssend b cnt d r t c = {# call unsafe Ssend as ssend_ #} b cnt (fromDatatype d) r t (fromComm c)\nrsend b cnt d r t c = {# call unsafe Rsend as rsend_ #} b cnt (fromDatatype d) r t (fromComm c)\nrecv b cnt d r t c = {# call unsafe Recv as recv_ #} b cnt (fromDatatype d) r t (fromComm c)\nisend b cnt d r t c = {# call unsafe Isend as isend_ #} b cnt (fromDatatype d) r t (fromComm c)\nibsend b cnt d r t c = {# call unsafe Ibsend as ibsend_ #} b cnt (fromDatatype d) r t (fromComm c)\nissend b cnt d r t c = {# call unsafe Issend as issend_ #} b cnt (fromDatatype d) r t (fromComm c)\nirecv b cnt d r t c = {# call Irecv as irecv_ #} b cnt (fromDatatype d) r t (fromComm c)\nbcast b cnt d r c = {# call unsafe Bcast as bcast_ #} b cnt (fromDatatype d) r (fromComm c)\nbarrier = {# call unsafe Barrier as barrier_ #} <$> fromComm\nwait = {# call unsafe Wait as wait_ #}\nwaitall = {# call unsafe Waitall as waitall_ #}\ntest = {# call unsafe Test as test_ #}\ncancel = {# call unsafe Cancel as cancel_ #}\nscatter sb se st rb re rt r c = {# call unsafe Scatter as scatter_ #} sb se (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\ngather sb se st rb re rt r c = {# call unsafe Gather as gather_ #} sb se (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\nscatterv sb sc sd st rb re rt r c = {# call unsafe Scatterv as scatterv_ #} sb sc sd (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\ngatherv sb se st rb rc rd rt r c = {# call unsafe Gatherv as gatherv_ #} sb se (fromDatatype st) rb rc rd (fromDatatype rt) r (fromComm c)\nallgather sb se st rb re rt c = {# call unsafe Allgather as allgather_ #} sb se (fromDatatype st) rb re (fromDatatype rt) (fromComm c)\nallgatherv sb se st rb rc rd rt c = {# call unsafe Allgatherv as allgatherv_ #} sb se (fromDatatype st) rb rc rd (fromDatatype rt) (fromComm c)\nalltoall sb sc st rb rc rt c = {# call unsafe Alltoall as alltoall_ #} sb sc (fromDatatype st) rb rc (fromDatatype rt) (fromComm c)\nalltoallv sb sc sd st rb rc rd rt c = {# call unsafe Alltoallv as alltoallv_ #} sb sc sd (fromDatatype st) rb rc rd (fromDatatype rt) (fromComm c)\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce sb rb se st o r c = {# call Reduce as reduce_ #} sb rb se (fromDatatype st) o r (fromComm c)\nallreduce sb rb se st o c = {# call Allreduce as allreduce_ #} sb rb se (fromDatatype st) o (fromComm c)\nreduceScatter sb rb cnt t o c = {# call Reduce_scatter as reduceScatter_ #} sb rb cnt (fromDatatype t) o (fromComm c)\nopCreate = {# call unsafe Op_create as opCreate_ #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\ncommGroup = {# call unsafe Comm_group as commGroup_ #} <$> fromComm\ngroupRank = {# call unsafe Group_rank as groupRank_ #} <$> fromGroup\ngroupSize = {# call unsafe Group_size as groupSize_ #} <$> fromGroup\ngroupUnion g1 g2 = {# call unsafe Group_union as groupUnion_ #} (fromGroup g1) (fromGroup g2)\ngroupIntersection g1 g2 = {# call unsafe Group_intersection as groupIntersection_ #} (fromGroup g1) (fromGroup g2)\ngroupDifference g1 g2 = {# call unsafe Group_difference as groupDifference_ #} (fromGroup g1) (fromGroup g2)\ngroupCompare g1 g2 = {# call unsafe Group_compare as groupCompare_ #} (fromGroup g1) (fromGroup g2)\ngroupExcl g = {# call unsafe Group_excl as groupExcl_ #} (fromGroup g)\ngroupIncl g = {# call unsafe Group_incl as groupIncl_ #} (fromGroup g)\ngroupTranslateRanks g1 s r g2 = {# call unsafe Group_translate_ranks as groupTranslateRanks_ #} (fromGroup g1) s r (fromGroup g2)\ntypeSize = {# call unsafe Type_size as typeSize_ #} <$> fromDatatype\nerrorClass = {# call unsafe Error_class as errorClass_ #}\nerrorString = {# call unsafe Error_string as errorString_ #}\ncommSetErrhandler = {# call unsafe Comm_set_errhandler as commSetErrhandler_ #} <$> fromComm\ncommGetErrhandler = {# call unsafe Comm_get_errhandler as commGetErrhandler_ #} <$> fromComm\nabort = {# call unsafe Abort as abort_ #} <$> fromComm\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 Errhandler = {# type MPI_Errhandler #}\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr Errhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr Errhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = 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 #}\n\nnewtype Group = MkGroup { fromGroup :: MPIGroup }\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 Operation = {# type MPI_Op #}\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr Operation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: Operation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: Operation\n-- foreign import ccall \"mpi_replace\" replaceOp :: Operation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = unsafePerformIO $ peek maxOp_\nminOp = unsafePerformIO $ peek minOp_\nsumOp = unsafePerformIO $ peek sumOp_\nprodOp = unsafePerformIO $ peek prodOp_\nlandOp = unsafePerformIO $ peek landOp_\nbandOp = unsafePerformIO $ peek bandOp_\nlorOp = unsafePerformIO $ peek lorOp_\nborOp = unsafePerformIO $ peek borOp_\nlxorOp = unsafePerformIO $ peek lxorOp_\nbxorOp = unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\n-- TODO: actually, this should be 32-bit int\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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 Request = {# type MPI_Request #}\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\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#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\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\n-- TODO: actually, this is a 32-bit int, and even less than that.\n-- See section 8 of MPI report about extracting MPI_TAG_UB\n-- and using it here\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\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,\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare,\n isend, ibsend, issend, irecv, 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 (..),\n Group(MkGroup), 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 (..), StatusPtr,\n Tag, toTag, fromTag, tagVal, anyTag,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\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\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\ninitialized = {# call unsafe Initialized as initialized_ #}\nfinalized = {# call unsafe Finalized as finalized_ #}\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_ #}\ngetProcessorName = {# call unsafe Get_processor_name as getProcessorName_ #}\ngetVersion = {# call unsafe Get_version as getVersion_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #} <$> fromComm\ncommRank = {# call unsafe Comm_rank as commRank_ #} <$> fromComm\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #} <$> fromComm\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #} <$> fromComm\ncommCompare c1 c2 = {# call unsafe Comm_compare as commCompare_ #} (fromComm c1) (fromComm c2)\nprobe s t c = {# call Probe as probe_ #} s t (fromComm c)\nsend b cnt d r t c = {# call unsafe Send as send_ #} b cnt d r t (fromComm c)\nbsend b cnt d r t c = {# call unsafe Bsend as bsend_ #} b cnt d r t (fromComm c)\nssend b cnt d r t c = {# call unsafe Ssend as ssend_ #} b cnt d r t (fromComm c)\nrsend b cnt d r t c = {# call unsafe Rsend as rsend_ #} b cnt d r t (fromComm c)\nrecv b cnt d r t c = {# call unsafe Recv as recv_ #} b cnt d r t (fromComm c)\nisend b cnt d r t c = {# call unsafe Isend as isend_ #} b cnt d r t (fromComm c)\nibsend b cnt d r t c = {# call unsafe Ibsend as ibsend_ #} b cnt d r t (fromComm c)\nissend b cnt d r t c = {# call unsafe Issend as issend_ #} b cnt d r t (fromComm c)\nirecv b cnt d r t c = {# call Irecv as irecv_ #} b cnt d r t (fromComm c)\nbcast b cnt d r c = {# call unsafe Bcast as bcast_ #} b cnt d r (fromComm c)\nbarrier = {# call unsafe Barrier as barrier_ #} <$> fromComm\nwait = {# call unsafe Wait as wait_ #}\nwaitall = {# call unsafe Waitall as waitall_ #}\ntest = {# call unsafe Test as test_ #}\ncancel = {# call unsafe Cancel as cancel_ #}\nscatter sb se st rb re rt r c = {# call unsafe Scatter as scatter_ #} sb se st rb re rt r (fromComm c)\ngather sb se st rb re rt r c = {# call unsafe Gather as gather_ #} sb se st rb re rt r (fromComm c)\nscatterv sb sc sd st rb re rt r c = {# call unsafe Scatterv as scatterv_ #} sb sc sd st rb re rt r (fromComm c)\ngatherv sb se st rb rc rd rt r c = {# call unsafe Gatherv as gatherv_ #} sb se st rb rc rd rt r (fromComm c)\nallgather sb se st rb re rt c = {# call unsafe Allgather as allgather_ #} sb se st rb re rt (fromComm c)\nallgatherv sb se st rb rc rd rt c = {# call unsafe Allgatherv as allgatherv_ #} sb se st rb rc rd rt (fromComm c)\nalltoall sb sc st rb rc rt c = {# call unsafe Alltoall as alltoall_ #} sb sc st rb rc rt (fromComm c)\nalltoallv sb sc sd st rb rc rd rt c = {# call unsafe Alltoallv as alltoallv_ #} sb sc sd st rb rc rd rt (fromComm c)\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce sb rb se st o r c = {# call Reduce as reduce_ #} sb rb se st o r (fromComm c)\nallreduce sb rb se st o c = {# call Allreduce as allreduce_ #} sb rb se st o (fromComm c)\nreduceScatter sb rb cnt t o c = {# call Reduce_scatter as reduceScatter_ #} sb rb cnt t o (fromComm c)\nopCreate = {# call unsafe Op_create as opCreate_ #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\ncommGroup = {# call unsafe Comm_group as commGroup_ #} <$> fromComm\ngroupRank = {# call unsafe Group_rank as groupRank_ #} <$> fromGroup\ngroupSize = {# call unsafe Group_size as groupSize_ #} <$> fromGroup\ngroupUnion g1 g2 = {# call unsafe Group_union as groupUnion_ #} (fromGroup g1) (fromGroup g2)\ngroupIntersection g1 g2 = {# call unsafe Group_intersection as groupIntersection_ #} (fromGroup g1) (fromGroup g2)\ngroupDifference g1 g2 = {# call unsafe Group_difference as groupDifference_ #} (fromGroup g1) (fromGroup g2)\ngroupCompare g1 g2 = {# call unsafe Group_compare as groupCompare_ #} (fromGroup g1) (fromGroup g2)\ngroupExcl g = {# call unsafe Group_excl as groupExcl_ #} (fromGroup g)\ngroupIncl g = {# call unsafe Group_incl as groupIncl_ #} (fromGroup g)\ngroupTranslateRanks g1 s r g2 = {# call unsafe Group_translate_ranks as groupTranslateRanks_ #} (fromGroup g1) s r (fromGroup g2)\ntypeSize = {# call unsafe Type_size as typeSize_ #}\nerrorClass = {# call unsafe Error_class as errorClass_ #}\nerrorString = {# call unsafe Error_string as errorString_ #}\ncommSetErrhandler = {# call unsafe Comm_set_errhandler as commSetErrhandler_ #} <$> fromComm\ncommGetErrhandler = {# call unsafe Comm_get_errhandler as commGetErrhandler_ #} <$> fromComm\nabort = {# call unsafe Abort as abort_ #} <$> fromComm\n\n\ntype Datatype = {# type MPI_Datatype #}\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr Datatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = unsafePerformIO $ peek char_\nwchar = unsafePerformIO $ peek wchar_\nshort = unsafePerformIO $ peek short_\nint = unsafePerformIO $ peek int_\nlong = unsafePerformIO $ peek long_\nlongLong = unsafePerformIO $ peek longLong_\nunsignedChar = unsafePerformIO $ peek unsignedChar_\nunsignedShort = unsafePerformIO $ peek unsignedShort_\nunsigned = unsafePerformIO $ peek unsigned_\nunsignedLong = unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = unsafePerformIO $ peek unsignedLongLong_\nfloat = unsafePerformIO $ peek float_\ndouble = unsafePerformIO $ peek double_\nlongDouble = unsafePerformIO $ peek longDouble_\nbyte = unsafePerformIO $ peek byte_\npacked = unsafePerformIO $ peek packed_\n\n\ntype Errhandler = {# type MPI_Errhandler #}\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr Errhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr Errhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = 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 #}\n\nnewtype Group = MkGroup { fromGroup :: MPIGroup }\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 Operation = {# type MPI_Op #}\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr Operation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: Operation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: Operation\n-- foreign import ccall \"mpi_replace\" replaceOp :: Operation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = unsafePerformIO $ peek maxOp_\nminOp = unsafePerformIO $ peek minOp_\nsumOp = unsafePerformIO $ peek sumOp_\nprodOp = unsafePerformIO $ peek prodOp_\nlandOp = unsafePerformIO $ peek landOp_\nbandOp = unsafePerformIO $ peek bandOp_\nlorOp = unsafePerformIO $ peek lorOp_\nborOp = unsafePerformIO $ peek borOp_\nlxorOp = unsafePerformIO $ peek lxorOp_\nbxorOp = unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\n-- TODO: actually, this should be 32-bit int\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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 Request = {# type MPI_Request #}\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\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#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\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\n-- TODO: actually, this is a 32-bit int, and even less than that.\n-- See section 8 of MPI report about extracting MPI_TAG_UB\n-- and using it here\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7f6e5dee510a9cd7013845614b471beb7a43a5e5","subject":"add compute-compatibility 5.2","message":"add compute-compatibility 5.2\n\nFixes #27\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 2 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Jetson TK1 (speculative)\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n Compute 5 2 -> DeviceResources 32 2048 32 64 128 98304 256 65536 256 4 255 Warp -- Maxwell GM20x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: Unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 2 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Jetson TK1 (speculative)\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: Unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c0e5d88819d59d7112a0f8ec54a9f762cac54438","subject":"Rename...generally, 1 represents true. puz_cksums_check returns the number of errors that occurred, not a boolean.","message":"Rename...generally, 1 represents true. puz_cksums_check returns the number of errors that occurred, not a boolean.\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\ncintToBool :: CInt -> Bool\ncintToBool = (0 ==)\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' cintToBool\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":"3ab2b628cbc0a870b35df996b509b704c0baf12c","subject":"Correct matrix inversion.","message":"Correct matrix inversion.\n\nCalculating the determinant was incorrect. Pointed out by\nMaur\u00edcio .\n\n","repos":"vincenthz\/webkit","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"5c4144ee1c5385063411312c0a05d25534cce443","subject":"gio: S.G.File: specify module exports","message":"gio: S.G.File: specify module exports\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"453cc4bcc0db96c6f752318ffd3401f19e663808","subject":"Use 'SourceMarkClass mark => mark' replace SourceBuffer as function argument.","message":"Use 'SourceMarkClass mark => mark' replace SourceBuffer as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n SourceMarkClass,\n\n-- * Methods\n castToSourceMark,\n sourceMarkNew,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev,\n\n-- * Attributes\n sourceMarkCategory\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Creates a text mark. Add it to a buffer using 'textBufferAddMark'. If name is 'Nothing', the mark\n-- is anonymous; otherwise, the mark can be retrieved by name using\n-- 'textBufferGetMark'. Normally marks are created using the utility function\n-- 'sourceBufferCreateMark'.\nsourceMarkNew :: Maybe String -- ^ @name@ Name of the 'SourceMark', can be 'Nothing' when not using a name\n -> String -- ^ @category@ is used to classify marks according to common characteristics (e.g. all the marks representing a bookmark could \n -> IO SourceMark\nsourceMarkNew name category = \n makeNewGObject mkSourceMark $\n maybeWith withUTFString name $ \\namePtr ->\n withUTFString category $ \\categoryPtr ->\n {#call gtk_source_mark_new#}\n namePtr\n categoryPtr\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMarkClass mark => mark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} (toSourceMark mark)\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMarkClass mark => mark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_next#} (toSourceMark mark)\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMarkClass mark => mark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_prev#} (toSourceMark mark)\n\n-- | The category of the 'SourceMark', classifies the mark and controls which pixbuf is used and with\n-- which priority it is drawn.\n-- Default value: \\\"\\\"\n--\nsourceMarkCategory :: SourceMarkClass mark => Attr mark String\nsourceMarkCategory = newAttrFromStringProperty \"category\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n\n-- * Methods\n castToSourceMark,\n sourceMarkNew,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev,\n\n-- * Attributes\n sourceMarkCategory\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Creates a text mark. Add it to a buffer using 'textBufferAddMark'. If name is 'Nothing', the mark\n-- is anonymous; otherwise, the mark can be retrieved by name using\n-- 'textBufferGetMark'. Normally marks are created using the utility function\n-- 'sourceBufferCreateMark'.\nsourceMarkNew :: Maybe String -- ^ @name@ Name of the 'SourceMark', can be 'Nothing' when not using a name\n -> String -- ^ @category@ is used to classify marks according to common characteristics (e.g. all the marks representing a bookmark could \n -> IO SourceMark\nsourceMarkNew name category = \n makeNewGObject mkSourceMark $\n maybeWith withUTFString name $ \\namePtr ->\n withUTFString category $ \\categoryPtr ->\n {#call gtk_source_mark_new#}\n namePtr\n categoryPtr\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n-- | The category of the 'SourceMark', classifies the mark and controls which pixbuf is used and with\n-- which priority it is drawn.\n-- Default value: \\\"\\\"\n--\nsourceMarkCategory :: Attr SourceMark String\nsourceMarkCategory = newAttrFromStringProperty \"category\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"cacdd5d80409e580f60ac4e9a114b3c361cd7b00","subject":"Must not use _static version of pango_font_description_set_family Since the string buffer is only kept around temporarily, not forever like pango_font_description_set_family_static requires.","message":"Must not use _static version of pango_font_description_set_family\nSince the string buffer is only kept around temporarily, not forever like\npango_font_description_set_family_static requires.\n","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family_static#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"77907e85b2ef18f5acc87217a620d34261004a10","subject":"[project @ 2002-07-17 16:02:09 by juhp]","message":"[project @ 2002-07-17 16:02:09 by juhp]\n\n(scrolledWindowNew): Make it maybe take Adjustments, passing\na null ptr when Nothing is given.\n\ndarcs-hash:20020717160209-f332a-688ea27842d8a650cae3df7245a8f9e508f4486a.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"3e4196349e6db0870e2d3fafac92725ec3787c05","subject":"gio: S.G.File: only export File(..) and FileClass(..), not all of module S.G.Types","message":"gio: S.G.File: only export File(..) and FileClass(..), not all of module S.G.Types","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-- \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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"974c1b6d1f849a9ffffaf8c8bc9c894ddc30a121","subject":"Fix IconTheme to only compile if gio is present.","message":"Fix IconTheme to only compile if gio is present.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items, such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0) && HAVE_GIO\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0) && HAVE_GIO\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"73f23981c10b23a04659a358c651b54fcdb52fb8","subject":"Pull result from an either or throw an error","message":"Pull result from an either or throw an error\n\nIgnore-this: f9596bcd7c841b28db9f08656b85aa09\n\ndarcs-hash:20090720021758-115f9-f5db7a4bcd2edafb9d1f1b4d994cd6348b12de98.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Utils.chs","new_file":"Foreign\/CUDA\/Utils.chs","new_contents":"{-\n - Utilities\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Utils\n (\n getErrorString,\n resultIfOk, nothingIfOk,\n forceEither\n )\n where\n\nimport Foreign.CUDA.Types\nimport Foreign.CUDA.Internal.C2HS\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Error Handling\n--------------------------------------------------------------------------------\n\n--\n-- Return the descriptive string associated with a particular error code.\n-- Logically, this must a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n{# fun pure unsafe GetErrorString as ^\n { cFromEnum `Status' } -> `String' #}\n\n\nresultIfOk :: (Status, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (getErrorString status)\n\nnothingIfOk :: Status -> Maybe String\nnothingIfOk = nothingIf (== Success) getErrorString\n\nforceEither :: Either String a -> a\nforceEither (Left s) = error s\nforceEither (Right r) = r\n\n","old_contents":"{-\n - Utilities\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Utils\n (\n getErrorString, resultIfOk, nothingIfOk\n )\n where\n\nimport Foreign.CUDA.Types\n\nimport Foreign.CUDA.Internal.C2HS\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Error Handling\n--------------------------------------------------------------------------------\n\n--\n-- Return the descriptive string associated with a particular error code.\n-- Logically, this must a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n{# fun pure unsafe GetErrorString as ^\n { cFromEnum `Status' } -> `String' #}\n\n\nresultIfOk :: (Status, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (getErrorString status)\n\nnothingIfOk :: Status -> Maybe String\nnothingIfOk = nothingIf (== Success) getErrorString\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"295b273eef98c7d6d561e31090f77d9b779d5d1b","subject":"fixes for 7.8.4","message":"fixes for 7.8.4\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/GCP.chs","new_file":"src\/GDAL\/Internal\/GCP.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule GDAL.Internal.GCP (\n GroundControlPoint (..)\n , GroundControlPointPtr\n , withGCPArrayLen\n , fromGCPArray\n , gcp\n) where\n\n#include \"gdal.h\"\n\nimport Data.ByteString.Char8 (empty, packCString)\nimport Data.ByteString.Internal (ByteString(..))\nimport Data.ByteString.Unsafe (unsafeUseAsCStringLen)\nimport Data.Coerce (coerce)\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception (bracket)\nimport Control.Monad (liftM, mapM_)\n\nimport Foreign.Marshal.Alloc (free)\nimport Foreign.Marshal.Array (mallocArray0, allocaArray, peekArray, copyArray)\nimport Foreign.C.Types (CChar(..), CDouble(..))\nimport Foreign.Ptr (Ptr, castPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\n\nimport GDAL.Internal.Types (XY(..))\n\ntype GroundControlPointPtr = Ptr GroundControlPoint\n{#pointer *GDAL_GCP as GroundControlPointPtr nocode#}\n\ndata GroundControlPoint =\n GCP {\n gcpId :: ByteString\n , gcpInfo :: ByteString\n , gcpPixel :: !(XY Double)\n , gcpPoint :: !(XY Double)\n , gcpElev :: !Double\n } deriving (Eq, Show)\n\n-- So the unsafe Storable instance doesn't escape the module\nnewtype GroundControlPointInternal = GCPI GroundControlPoint\n\ngcp :: ByteString -> XY Double -> XY Double -> GroundControlPoint\ngcp id_ px pt = GCP id_ empty px pt 0\n\nwithGCPArrayLen\n :: [GroundControlPoint] -> (Int -> GroundControlPointPtr -> IO a) -> IO a\nwithGCPArrayLen gcps act =\n allocaArray nPoints $ \\pPoints ->\n bracket (mapM_ (uncurry (pokeElemOff pPoints)) (zip [0..] gcps'))\n (const (mapM_ (freeGCP . plusPtr pPoints) [0..nPoints-1]))\n (const (act nPoints (castPtr pPoints)))\n where\n freeGCP p = do\n {#get GDAL_GCP->pszId#} p >>= free\n {#get GDAL_GCP->pszInfo#} p >>= free\n nPoints = length gcps\n gcps' = coerce gcps :: [GroundControlPointInternal]\n\nfromGCPArray :: Int -> GroundControlPointPtr -> IO [GroundControlPoint]\nfromGCPArray i p = liftM coerce (peekArray i p')\n where p' = castPtr p :: Ptr GroundControlPointInternal\n\n\ninstance Storable GroundControlPointInternal where\n sizeOf _ = {#sizeof GDAL_GCP#}\n alignment _ = {#alignof GDAL_GCP#}\n poke p (GCPI GCP{..}) = do\n unsafeUseAsCStringLen gcpId $ \\(pId,len) -> do\n ptr0 <- mallocArray0 len\n pokeElemOff ptr0 len 0\n copyArray ptr0 pId len\n {#set GDAL_GCP->pszId#} p ptr0\n unsafeUseAsCStringLen gcpInfo $ \\(pInfo,len) -> do\n ptr0 <- mallocArray0 len\n pokeElemOff ptr0 len 0\n copyArray ptr0 pInfo len\n {#set GDAL_GCP->pszInfo#} p ptr0\n {#set GDAL_GCP->dfGCPPixel#} p (realToFrac (px gcpPixel))\n {#set GDAL_GCP->dfGCPLine#} p (realToFrac (py gcpPixel))\n {#set GDAL_GCP->dfGCPX#} p (realToFrac (px gcpPoint))\n {#set GDAL_GCP->dfGCPY#} p (realToFrac (py gcpPoint))\n {#set GDAL_GCP->dfGCPZ#} p (realToFrac gcpElev)\n peek p = liftM GCPI $\n GCP <$> ({#get GDAL_GCP->pszId#} p >>= packCString)\n <*> ({#get GDAL_GCP->pszInfo#} p >>= packCString)\n <*> (XY <$> liftM realToFrac ({#get GDAL_GCP->dfGCPPixel#} p)\n <*> liftM realToFrac ({#get GDAL_GCP->dfGCPLine#} p))\n <*> (XY <$> liftM realToFrac ({#get GDAL_GCP->dfGCPX#} p)\n <*> liftM realToFrac ({#get GDAL_GCP->dfGCPY#} p))\n <*> liftM realToFrac ({#get GDAL_GCP->dfGCPZ#} p)\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule GDAL.Internal.GCP (\n GroundControlPoint (..)\n , GroundControlPointPtr\n , withGCPArrayLen\n , fromGCPArray\n , gcp\n) where\n\n#include \"gdal.h\"\n\nimport Data.ByteString.Char8 (empty, packCString)\nimport Data.ByteString.Internal (ByteString(..))\nimport Data.ByteString.Unsafe (unsafeUseAsCStringLen)\nimport Data.Coerce (coerce)\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception (bracket)\nimport Control.Monad (liftM, mapM_)\n\nimport Foreign.Marshal.Alloc (free)\nimport Foreign.Marshal.Array (callocArray0, allocaArray, peekArray, copyArray)\nimport Foreign.C.Types (CChar(..), CDouble(..))\nimport Foreign.Ptr (Ptr, castPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\n\nimport GDAL.Internal.Types (XY(..))\n\ntype GroundControlPointPtr = Ptr GroundControlPoint\n{#pointer *GDAL_GCP as GroundControlPointPtr nocode#}\n\ndata GroundControlPoint =\n GCP {\n gcpId :: ByteString\n , gcpInfo :: ByteString\n , gcpPixel :: !(XY Double)\n , gcpPoint :: !(XY Double)\n , gcpElev :: !Double\n } deriving (Eq, Show)\n\n-- So the unsafe Storable instance doesn't escape the module\nnewtype GroundControlPointInternal = GCPI GroundControlPoint\n\ngcp :: ByteString -> XY Double -> XY Double -> GroundControlPoint\ngcp id_ px pt = GCP id_ empty px pt 0\n\nwithGCPArrayLen\n :: [GroundControlPoint] -> (Int -> GroundControlPointPtr -> IO a) -> IO a\nwithGCPArrayLen gcps act =\n allocaArray nPoints $ \\pPoints ->\n bracket (mapM_ (uncurry (pokeElemOff pPoints)) (zip [0..] gcps'))\n (const (mapM_ (freeGCP . plusPtr pPoints) [0..nPoints-1]))\n (const (act nPoints (castPtr pPoints)))\n where\n freeGCP p = do\n {#get GDAL_GCP->pszId#} p >>= free\n {#get GDAL_GCP->pszInfo#} p >>= free\n nPoints = length gcps\n gcps' = coerce gcps :: [GroundControlPointInternal]\n\nfromGCPArray :: Int -> GroundControlPointPtr -> IO [GroundControlPoint]\nfromGCPArray i p = liftM coerce (peekArray i p')\n where p' = castPtr p :: Ptr GroundControlPointInternal\n\n\ninstance Storable GroundControlPointInternal where\n sizeOf _ = {#sizeof GDAL_GCP#}\n alignment _ = {#alignof GDAL_GCP#}\n poke p (GCPI GCP{..}) = do\n unsafeUseAsCStringLen gcpId $ \\(pId,len) -> do\n ptr0 <- callocArray0 len\n copyArray ptr0 pId len\n {#set GDAL_GCP->pszId#} p ptr0\n unsafeUseAsCStringLen gcpInfo $ \\(pInfo,len) -> do\n ptr0 <- callocArray0 len\n copyArray ptr0 pInfo len\n {#set GDAL_GCP->pszInfo#} p ptr0\n {#set GDAL_GCP->dfGCPPixel#} p (realToFrac (px gcpPixel))\n {#set GDAL_GCP->dfGCPLine#} p (realToFrac (py gcpPixel))\n {#set GDAL_GCP->dfGCPX#} p (realToFrac (px gcpPoint))\n {#set GDAL_GCP->dfGCPY#} p (realToFrac (py gcpPoint))\n {#set GDAL_GCP->dfGCPZ#} p (realToFrac gcpElev)\n peek p = liftM GCPI $\n GCP <$> ({#get GDAL_GCP->pszId#} p >>= packCString)\n <*> ({#get GDAL_GCP->pszInfo#} p >>= packCString)\n <*> (XY <$> liftM realToFrac ({#get GDAL_GCP->dfGCPPixel#} p)\n <*> liftM realToFrac ({#get GDAL_GCP->dfGCPLine#} p))\n <*> (XY <$> liftM realToFrac ({#get GDAL_GCP->dfGCPX#} p)\n <*> liftM realToFrac ({#get GDAL_GCP->dfGCPY#} p))\n <*> liftM realToFrac ({#get GDAL_GCP->dfGCPZ#} p)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c89737567010f192495b40b84fccc8e952942bfc","subject":"remove unnecessary Types.chs from git repo","message":"remove unnecessary Types.chs from git repo\n","repos":"gtk2hs\/poppler,wavewave\/poppler","old_file":"Graphics\/UI\/Gtk\/Poppler\/Types.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Types.chs","new_contents":"","old_contents":"{-# OPTIONS_HADDOCK hide #-}\n{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- -------------------- automatically generated file - do not edit ----------\n-- Object hierarchy for the GIMP Toolkit (GTK) Binding for Haskell\n--\n-- Author : Axel Simon\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This file reflects the Gtk+ object hierarchy in terms of Haskell classes.\n--\n-- Note: the mk... functions were originally meant to simply be an alias\n-- for the constructor. However, in order to communicate the destructor\n-- of an object to objectNew, the mk... functions are now a tuple containing\n-- Haskell constructor and the destructor function pointer. This hack avoids\n-- changing all modules that simply pass mk... to objectNew.\n--\nmodule Graphics.UI.Gtk.Poppler.Types (\n\n Document(Document), DocumentClass,\n toDocument, \n mkDocument, unDocument,\n castToDocument, gTypeDocument,\n FontsIter(FontsIter), FontsIterClass,\n toFontsIter, \n mkFontsIter, unFontsIter,\n castToFontsIter, gTypeFontsIter,\n Page(Page), PageClass,\n toPage, \n mkPage, unPage,\n castToPage, gTypePage,\n FormField(FormField), FormFieldClass,\n toFormField, \n mkFormField, unFormField,\n castToFormField, gTypeFormField,\n PSFile(PSFile), PSFileClass,\n toPSFile, \n mkPSFile, unPSFile,\n castToPSFile, gTypePSFile,\n FontInfo(FontInfo), FontInfoClass,\n toFontInfo, \n mkFontInfo, unFontInfo,\n castToFontInfo, gTypeFontInfo,\n Attachment(Attachment), AttachmentClass,\n toAttachment, \n mkAttachment, unAttachment,\n castToAttachment, gTypeAttachment,\n Layer(Layer), LayerClass,\n toLayer, \n mkLayer, unLayer,\n castToLayer, gTypeLayer\n ) where\n\nimport Foreign.ForeignPtr (ForeignPtr, castForeignPtr, unsafeForeignPtrToPtr)\nimport Foreign.C.Types (CULong(..), CUInt(..))\nimport System.Glib.GType (GType, typeInstanceIsA)\nimport System.Glib.GObject\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\n--\ncastTo :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\ncastTo gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n\n-- ******************************************************************* Document\n\n{#pointer *Document foreign newtype #} deriving (Eq,Ord)\n\nmkDocument = (Document, objectUnref)\nunDocument (Document o) = o\n\nclass GObjectClass o => DocumentClass o\ntoDocument :: DocumentClass o => o -> Document\ntoDocument = unsafeCastGObject . toGObject\n\ninstance DocumentClass Document\ninstance GObjectClass Document where\n toGObject = GObject . castForeignPtr . unDocument\n unsafeCastGObject = Document . castForeignPtr . unGObject\n\ncastToDocument :: GObjectClass obj => obj -> Document\ncastToDocument = castTo gTypeDocument \"Document\"\n\ngTypeDocument :: GType\ngTypeDocument =\n {# call fun unsafe poppler_document_get_type #}\n\n-- ****************************************************************** FontsIter\n\n{#pointer *FontsIter foreign newtype #} deriving (Eq,Ord)\n\nmkFontsIter = (FontsIter, objectUnref)\nunFontsIter (FontsIter o) = o\n\nclass GObjectClass o => FontsIterClass o\ntoFontsIter :: FontsIterClass o => o -> FontsIter\ntoFontsIter = unsafeCastGObject . toGObject\n\ninstance FontsIterClass FontsIter\ninstance GObjectClass FontsIter where\n toGObject = GObject . castForeignPtr . unFontsIter\n unsafeCastGObject = FontsIter . castForeignPtr . unGObject\n\ncastToFontsIter :: GObjectClass obj => obj -> FontsIter\ncastToFontsIter = castTo gTypeFontsIter \"FontsIter\"\n\ngTypeFontsIter :: GType\ngTypeFontsIter =\n {# call fun unsafe poppler_fonts_iter_get_type #}\n\n-- *********************************************************************** Page\n\n{#pointer *Page foreign newtype #} deriving (Eq,Ord)\n\nmkPage = (Page, objectUnref)\nunPage (Page o) = o\n\nclass GObjectClass o => PageClass o\ntoPage :: PageClass o => o -> Page\ntoPage = unsafeCastGObject . toGObject\n\ninstance PageClass Page\ninstance GObjectClass Page where\n toGObject = GObject . castForeignPtr . unPage\n unsafeCastGObject = Page . castForeignPtr . unGObject\n\ncastToPage :: GObjectClass obj => obj -> Page\ncastToPage = castTo gTypePage \"Page\"\n\ngTypePage :: GType\ngTypePage =\n {# call fun unsafe poppler_page_get_type #}\n\n-- ****************************************************************** FormField\n\n{#pointer *FormField foreign newtype #} deriving (Eq,Ord)\n\nmkFormField = (FormField, objectUnref)\nunFormField (FormField o) = o\n\nclass GObjectClass o => FormFieldClass o\ntoFormField :: FormFieldClass o => o -> FormField\ntoFormField = unsafeCastGObject . toGObject\n\ninstance FormFieldClass FormField\ninstance GObjectClass FormField where\n toGObject = GObject . castForeignPtr . unFormField\n unsafeCastGObject = FormField . castForeignPtr . unGObject\n\ncastToFormField :: GObjectClass obj => obj -> FormField\ncastToFormField = castTo gTypeFormField \"FormField\"\n\ngTypeFormField :: GType\ngTypeFormField =\n {# call fun unsafe poppler_form_field_get_type #}\n\n-- ********************************************************************* PSFile\n\n{#pointer *PSFile foreign newtype #} deriving (Eq,Ord)\n\nmkPSFile = (PSFile, objectUnref)\nunPSFile (PSFile o) = o\n\nclass GObjectClass o => PSFileClass o\ntoPSFile :: PSFileClass o => o -> PSFile\ntoPSFile = unsafeCastGObject . toGObject\n\ninstance PSFileClass PSFile\ninstance GObjectClass PSFile where\n toGObject = GObject . castForeignPtr . unPSFile\n unsafeCastGObject = PSFile . castForeignPtr . unGObject\n\ncastToPSFile :: GObjectClass obj => obj -> PSFile\ncastToPSFile = castTo gTypePSFile \"PSFile\"\n\ngTypePSFile :: GType\ngTypePSFile =\n {# call fun unsafe poppler_ps_file_get_type #}\n\n-- ******************************************************************* FontInfo\n\n{#pointer *FontInfo foreign newtype #} deriving (Eq,Ord)\n\nmkFontInfo = (FontInfo, objectUnref)\nunFontInfo (FontInfo o) = o\n\nclass GObjectClass o => FontInfoClass o\ntoFontInfo :: FontInfoClass o => o -> FontInfo\ntoFontInfo = unsafeCastGObject . toGObject\n\ninstance FontInfoClass FontInfo\ninstance GObjectClass FontInfo where\n toGObject = GObject . castForeignPtr . unFontInfo\n unsafeCastGObject = FontInfo . castForeignPtr . unGObject\n\ncastToFontInfo :: GObjectClass obj => obj -> FontInfo\ncastToFontInfo = castTo gTypeFontInfo \"FontInfo\"\n\ngTypeFontInfo :: GType\ngTypeFontInfo =\n {# call fun unsafe poppler_font_info_get_type #}\n\n-- ***************************************************************** Attachment\n\n{#pointer *Attachment foreign newtype #} deriving (Eq,Ord)\n\nmkAttachment = (Attachment, objectUnref)\nunAttachment (Attachment o) = o\n\nclass GObjectClass o => AttachmentClass o\ntoAttachment :: AttachmentClass o => o -> Attachment\ntoAttachment = unsafeCastGObject . toGObject\n\ninstance AttachmentClass Attachment\ninstance GObjectClass Attachment where\n toGObject = GObject . castForeignPtr . unAttachment\n unsafeCastGObject = Attachment . castForeignPtr . unGObject\n\ncastToAttachment :: GObjectClass obj => obj -> Attachment\ncastToAttachment = castTo gTypeAttachment \"Attachment\"\n\ngTypeAttachment :: GType\ngTypeAttachment =\n {# call fun unsafe poppler_attachment_get_type #}\n\n-- ********************************************************************** Layer\n\n{#pointer *Layer foreign newtype #} deriving (Eq,Ord)\n\nmkLayer = (Layer, objectUnref)\nunLayer (Layer o) = o\n\nclass GObjectClass o => LayerClass o\ntoLayer :: LayerClass o => o -> Layer\ntoLayer = unsafeCastGObject . toGObject\n\ninstance LayerClass Layer\ninstance GObjectClass Layer where\n toGObject = GObject . castForeignPtr . unLayer\n unsafeCastGObject = Layer . castForeignPtr . unGObject\n\ncastToLayer :: GObjectClass obj => obj -> Layer\ncastToLayer = castTo gTypeLayer \"Layer\"\n\ngTypeLayer :: GType\ngTypeLayer =\n {# call fun unsafe poppler_layer_get_type #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"ab097875defbf49a3188f67454d48a2f1790bae3","subject":"more local allocation functions","message":"more local allocation functions\n\nIgnore-this: 8fb7875adc5dba47ccdad01431c7fa2d\n\ndarcs-hash:20090724060859-115f9-27c06f521ccd71683556163754b931ed2ca2d15d.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 free,\n malloc,\n-- malloc2D,\n-- malloc3D,\n memset,\n-- memset2D,\n-- memset3D,\n\n -- ** Local allocation\n alloca,\n allocaBytes,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n withArrayLen,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr hiding (newForeignPtr)\nimport Foreign.Concurrent (newForeignPtr)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = newForeignPtr p (free_ p)\n--newDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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) => a -> (DevicePtr a -> IO b) -> IO b\nalloca = allocaBytes . fromIntegral . F.sizeOf\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 fun =\n forceEither `fmap` malloc bytes >>= \\dptr ->\n fun dptr >>= return\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\n\n\nwithArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithArrayLen vals fun =\n let len = length vals\n bytes = fromIntegral len * fromIntegral (F.sizeOf (head vals))\n in do\n dptr <- forceEither `fmap` malloc bytes\n pokeArray dptr vals\n fun len dptr\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 free,\n malloc,\n-- malloc2D,\n-- malloc3D,\n memset,\n-- memset2D,\n-- memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr hiding (newForeignPtr)\nimport Foreign.Concurrent (newForeignPtr)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = newForeignPtr p (free_ p)\n--newDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\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":"6bd7613690c6be89bacacab3c2fa80a4575096a5","subject":"reorder attribute types to match order in pkcs11 header file","message":"reorder attribute types to match order in pkcs11 header file\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 getModulus,\n getPublicExponent,\n getDecryptFlag,\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_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\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\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\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 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_LABEL as LabelType,\n CKA_KEY_TYPE as KeyTypeType,\n CKA_DECRYPT as DecryptType,\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 } deriving (Show, Eq) #}\n\ndata Attribute = Class ClassType\n | KeyType KeyTypeValue\n | Label String\n | ModulusBits Int\n | Token Bool\n | Decrypt 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\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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\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","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 getModulus,\n getPublicExponent,\n getDecryptFlag,\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_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\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\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\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 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_KEY_TYPE as KeyTypeType,\n CKA_LABEL as LabelType,\n CKA_MODULUS_BITS as ModulusBitsType,\n CKA_MODULUS as ModulusType,\n CKA_PUBLIC_EXPONENT as PublicExponentType,\n CKA_PRIVATE_EXPONENT as PrivateExponentType,\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 CKA_TOKEN as TokenType,\n CKA_DECRYPT as DecryptType\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 | 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\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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\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":"dad1a622632d8b15b65926f323da586b3e01e3a6","subject":"Restore constant exprs, catch exceptions thrown in the knot tying process and turn them to Either at the interface boundary","message":"Restore constant exprs, catch exceptions thrown in the knot tying process and turn them to Either at the interface boundary\n","repos":"travitch\/llvm-analysis,wangxiayang\/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 ( 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 )\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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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 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 = 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' } -> `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 , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n , result = Nothing\n , visitedTypes = S.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\nparseLLVMBitcodeFile :: ParserOptions -> FilePath -> IO (Either String Module)\nparseLLVMBitcodeFile _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 ref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState ref)\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 put s { typeMap = M.insert ip t (typeMap s) }\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 (_, TYPE_NAMED) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\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 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\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 ( parseLLVMBitcodeFile ) 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 Data.Set ( Set )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Maybe ( catMaybes )\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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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 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 = 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' } -> `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 , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n , result = Nothing\n , visitedTypes = S.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\nparseLLVMBitcodeFile :: ParserOptions -> FilePath -> IO (Either String Module)\nparseLLVMBitcodeFile _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 -> do\n ref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState ref)\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 put s { typeMap = M.insert ip t (typeMap s) }\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 (_, TYPE_NAMED) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\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 -> return UnwindInst -- 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 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\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":"6dd8256413140029ad2a5992e8c1bb9e6725fee0","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\/gtksourceview,gtk2hs\/gtksourceview","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":"ea3dddadfc1d848da3d916dedce0b6edf88072da","subject":"Fix redundant imports for -wall, -werror build.","message":"Fix redundant imports for -wall, -werror build.\n\nBuilds clean with \"debug\" flag.\n\nSigned-off-by: Aaron Friel \n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Ffi\/Client.chs","new_file":"src\/Database\/HyperDex\/Internal\/Ffi\/Client.chs","new_contents":"{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n-- |\n-- Module : Database.HyperDex.Internal.Ffi.Client\n-- Copyright : (c) Aaron Friel 2013-2014\n-- (c) Niklas Hamb\u00fcchen 2013-2014 \n-- License : BSD-style\n-- Maintainer : mayreply@aaronfriel.com\n-- Stability : unstable\n-- Portability : portable\n--\nmodule Database.HyperDex.Internal.Ffi.Client\n ( -- Simple, single-key operations\n get\n , put\n , putIfNotExist\n , delete\n , putConditional\n -- Atomic numeric operations\n , atomicAdd, atomicSub\n , atomicMul, atomicDiv\n -- Atomic integral operations\n , atomicMod\n , atomicAnd, atomicOr\n , atomicXor\n -- Atomic string operations\n , stringPrepend, stringAppend\n , listLPush, listRPush\n , setAdd, setRemove\n , setUnion, setIntersect\n -- Atomic simple map operations\n , mapAdd, mapRemove\n -- , atomicConditionalMapInsert\n -- Atomic numeric value operations\n , mapAtomicAdd, mapAtomicSub\n , mapAtomicMul, mapAtomicDiv\n -- Atomic integral value operations\n , mapAtomicMod\n , mapAtomicAnd, mapAtomicOr\n , mapAtomicXor\n -- Atomic string value operations\n , mapStringPrepend\n , mapStringAppend\n -- Search operations\n , search\n , describeSearch\n , deleteGroup\n , count\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Data.ByteString (ByteString, packCString)\n\nimport Control.Monad.IO.Class\n\n#include \"hyperdex\/client.h\"\n\n{# import Database.HyperDex.Internal.Client #}\n{# import Database.HyperDex.Internal.Data.Attribute #}\n{# import Database.HyperDex.Internal.Data.AttributeCheck #}\n{# import Database.HyperDex.Internal.Data.MapAttribute #}\nimport Database.HyperDex.Internal.Core\nimport Database.HyperDex.Internal.Handle (wrapHyperCallHandle)\nimport Database.HyperDex.Internal.Util\nimport Database.HyperDex.Internal.Util.Resource\n\ntype ClientCall = Client\n -> CString \n -> CString -> CULong\n -> Ptr Attribute -> CULong\n -> Ptr CInt\n -> IO CLong\n\ntype MapCall = Client\n -> CString \n -> CString -> CULong\n -> Ptr MapAttribute -> CULong\n -> Ptr CInt\n -> IO CLong\n\nput = hyperdexClientOp {# call hyperdex_client_put #}\nputIfNotExist = hyperdexClientOp {# call hyperdex_client_put_if_not_exist #}\natomicAdd = hyperdexClientOp {# call hyperdex_client_atomic_add #}\natomicSub = hyperdexClientOp {# call hyperdex_client_atomic_sub #}\natomicMul = hyperdexClientOp {# call hyperdex_client_atomic_mul #}\natomicDiv = hyperdexClientOp {# call hyperdex_client_atomic_div #}\natomicMod = hyperdexClientOp {# call hyperdex_client_atomic_mod #}\natomicAnd = hyperdexClientOp {# call hyperdex_client_atomic_and #}\natomicOr = hyperdexClientOp {# call hyperdex_client_atomic_or #}\natomicXor = hyperdexClientOp {# call hyperdex_client_atomic_xor #}\nstringPrepend = hyperdexClientOp {# call hyperdex_client_string_prepend #}\nstringAppend = hyperdexClientOp {# call hyperdex_client_string_append #}\nlistLPush = hyperdexClientOp {# call hyperdex_client_list_lpush #}\nlistRPush = hyperdexClientOp {# call hyperdex_client_list_rpush #}\nsetAdd = hyperdexClientOp {# call hyperdex_client_set_add #}\nsetRemove = hyperdexClientOp {# call hyperdex_client_set_remove #}\nsetIntersect = hyperdexClientOp {# call hyperdex_client_set_intersect #}\nsetUnion = hyperdexClientOp {# call hyperdex_client_set_union #}\n\n-- mapAtomicInsert = hyperdexClientMapOp {# call hyperdex_client_map_atomic_insert #}\nmapAdd = hyperdexClientMapOp {# call hyperdex_client_map_add #}\nmapRemove = hyperdexClientOp {# call hyperdex_client_map_remove #}\nmapAtomicAdd = hyperdexClientMapOp {# call hyperdex_client_map_atomic_add #}\nmapAtomicSub = hyperdexClientMapOp {# call hyperdex_client_map_atomic_sub #}\nmapAtomicMul = hyperdexClientMapOp {# call hyperdex_client_map_atomic_mul #}\nmapAtomicDiv = hyperdexClientMapOp {# call hyperdex_client_map_atomic_div #}\nmapAtomicMod = hyperdexClientMapOp {# call hyperdex_client_map_atomic_mod #}\nmapAtomicAnd = hyperdexClientMapOp {# call hyperdex_client_map_atomic_and #}\nmapAtomicOr = hyperdexClientMapOp {# call hyperdex_client_map_atomic_or #}\nmapAtomicXor = hyperdexClientMapOp {# call hyperdex_client_map_atomic_xor #}\nmapStringPrepend = hyperdexClientMapOp {# call hyperdex_client_map_string_prepend #}\nmapStringAppend = hyperdexClientMapOp {# call hyperdex_client_map_string_append #}\n\n-- mapAtomicInsert = hyperdexClientMapOp OpAtomicMapInsert\n-- mapAtomicAdd = hyperdexClientMapOp OpAtomicMapAdd\n-- mapAtomicSub = hyperdexClientMapOp OpAtomicMapSub\n-- mapAtomicMul = hyperdexClientMapOp OpAtomicMapMul\n-- mapAtomicDiv = hyperdexClientMapOp OpAtomicMapDiv\n-- mapAtomicMod = hyperdexClientMapOp OpAtomicMapMod\n-- mapAtomicAnd = hyperdexClientMapOp OpAtomicMapAnd\n-- mapAtomicOr = hyperdexClientMapOp OpAtomicMapOr\n-- mapAtomicXor = hyperdexClientMapOp OpAtomicMapXor\n-- mapAtomicStringPrepend = hyperdexClientMapOp OpAtomicMapStringPrepend\n-- mapAtomicStringAppend = hyperdexClientMapOp OpAtomicMapStringAppend\n\n--hyperdexClientMapOp = undefined\n--hyperdexClientOp = undefined\n--putConditional = undefined\n--search = undefined\n--describeSearch = undefined\n--deleteGroup = undefined\n--count = undefined\n\n\n-- int64_t\n-- hyperdex_client_get(struct hyperdex_client* client,\n-- const char* space,\n-- const char* key, size_t key_sz,\n-- enum hyperdex_client_returncode* status,\n-- const struct hyperdex_client_attribute** attrs, size_t* attrs_sz);\nget :: ByteString\n -> ByteString\n -> HyperDexConnection Client\n -> IO (AsyncResult Client [Attribute])\nget s k = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (attrPtrPtr, attrSzPtr, peekResult) <- rMallocAttributeArray\n let ccall ptr = do\n wrapHyperCallHandle $\n {# call hyperdex_client_get #}\n ptr\n space key (fromIntegral keySize)\n returnCodePtr attrPtrPtr attrSzPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> fmap Right peekResult\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_del(struct hyperdex_client* client,\n-- const char* space,\n-- const char* key, size_t key_sz,\n-- enum hyperdex_client_returncode* status);\ndelete :: ByteString\n -> ByteString\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\ndelete s k = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n let ccall ptr = \n wrapHyperCallHandle $\n {# call hyperdex_client_del #}\n ptr\n space key (fromIntegral keySize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_cond_put(struct hyperdexClient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- const struct hyperdex_client_attribute* attrs, size_t attrs_sz,\n-- enum hyperdex_client_returncode* status);\nputConditional :: ByteString\n -> ByteString\n -> [AttributeCheck]\n -> [Attribute]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\nputConditional s k checks attrs = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (attributePtr, attributeSize) <- rNewAttributeArray attrs\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n let ccall ptr = \n wrapHyperCallHandle $\n {# call hyperdex_client_cond_put #}\n ptr\n space key (fromIntegral keySize)\n checkPtr (fromIntegral checkSize)\n attributePtr (fromIntegral attributeSize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_atomic_xor(struct hyperdexClient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperdex_client_attribute* attrs, size_t attrs_sz,\n-- enum hyperdex_client_returncode* status);\nhyperdexClientOp :: ClientCall\n -> ByteString\n -> ByteString\n -> [Attribute]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\nhyperdexClientOp call s k attrs = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (attributePtr, attributeSize) <- rNewAttributeArray attrs\n let ccall ptr = do\n wrapHyperCallHandle $\n call\n ptr\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n{-# INLINE hyperdexClientOp #-}\n\n\n-- data MapAttribute = MapAttribute\n-- { mapAttrName :: ByteString\n-- , mapAttrKey :: ByteString\n-- , mapAttrKeyDatatype :: Hyperdatatype\n-- , mapAttrValue :: ByteString\n-- , mapAttrValueDatatype :: Hyperdatatype\n\n-- int64_t\n-- hyperdex_client_map_add(struct hyperdexClient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperdex_client_map_attribute* attrs, size_t attrs_sz,\n-- enum hyperdex_client_returncode* status);\nhyperdexClientMapOp :: MapCall\n -> ByteString\n -> ByteString\n -> [MapAttribute]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\nhyperdexClientMapOp call s k mapAttrs = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (mapAttributePtr, mapAttributeSize) <- rNewMapAttributeArray mapAttrs\n let ccall ptr = do\n wrapHyperCallHandle $\n call\n ptr space\n key (fromIntegral keySize)\n mapAttributePtr (fromIntegral mapAttributeSize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n{-# INLINE hyperdexClientMapOp #-}\n\n-- -- int64_t\n-- -- hyperdex_client_search(struct hyperdexClient* client, const char* space,\n-- -- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- -- enum hyperdex_client_returncode* status,\n-- -- struct hyperdex_client_attribute** attrs, size_t* attrs_sz);\n--search :: HyperDexConnection Client\n-- -> ByteString\n-- -> [AttributeCheck]\n-- -> IO (SearchStream [Attribute])\nsearch s checks = clientIterator $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n (resultPtrPtr, resultSizePtr, peekResult) <- rMallocAttributeArray\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_search #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n resultPtrPtr resultSizePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> fmap Right peekResult\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_group_del(struct hyperdex_client* client,\n-- const char* space,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- enum hyperdex_client_returncode* status,\n-- uint64_t* count);\ndeleteGroup :: ByteString\n -> [AttributeCheck]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client Word64)\ndeleteGroup s checks = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n countPtr <- rMalloc\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_group_del #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n countPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> liftIO $ fmap (Right . unCULong) $ peek countPtr \n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_search_describe(struct hyperdexClient* client, const char* space,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- enum hyperdex_client_returncode* status, const char** description);\ndescribeSearch :: ByteString\n -> [AttributeCheck]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ByteString)\ndescribeSearch s checks = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n descriptionPtr <- rMalloc\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_search_describe #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n descriptionPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n -- TODO: Who is responsible for freeing the description string?\n case returnCode of\n ClientSuccess -> liftIO $ do\n cStr <- peek descriptionPtr\n description <- packCString cStr\n return $ Right description\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_count(struct hyperdexClient* client, const char* space,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- enum hyperdex_client_returncode* status, uint64_t* result);\ncount :: ByteString\n -> [AttributeCheck]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client Word64)\ncount s checks = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n countPtr <- rNew 0\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_count #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n countPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n -- TODO: Who is responsible for freeing the description string?\n case returnCode of\n ClientSuccess -> liftIO $ fmap (Right . unCULong) $ peek countPtr \n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n","old_contents":"{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n-- |\n-- Module : Database.HyperDex.Internal.Ffi.Client\n-- Copyright : (c) Aaron Friel 2013-2014\n-- (c) Niklas Hamb\u00fcchen 2013-2014 \n-- License : BSD-style\n-- Maintainer : mayreply@aaronfriel.com\n-- Stability : unstable\n-- Portability : portable\n--\nmodule Database.HyperDex.Internal.Ffi.Client\n ( -- Simple, single-key operations\n get\n , put\n , putIfNotExist\n , delete\n , putConditional\n -- Atomic numeric operations\n , atomicAdd, atomicSub\n , atomicMul, atomicDiv\n -- Atomic integral operations\n , atomicMod\n , atomicAnd, atomicOr\n , atomicXor\n -- Atomic string operations\n , stringPrepend, stringAppend\n , listLPush, listRPush\n , setAdd, setRemove\n , setUnion, setIntersect\n -- Atomic simple map operations\n , mapAdd, mapRemove\n -- , atomicConditionalMapInsert\n -- Atomic numeric value operations\n , mapAtomicAdd, mapAtomicSub\n , mapAtomicMul, mapAtomicDiv\n -- Atomic integral value operations\n , mapAtomicMod\n , mapAtomicAnd, mapAtomicOr\n , mapAtomicXor\n -- Atomic string value operations\n , mapStringPrepend\n , mapStringAppend\n -- Search operations\n , search\n , describeSearch\n , deleteGroup\n , count\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Data.ByteString (ByteString, packCString)\n\nimport Control.Monad.IO.Class\n\n#include \"hyperdex\/client.h\"\n\n{# import Database.HyperDex.Internal.Client #}\n{# import Database.HyperDex.Internal.Data.Attribute #}\n{# import Database.HyperDex.Internal.Data.AttributeCheck #}\n{# import Database.HyperDex.Internal.Data.MapAttribute #}\nimport Database.HyperDex.Internal.Core\nimport Database.HyperDex.Internal.Handle (wrapHyperCallHandle)\nimport Database.HyperDex.Internal.Util\nimport Database.HyperDex.Internal.Util.Resource\nimport qualified Data.ByteString as BS\nimport Control.Monad\n\ntype ClientCall = Client\n -> CString \n -> CString -> CULong\n -> Ptr Attribute -> CULong\n -> Ptr CInt\n -> IO CLong\n\ntype MapCall = Client\n -> CString \n -> CString -> CULong\n -> Ptr MapAttribute -> CULong\n -> Ptr CInt\n -> IO CLong\n\nput = hyperdexClientOp {# call hyperdex_client_put #}\nputIfNotExist = hyperdexClientOp {# call hyperdex_client_put_if_not_exist #}\natomicAdd = hyperdexClientOp {# call hyperdex_client_atomic_add #}\natomicSub = hyperdexClientOp {# call hyperdex_client_atomic_sub #}\natomicMul = hyperdexClientOp {# call hyperdex_client_atomic_mul #}\natomicDiv = hyperdexClientOp {# call hyperdex_client_atomic_div #}\natomicMod = hyperdexClientOp {# call hyperdex_client_atomic_mod #}\natomicAnd = hyperdexClientOp {# call hyperdex_client_atomic_and #}\natomicOr = hyperdexClientOp {# call hyperdex_client_atomic_or #}\natomicXor = hyperdexClientOp {# call hyperdex_client_atomic_xor #}\nstringPrepend = hyperdexClientOp {# call hyperdex_client_string_prepend #}\nstringAppend = hyperdexClientOp {# call hyperdex_client_string_append #}\nlistLPush = hyperdexClientOp {# call hyperdex_client_list_lpush #}\nlistRPush = hyperdexClientOp {# call hyperdex_client_list_rpush #}\nsetAdd = hyperdexClientOp {# call hyperdex_client_set_add #}\nsetRemove = hyperdexClientOp {# call hyperdex_client_set_remove #}\nsetIntersect = hyperdexClientOp {# call hyperdex_client_set_intersect #}\nsetUnion = hyperdexClientOp {# call hyperdex_client_set_union #}\n\n-- mapAtomicInsert = hyperdexClientMapOp {# call hyperdex_client_map_atomic_insert #}\nmapAdd = hyperdexClientMapOp {# call hyperdex_client_map_add #}\nmapRemove = hyperdexClientOp {# call hyperdex_client_map_remove #}\nmapAtomicAdd = hyperdexClientMapOp {# call hyperdex_client_map_atomic_add #}\nmapAtomicSub = hyperdexClientMapOp {# call hyperdex_client_map_atomic_sub #}\nmapAtomicMul = hyperdexClientMapOp {# call hyperdex_client_map_atomic_mul #}\nmapAtomicDiv = hyperdexClientMapOp {# call hyperdex_client_map_atomic_div #}\nmapAtomicMod = hyperdexClientMapOp {# call hyperdex_client_map_atomic_mod #}\nmapAtomicAnd = hyperdexClientMapOp {# call hyperdex_client_map_atomic_and #}\nmapAtomicOr = hyperdexClientMapOp {# call hyperdex_client_map_atomic_or #}\nmapAtomicXor = hyperdexClientMapOp {# call hyperdex_client_map_atomic_xor #}\nmapStringPrepend = hyperdexClientMapOp {# call hyperdex_client_map_string_prepend #}\nmapStringAppend = hyperdexClientMapOp {# call hyperdex_client_map_string_append #}\n\n-- mapAtomicInsert = hyperdexClientMapOp OpAtomicMapInsert\n-- mapAtomicAdd = hyperdexClientMapOp OpAtomicMapAdd\n-- mapAtomicSub = hyperdexClientMapOp OpAtomicMapSub\n-- mapAtomicMul = hyperdexClientMapOp OpAtomicMapMul\n-- mapAtomicDiv = hyperdexClientMapOp OpAtomicMapDiv\n-- mapAtomicMod = hyperdexClientMapOp OpAtomicMapMod\n-- mapAtomicAnd = hyperdexClientMapOp OpAtomicMapAnd\n-- mapAtomicOr = hyperdexClientMapOp OpAtomicMapOr\n-- mapAtomicXor = hyperdexClientMapOp OpAtomicMapXor\n-- mapAtomicStringPrepend = hyperdexClientMapOp OpAtomicMapStringPrepend\n-- mapAtomicStringAppend = hyperdexClientMapOp OpAtomicMapStringAppend\n\n--hyperdexClientMapOp = undefined\n--hyperdexClientOp = undefined\n--putConditional = undefined\n--search = undefined\n--describeSearch = undefined\n--deleteGroup = undefined\n--count = undefined\n\n\n-- int64_t\n-- hyperdex_client_get(struct hyperdex_client* client,\n-- const char* space,\n-- const char* key, size_t key_sz,\n-- enum hyperdex_client_returncode* status,\n-- const struct hyperdex_client_attribute** attrs, size_t* attrs_sz);\nget :: ByteString\n -> ByteString\n -> HyperDexConnection Client\n -> IO (AsyncResult Client [Attribute])\nget s k = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (attrPtrPtr, attrSzPtr, peekResult) <- rMallocAttributeArray\n let ccall ptr = do\n wrapHyperCallHandle $\n {# call hyperdex_client_get #}\n ptr\n space key (fromIntegral keySize)\n returnCodePtr attrPtrPtr attrSzPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> fmap Right peekResult\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_del(struct hyperdex_client* client,\n-- const char* space,\n-- const char* key, size_t key_sz,\n-- enum hyperdex_client_returncode* status);\ndelete :: ByteString\n -> ByteString\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\ndelete s k = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n let ccall ptr = \n wrapHyperCallHandle $\n {# call hyperdex_client_del #}\n ptr\n space key (fromIntegral keySize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_cond_put(struct hyperdexClient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- const struct hyperdex_client_attribute* attrs, size_t attrs_sz,\n-- enum hyperdex_client_returncode* status);\nputConditional :: ByteString\n -> ByteString\n -> [AttributeCheck]\n -> [Attribute]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\nputConditional s k checks attrs = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (attributePtr, attributeSize) <- rNewAttributeArray attrs\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n let ccall ptr = \n wrapHyperCallHandle $\n {# call hyperdex_client_cond_put #}\n ptr\n space key (fromIntegral keySize)\n checkPtr (fromIntegral checkSize)\n attributePtr (fromIntegral attributeSize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_atomic_xor(struct hyperdexClient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperdex_client_attribute* attrs, size_t attrs_sz,\n-- enum hyperdex_client_returncode* status);\nhyperdexClientOp :: ClientCall\n -> ByteString\n -> ByteString\n -> [Attribute]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\nhyperdexClientOp call s k attrs = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (attributePtr, attributeSize) <- rNewAttributeArray attrs\n let ccall ptr = do\n wrapHyperCallHandle $\n call\n ptr\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n{-# INLINE hyperdexClientOp #-}\n\n\n-- data MapAttribute = MapAttribute\n-- { mapAttrName :: ByteString\n-- , mapAttrKey :: ByteString\n-- , mapAttrKeyDatatype :: Hyperdatatype\n-- , mapAttrValue :: ByteString\n-- , mapAttrValueDatatype :: Hyperdatatype\n\n-- int64_t\n-- hyperdex_client_map_add(struct hyperdexClient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperdex_client_map_attribute* attrs, size_t attrs_sz,\n-- enum hyperdex_client_returncode* status);\nhyperdexClientMapOp :: MapCall\n -> ByteString\n -> ByteString\n -> [MapAttribute]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ())\nhyperdexClientMapOp call s k mapAttrs = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (key,keySize) <- rNewCBStringLen k\n (mapAttributePtr, mapAttributeSize) <- rNewMapAttributeArray mapAttrs\n let ccall ptr = do\n wrapHyperCallHandle $\n call\n ptr space\n key (fromIntegral keySize)\n mapAttributePtr (fromIntegral mapAttributeSize)\n returnCodePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> return $ Right ()\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n{-# INLINE hyperdexClientMapOp #-}\n\n-- -- int64_t\n-- -- hyperdex_client_search(struct hyperdexClient* client, const char* space,\n-- -- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- -- enum hyperdex_client_returncode* status,\n-- -- struct hyperdex_client_attribute** attrs, size_t* attrs_sz);\n--search :: HyperDexConnection Client\n-- -> ByteString\n-- -> [AttributeCheck]\n-- -> IO (SearchStream [Attribute])\nsearch s checks = clientIterator $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n (resultPtrPtr, resultSizePtr, peekResult) <- rMallocAttributeArray\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_search #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n resultPtrPtr resultSizePtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> fmap Right peekResult\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_group_del(struct hyperdex_client* client,\n-- const char* space,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- enum hyperdex_client_returncode* status,\n-- uint64_t* count);\ndeleteGroup :: ByteString\n -> [AttributeCheck]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client Word64)\ndeleteGroup s checks = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n countPtr <- rMalloc\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_group_del #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n countPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n case returnCode of\n ClientSuccess -> liftIO $ fmap (Right . unCULong) $ peek countPtr \n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_search_describe(struct hyperdexClient* client, const char* space,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- enum hyperdex_client_returncode* status, const char** description);\ndescribeSearch :: ByteString\n -> [AttributeCheck]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client ByteString)\ndescribeSearch s checks = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n descriptionPtr <- rMalloc\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_search_describe #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n descriptionPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n -- TODO: Who is responsible for freeing the description string?\n case returnCode of\n ClientSuccess -> liftIO $ do\n cStr <- peek descriptionPtr\n description <- packCString cStr\n return $ Right description\n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n\n-- int64_t\n-- hyperdex_client_count(struct hyperdexClient* client, const char* space,\n-- const struct hyperdex_client_attribute_check* checks, size_t checks_sz,\n-- enum hyperdex_client_returncode* status, uint64_t* result);\ncount :: ByteString\n -> [AttributeCheck]\n -> HyperDexConnection Client\n -> IO (AsyncResult Client Word64)\ncount s checks = clientDeferred $ do\n returnCodePtr <- rNew (fromIntegral . fromEnum $ ClientGarbage)\n space <- rNewCBString0 s\n (checkPtr, checkSize) <- rNewAttributeCheckArray checks\n countPtr <- rNew 0\n let ccall ptr =\n wrapHyperCallHandle $\n {# call hyperdex_client_count #}\n ptr\n space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n countPtr\n let callback = do\n returnCode <- peekReturnCode returnCodePtr\n -- TODO: Who is responsible for freeing the description string?\n case returnCode of\n ClientSuccess -> liftIO $ fmap (Right . unCULong) $ peek countPtr \n _ -> return $ Left returnCode\n return $ AsyncCall ccall callback\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c148e47097a3d2731af6fcfadd5be55f435a7ddc","subject":"gstreamer: M.S.G.Core.Types.chs: staticPadTemplateGet: Control.Monad.>=> not available before ghc 6.8; don't export StaticPadTemplate constructors","message":"gstreamer: M.S.G.Core.Types.chs: staticPadTemplateGet: Control.Monad.>=> not available before ghc 6.8; don't export StaticPadTemplate constructors\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate {-(..)-},\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet staticPadTemplate =\n {# call static_pad_template_get #} staticPadTemplate >>= takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate(..),\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet =\n {# call static_pad_template_get #} >=> takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e8de29c369b110141c2505491b6066166f69eeef","subject":"[project @ 2002-07-17 16:07:50 by juhp] Export timeoutAdd, timeoutRemove, idleAdd, idleRemove and HandlerId.","message":"[project @ 2002-07-17 16:07:50 by juhp]\nExport timeoutAdd, timeoutRemove, idleAdd, idleRemove and HandlerId.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/gtksourceview","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 16:07:50 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:13:09 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"2091f3d2d5e8807d94014f985b8b1fbf589a0a0f","subject":"more work on the ffi stuff","message":"more work on the ffi stuff\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ntype CRSLong = CLLong\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- | The Signature type\ndata CSignature -- = CSignature { flength :: CRSLong\n -- , count :: CInt\n -- , remainder :: CInt\n -- , blockLenth :: CInt\n -- , strongSumLenght :: CInt\n -- , blockSigs :: BlockSigPtr\n -- , targets :: TargetPtr\n -- }\n -- deriving (Eq, Show)\n\n{#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The Stats type\ndata Stats\n{#pointer *rs_stats as StatsPtr -> Stats #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\n-- crsSignature :: Handle -> IO (Maybe CSignature, Result)\n-- crsSignature h = undefined\n\ntype CFilePtr = Ptr CFile\n\n-- | Loading signatures\n-- the c-function is:\n-- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n{#fun unsafe rs_loadsig_file as cRSLoadSigFile\n { id `CFilePtr'\n , alloca- `SignaturePtr' peek*\n , alloca- `StatsPtr'\n } -> `Result' cIntToEnum\n #}\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Storable\n\n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ntype CRSLong = CLLong\n\n-- | Extract the signature type\n{#pointer *rs_signature_t as Stignature #}\n\n-- | Extract the stats type\n{#pointer *rs_stats as Stats #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n\n--------------------------------------------------------------------------------\n-- | The functions\n\n\n-- | Loading signatures\n-- the c-function is:\n-- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n{#fun unsafe rs_loadsig_file as cRSLoadSigFile\n { handleToCFile* `Handle'\n , alloca- `Ptr Signature' peek*\n , alloca- `Ptr Stats' peek*\n } -> `Result' cIntToEnum\n #}\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . cIntConv\n\n-- | Convert a handle into a pointer to a CFile\n-- Code taken from http:\/\/www.pwan.org\/wp\/?p=33\nhandleToCFile :: Handle -> String -> IO (Ptr CFile)\nhandleToCFile h m =\n do iomode <- newCString m\n -- Duplicate the handle, so the original stays open\n -- after the handleToFd call closes the duplicate\n dup_h <- hDuplicate h\n fd <- handleToFd dup_h\n fdopen fd iomode\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9e5ef9f38cadcba18278324fbc7b6072fb04413f","subject":"[project @ 2003-11-11 12:07:43 by juhp] (sourceTagSetStyle): Fix docu typo.","message":"[project @ 2003-11-11 12:07:43 by juhp]\n(sourceTagSetStyle): Fix docu typo.\n","repos":"vincenthz\/webkit","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":"800eda7c4262a4002e87f1c7f42df2fc8bdf53e1","subject":"fix return type","message":"fix return type\n","repos":"adamwalker\/haskell_cudd,maweki\/haskell_cudd","old_file":"CuddC.chs","new_file":"CuddC.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, CPP #-}\n\nmodule CuddC (\n CDdManager,\n CDdNode,\n c_cuddReadOne,\n c_cuddReadLogicZero,\n c_cuddReadOneWithRef,\n c_cuddReadLogicZeroWithRef,\n c_cuddBddIthVar,\n c_cuddBddAnd,\n c_cuddBddOr,\n c_cuddBddNand,\n c_cuddBddNor,\n c_cuddBddXor,\n c_cuddBddXnor,\n c_cuddNot,\n c_cuddNotNoRef,\n c_cuddBddIte,\n c_cuddBddExistAbstract,\n c_cuddBddUnivAbstract,\n c_cuddIterDerefBdd,\n cuddRef,\n c_cuddInit,\n c_cuddShuffleHeap,\n c_cuddSetVarMap,\n c_cuddBddVarMap,\n c_cuddBddLeq,\n c_cuddBddSwapVariables,\n c_cuddLargestCube,\n c_cuddBddMakePrime,\n c_cuddSupportIndex,\n c_cuddSupportIndices,\n c_cuddIndicesToCube,\n c_cuddBddComputeCube,\n c_cuddBddToCubeArray,\n c_cuddReadSize,\n c_cuddBddCompose,\n c_cuddBddAndAbstract,\n c_cuddBddXorExistAbstract,\n c_cuddBddLeqUnless,\n c_cuddEquivDC,\n c_cuddXeqy,\n c_cuddDebugCheck,\n c_cuddCheckKeys,\n c_cuddBddPickOneMinterm,\n c_cuddCheckZeroRef,\n c_cuddReadInvPerm,\n c_cuddReadPerm,\n c_cuddDagSize,\n c_cuddReadNodeCount,\n c_cuddReadPeakNodeCount,\n c_cuddReadMaxCache,\n c_cuddReadMaxCacheHard,\n c_cuddSetMaxCacheHard,\n c_cuddReadCacheSlots,\n c_cuddReadCacheUsedSlots,\n c_cuddBddAndLimit,\n c_cuddBddNewVarAtLevel,\n c_cuddReadTree\n ) where\n\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C.Types\n\nimport MTR\n\ndata CDdManager\ndata CDdNode = CDdNode {index :: CInt, ref :: CInt}\n\n{-\ninstance Storable CDdNode where\n\tsizeOf _ = (#size DdNode)\n\talignment _ = alignment (undefined :: Int)\n\tpeek ptr = do\n\t\tindex <- (#peek DdNode, index) ptr\n\t\tref <- (#peek DdNode, ref) ptr\n\t\treturn $ CDdNode index ref\n\tpoke ptr (CDdNode index ref) = do\n\t\t(#poke DdNode, index) ptr index\n\t\t(#poke DdNode, ref) ptr ref\n -}\n\nforeign import ccall safe \"cudd.h Cudd_ReadOne_s\"\n\tc_cuddReadOne :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadLogicZero_s\"\n\tc_cuddReadLogicZero :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadOne_withRef_s\"\n\tc_cuddReadOneWithRef :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadLogicZero_withRef_s\"\n\tc_cuddReadLogicZeroWithRef :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddIthVar_s\"\n\tc_cuddBddIthVar :: Ptr CDdManager -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddAnd_s\"\n\tc_cuddBddAnd :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddOr_s\"\n\tc_cuddBddOr :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddNand_s\"\n\tc_cuddBddNand :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddNor_s\"\n\tc_cuddBddNor :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddXor_s\"\n\tc_cuddBddXor :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddXnor_s\"\n\tc_cuddBddXnor :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_Not_s\"\n\tc_cuddNot :: Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_NotNoRef_s\"\n\tc_cuddNotNoRef :: Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddIte_s\"\n c_cuddBddIte :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddExistAbstract_s\"\n\tc_cuddBddExistAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddUnivAbstract_s\"\n\tc_cuddBddUnivAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_IterDerefBdd\"\n\tc_cuddIterDerefBdd :: Ptr CDdManager -> Ptr CDdNode -> IO ()\n\nforeign import ccall safe \"cuddwrap.h wrappedCuddRef\"\n\tcuddRef :: Ptr CDdNode -> IO ()\n\nforeign import ccall safe \"cudd.h Cudd_Init\"\n\tc_cuddInit :: CInt -> CInt -> CInt -> CInt -> CInt -> IO (Ptr CDdManager)\n\nforeign import ccall safe \"cudd.h Cudd_ShuffleHeap\"\n c_cuddShuffleHeap :: Ptr CDdManager -> Ptr CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_SetVarMap\"\n c_cuddSetVarMap :: Ptr CDdManager -> Ptr (Ptr CDdNode) -> Ptr (Ptr CDdNode) -> CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddVarMap_s\"\n c_cuddBddVarMap :: Ptr CDdManager -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddLeq\"\n c_cuddBddLeq :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddSwapVariables_s\"\n c_cuddBddSwapVariables :: Ptr CDdManager -> Ptr CDdNode -> Ptr (Ptr CDdNode) -> Ptr (Ptr CDdNode) -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_LargestCube_s\"\n c_cuddLargestCube :: Ptr CDdManager -> Ptr CDdNode -> Ptr CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddMakePrime_s\"\n c_cuddBddMakePrime :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_SupportIndex\"\n\tc_cuddSupportIndex :: Ptr CDdManager -> Ptr CDdNode -> IO(Ptr CInt)\n\nforeign import ccall safe \"cudd.h Cudd_SupportIndices\"\n c_cuddSupportIndices :: Ptr CDdManager -> Ptr CDdNode -> Ptr (Ptr CInt) -> IO (CInt)\n\nforeign import ccall safe \"cudd.h Cudd_IndicesToCube_s\"\n c_cuddIndicesToCube :: Ptr CDdManager -> Ptr CInt -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddComputeCube_s\"\n c_cuddBddComputeCube :: Ptr CDdManager -> Ptr (Ptr CDdNode) -> Ptr CInt -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_BddToCubeArray\"\n c_cuddBddToCubeArray :: Ptr CDdManager -> Ptr CDdNode -> Ptr CInt -> IO (CInt)\n\nforeign import ccall safe \"cudd.h Cudd_ReadSize\"\n\tc_cuddReadSize :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddCompose_s\"\n c_cuddBddCompose :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddAndAbstract_s\"\n c_cuddBddAndAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddXorExistAbstract_s\"\n c_cuddBddXorExistAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddLeqUnless\"\n c_cuddBddLeqUnless :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_EquivDC\"\n c_cuddEquivDC :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_Xeqy_s\"\n\tc_cuddXeqy :: Ptr CDdManager -> CInt -> Ptr (Ptr CDdNode) -> Ptr (Ptr CDdNode) -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_DebugCheck\"\n c_cuddDebugCheck :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_CheckKeys\"\n c_cuddCheckKeys :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddPickOneMinterm_s\"\n\tc_cuddBddPickOneMinterm :: Ptr CDdManager -> Ptr CDdNode -> Ptr (Ptr CDdNode) -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_CheckZeroRef\"\n c_cuddCheckZeroRef :: Ptr CDdManager -> IO (CInt)\n\nforeign import ccall safe \"cudd.h Cudd_ReadInvPerm\"\n c_cuddReadInvPerm :: Ptr CDdManager -> CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadPerm\"\n c_cuddReadPerm :: Ptr CDdManager -> CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_DagSize\"\n c_cuddDagSize :: Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadNodeCount\"\n c_cuddReadNodeCount :: Ptr CDdManager -> IO CLong\n\nforeign import ccall safe \"cudd.h Cudd_ReadPeakNodeCount\"\n c_cuddReadPeakNodeCount :: Ptr CDdManager -> IO CLong\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxCache\"\n c_cuddReadMaxCache :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxCacheHard\"\n c_cuddReadMaxCacheHard :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxCacheHard\"\n c_cuddSetMaxCacheHard :: Ptr CDdManager -> CInt -> IO ()\n\nforeign import ccall safe \"cudd.h Cudd_ReadCacheSlots\"\n c_cuddReadCacheSlots :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadCacheUsedSlots\"\n c_cuddReadCacheUsedSlots :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddAndLimit\"\n c_cuddBddAndLimit :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> CUInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddNewVarAtLevel_s\"\n c_cuddBddNewVarAtLevel :: Ptr CDdManager -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadTree\"\n c_cuddReadTree :: Ptr CDdManager -> IO (Ptr CMtrNode)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, CPP #-}\n\nmodule CuddC (\n CDdManager,\n CDdNode,\n c_cuddReadOne,\n c_cuddReadLogicZero,\n c_cuddReadOneWithRef,\n c_cuddReadLogicZeroWithRef,\n c_cuddBddIthVar,\n c_cuddBddAnd,\n c_cuddBddOr,\n c_cuddBddNand,\n c_cuddBddNor,\n c_cuddBddXor,\n c_cuddBddXnor,\n c_cuddNot,\n c_cuddNotNoRef,\n c_cuddBddIte,\n c_cuddBddExistAbstract,\n c_cuddBddUnivAbstract,\n c_cuddIterDerefBdd,\n cuddRef,\n c_cuddInit,\n c_cuddShuffleHeap,\n c_cuddSetVarMap,\n c_cuddBddVarMap,\n c_cuddBddLeq,\n c_cuddBddSwapVariables,\n c_cuddLargestCube,\n c_cuddBddMakePrime,\n c_cuddSupportIndex,\n c_cuddSupportIndices,\n c_cuddIndicesToCube,\n c_cuddBddComputeCube,\n c_cuddBddToCubeArray,\n c_cuddReadSize,\n c_cuddBddCompose,\n c_cuddBddAndAbstract,\n c_cuddBddXorExistAbstract,\n c_cuddBddLeqUnless,\n c_cuddEquivDC,\n c_cuddXeqy,\n c_cuddDebugCheck,\n c_cuddCheckKeys,\n c_cuddBddPickOneMinterm,\n c_cuddCheckZeroRef,\n c_cuddReadInvPerm,\n c_cuddReadPerm,\n c_cuddDagSize,\n c_cuddReadNodeCount,\n c_cuddReadPeakNodeCount,\n c_cuddReadMaxCache,\n c_cuddReadMaxCacheHard,\n c_cuddSetMaxCacheHard,\n c_cuddReadCacheSlots,\n c_cuddReadCacheUsedSlots,\n c_cuddBddAndLimit,\n c_cuddBddNewVarAtLevel,\n c_cuddReadTree\n ) where\n\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C.Types\n\nimport MTR\n\ndata CDdManager\ndata CDdNode = CDdNode {index :: CInt, ref :: CInt}\n\n{-\ninstance Storable CDdNode where\n\tsizeOf _ = (#size DdNode)\n\talignment _ = alignment (undefined :: Int)\n\tpeek ptr = do\n\t\tindex <- (#peek DdNode, index) ptr\n\t\tref <- (#peek DdNode, ref) ptr\n\t\treturn $ CDdNode index ref\n\tpoke ptr (CDdNode index ref) = do\n\t\t(#poke DdNode, index) ptr index\n\t\t(#poke DdNode, ref) ptr ref\n -}\n\nforeign import ccall safe \"cudd.h Cudd_ReadOne_s\"\n\tc_cuddReadOne :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadLogicZero_s\"\n\tc_cuddReadLogicZero :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadOne_withRef_s\"\n\tc_cuddReadOneWithRef :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadLogicZero_withRef_s\"\n\tc_cuddReadLogicZeroWithRef :: Ptr CDdManager -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddIthVar_s\"\n\tc_cuddBddIthVar :: Ptr CDdManager -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddAnd_s\"\n\tc_cuddBddAnd :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddOr_s\"\n\tc_cuddBddOr :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddNand_s\"\n\tc_cuddBddNand :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddNor_s\"\n\tc_cuddBddNor :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddXor_s\"\n\tc_cuddBddXor :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddXnor_s\"\n\tc_cuddBddXnor :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_Not_s\"\n\tc_cuddNot :: Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_NotNoRef_s\"\n\tc_cuddNotNoRef :: Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddIte_s\"\n c_cuddBddIte :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddExistAbstract_s\"\n\tc_cuddBddExistAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddUnivAbstract_s\"\n\tc_cuddBddUnivAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_IterDerefBdd\"\n\tc_cuddIterDerefBdd :: Ptr CDdManager -> Ptr CDdNode -> IO ()\n\nforeign import ccall safe \"cuddwrap.h wrappedCuddRef\"\n\tcuddRef :: Ptr CDdNode -> IO ()\n\nforeign import ccall safe \"cudd.h Cudd_Init\"\n\tc_cuddInit :: CInt -> CInt -> CInt -> CInt -> CInt -> IO (Ptr CDdManager)\n\nforeign import ccall safe \"cudd.h Cudd_ShuffleHeap\"\n c_cuddShuffleHeap :: Ptr CDdManager -> Ptr CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_SetVarMap\"\n c_cuddSetVarMap :: Ptr CDdManager -> Ptr (Ptr CDdNode) -> Ptr (Ptr CDdNode) -> CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddVarMap_s\"\n c_cuddBddVarMap :: Ptr CDdManager -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddLeq\"\n c_cuddBddLeq :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddSwapVariables_s\"\n c_cuddBddSwapVariables :: Ptr CDdManager -> Ptr CDdNode -> Ptr (Ptr CDdNode) -> Ptr (Ptr CDdNode) -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_LargestCube_s\"\n c_cuddLargestCube :: Ptr CDdManager -> Ptr CDdNode -> Ptr CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddMakePrime_s\"\n c_cuddBddMakePrime :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_SupportIndex\"\n\tc_cuddSupportIndex :: Ptr CDdManager -> Ptr CDdNode -> IO(Ptr CInt)\n\nforeign import ccall safe \"cudd.h Cudd_SupportIndices\"\n c_cuddSupportIndices :: Ptr CDdManager -> Ptr CDdNode -> Ptr (Ptr CInt) -> IO (CInt)\n\nforeign import ccall safe \"cudd.h Cudd_IndicesToCube_s\"\n c_cuddIndicesToCube :: Ptr CDdManager -> Ptr CInt -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddComputeCube_s\"\n c_cuddBddComputeCube :: Ptr CDdManager -> Ptr (Ptr CDdNode) -> Ptr CInt -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_BddToCubeArray\"\n c_cuddBddToCubeArray :: Ptr CDdManager -> Ptr CDdNode -> Ptr CInt -> IO (CInt)\n\nforeign import ccall safe \"cudd.h Cudd_ReadSize\"\n\tc_cuddReadSize :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddCompose_s\"\n c_cuddBddCompose :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddAndAbstract_s\"\n c_cuddBddAndAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddXorExistAbstract_s\"\n c_cuddBddXorExistAbstract :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddLeqUnless\"\n c_cuddBddLeqUnless :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_EquivDC\"\n c_cuddEquivDC :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_Xeqy_s\"\n\tc_cuddXeqy :: Ptr CDdManager -> CInt -> Ptr (Ptr CDdNode) -> Ptr (Ptr CDdNode) -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_DebugCheck\"\n c_cuddDebugCheck :: Ptr CDdManager -> IO ()\n\nforeign import ccall safe \"cudd.h Cudd_CheckKeys\"\n c_cuddCheckKeys :: Ptr CDdManager -> IO ()\n\nforeign import ccall safe \"cudd.h Cudd_bddPickOneMinterm_s\"\n\tc_cuddBddPickOneMinterm :: Ptr CDdManager -> Ptr CDdNode -> Ptr (Ptr CDdNode) -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_CheckZeroRef\"\n c_cuddCheckZeroRef :: Ptr CDdManager -> IO (CInt)\n\nforeign import ccall safe \"cudd.h Cudd_ReadInvPerm\"\n c_cuddReadInvPerm :: Ptr CDdManager -> CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadPerm\"\n c_cuddReadPerm :: Ptr CDdManager -> CInt -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_DagSize\"\n c_cuddDagSize :: Ptr CDdNode -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadNodeCount\"\n c_cuddReadNodeCount :: Ptr CDdManager -> IO CLong\n\nforeign import ccall safe \"cudd.h Cudd_ReadPeakNodeCount\"\n c_cuddReadPeakNodeCount :: Ptr CDdManager -> IO CLong\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxCache\"\n c_cuddReadMaxCache :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxCacheHard\"\n c_cuddReadMaxCacheHard :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxCacheHard\"\n c_cuddSetMaxCacheHard :: Ptr CDdManager -> CInt -> IO ()\n\nforeign import ccall safe \"cudd.h Cudd_ReadCacheSlots\"\n c_cuddReadCacheSlots :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_ReadCacheUsedSlots\"\n c_cuddReadCacheUsedSlots :: Ptr CDdManager -> IO CInt\n\nforeign import ccall safe \"cudd.h Cudd_bddAndLimit\"\n c_cuddBddAndLimit :: Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> CUInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_bddNewVarAtLevel_s\"\n c_cuddBddNewVarAtLevel :: Ptr CDdManager -> CInt -> IO (Ptr CDdNode)\n\nforeign import ccall safe \"cudd.h Cudd_ReadTree\"\n c_cuddReadTree :: Ptr CDdManager -> IO (Ptr CMtrNode)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e3b655c1eb6d85d4f6dc1d595454251aafc73a9d","subject":"refs #8: add clEnqueueMapImage","message":"refs #8: add clEnqueueMapImage\n","repos":"Delan90\/opencl,IFCA\/opencl,Delan90\/opencl,IFCA\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.chs","new_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.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.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, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n{-\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\n-}\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO 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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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":"{- 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.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, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ Must be a valid\n -- command-queue. The OpenCL\n -- context associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ Must be a valid\n -- command-queue. The OpenCL\n -- context associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following throw error:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a \n => CLCommandQueue -- ^ Must be a valid command-queue.\n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\n-}\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO 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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8b11d2fc2edb06961460b59c435e1dcde2a62876","subject":"close datasets directly without refcounting them since we're not sharing them and wont support it","message":"close datasets directly without refcounting them since we're not sharing them and wont support it\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 , 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\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 , nullDatasetH\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetDriverName\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 , 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 , 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(..), SomeException, try)\nimport Control.DeepSeq (NFData(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Catch (MonadMask, 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.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.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 (stderr, hPutStrLn)\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 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 (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\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\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\ndriverCreationOptionList :: DriverName -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverHByName 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 :: 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 options = 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 options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\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\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 options progressFun =\n newDatasetHandle $\n withProgressFun \"createCopy\" progressFun $ \\pFunc -> do\n d <- driverHByName 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 = {#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\ndatasetDriverName :: Dataset s a t -> DriverName\ndatasetDriverName ds = unsafePerformIO $\n DriverName <$> (packCString =<< {#call unsafe GetDriverShortName as ^#} d)\n where Driver d = datasetDriver 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\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\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 <- 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\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 <$> 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 = datasetHGeotransformIO . unDataset\n\ndatasetGeotransform :: Dataset s a t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform = liftIO . datasetGeotransformIO\n\ndatasetHGeotransformIO :: DatasetH -> IO (Maybe Geotransform)\ndatasetHGeotransformIO ds = alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} ds (castPtr p)\n if toEnumC ret == CE_None\n then liftM Just (peek p)\n else return Nothing\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\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\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\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\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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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\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{-# INLINEABLE 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{-# INLINEABLE 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 <- liftIO $ do\n h <-{#call unsafe GDALGetBandDataset as ^#} (unBand band)\n datasetHGeotransformIO h\n\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 = 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{-# INLINEABLE 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 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{-# 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{-# INLINEABLE 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 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{-# 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE fmapBand #-}\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 <- liftM (L.foldl' (G.zipWith fun) acc)\n (lift (mapM (flip readBandBlock bix) bs))\n yield (bix, r)\n{-# INLINEABLE foldBands #-}\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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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 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{-# INLINEABLE 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\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 >=> 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 :: (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\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{-# INLINEABLE 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 , 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\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 , nullDatasetH\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetDriverName\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 , 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 , 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(..), SomeException, try)\nimport Control.DeepSeq (NFData(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Catch (MonadMask, 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.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.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 (stderr, hPutStrLn)\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 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 (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\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\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\ndriverCreationOptionList :: DriverName -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverHByName 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 :: 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 options = 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 options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\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\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 options progressFun =\n newDatasetHandle $\n withProgressFun \"createCopy\" progressFun $ \\pFunc -> do\n d <- driverHByName 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 t'\ndatasetDriver ds =\n unsafePerformIO $\n Driver <$> {#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n\ndatasetDriverName :: Dataset s a t -> DriverName\ndatasetDriverName ds = unsafePerformIO $\n DriverName <$> (packCString =<< {#call unsafe GetDriverShortName as ^#} d)\n where Driver d = datasetDriver 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\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\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 <- 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\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 <$> 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\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\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\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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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\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{-# INLINEABLE 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{-# INLINEABLE 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\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{-# INLINEABLE 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 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{-# 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{-# INLINEABLE 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 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{-# 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE fmapBand #-}\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 <- liftM (L.foldl' (G.zipWith fun) acc)\n (lift (mapM (flip readBandBlock bix) bs))\n yield (bix, r)\n{-# INLINEABLE foldBands #-}\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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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{-# INLINEABLE 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 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{-# INLINEABLE 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\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 >=> 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 :: (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\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{-# INLINEABLE decorate #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1aaa5b5eb9aaf9bac278153b2ad4f9cb1a285b99","subject":"[project @ 2003-11-02 23:57:07 by as49] Added marshalling functions to create GLists and GSLists.","message":"[project @ 2003-11-02 23:57:07 by as49]\nAdded marshalling functions to create GLists and GSLists.\n","repos":"vincenthz\/webkit","old_file":"gtk\/glib\/GList.chs","new_file":"gtk\/glib\/GList.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n-- \n-- Created: 19 March 2002\n--\n-- Version $Revision: 1.8 $ from $Date: 2003\/11\/02 23:57:07 $\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-- * Defines functions to extract data from a GList and to produce a GList from\n-- a list of pointers.\n--\n-- * The same for GSList.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n--\nmodule GList(\n ptrToInt,\n GList,\n fromGList,\n toGList,\n GSList,\n readGSList,\n fromGSList,\n fromGSListRev,\n toGSList\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n\n{# context lib=\"g\" prefix=\"g\" #}\n\n{#pointer * GList#}\n{#pointer * GSList#}\n\n-- methods\n\n-- Convert a pointer to an Int.\n--\nptrToInt :: Ptr a -> Int\nptrToInt ptr = minusPtr ptr nullPtr \n\n-- Turn a GList into a list of pointers.\n--\nfromGList :: GList -> IO [Ptr a]\nfromGList glist = do\n glist' <- {#call unsafe list_reverse#} glist\n extractList glist' []\n where\n extractList gl xs\n | gl==nullPtr = return xs\n | otherwise = do\n\tx <- {#get GList.data#} gl\n\tgl' <- {#call unsafe list_delete_link#} gl gl\n\textractList gl' (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers but don't destroy the list.\n--\nreadGSList :: GSList -> IO [Ptr a]\nreadGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#get GSList->next#} gslist\n xs <- readGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers.\n--\nfromGSList :: GSList -> IO [Ptr a]\nfromGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#call unsafe slist_delete_link#} gslist gslist\n xs <- fromGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers and reverse it.\n--\nfromGSListRev :: GSList -> IO [Ptr a]\nfromGSListRev gslist =\n extractList gslist []\n where\n extractList gslist xs\n | gslist==nullPtr = return xs\n | otherwise\t= do\n\tx <- {#get GSList->data#} gslist\n\tgslist' <- {#call unsafe slist_delete_link#} gslist gslist\n\textractList gslist' (castPtr x:xs)\n\n-- Convert an Int into a pointer.\n--\nintToPtr :: Int -> Ptr a\nintToPtr int = plusPtr nullPtr int\n\n\n-- Turn a list of something into a GList.\n--\ntoGList :: [Ptr a] -> IO GList\ntoGList xs = makeList nullPtr xs\n where\n -- makeList :: GList -> [Ptr a] -> IO GList\n makeList current (x:xs) = do\n newHead <- {#call unsafe list_prepend#} current (castPtr x)\n makeList newHead xs\n makeList current [] = return current\n\n-- Turn a list of something into a GSList.\n--\ntoGSList :: [Ptr a] -> IO GSList\ntoGSList xs = makeList nullPtr xs\n where\n -- makeList :: GSList -> [Ptr a] -> IO GSList\n makeList current (x:xs) = do\n newHead <- {#call unsafe slist_prepend#} current (castPtr x)\n makeList newHead xs\n makeList current [] = return current\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n-- \n-- Created: 19 March 2002\n--\n-- Version $Revision: 1.7 $ from $Date: 2003\/07\/09 22:42:44 $\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-- * Define functions to extract data from a GList and to produce a GList from\n-- a list of pointers.\n--\n-- * Define functions to extract data from a GSList.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Figure out if we ever need to generate a GList.\n--\nmodule GList(\n ptrToInt,\n GList,\n fromGList,\n -- toGList,\n GSList,\n readGSList,\n fromGSList,\n fromGSListRev\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n\n{# context lib=\"g\" prefix=\"g\" #}\n\n{#pointer * GList#}\n{#pointer * GSList#}\n\n-- methods\n\n-- Convert a pointer to an Int.\n--\nptrToInt :: Ptr a -> Int\nptrToInt ptr = minusPtr ptr nullPtr \n\n-- Turn a GList into a list of pointers.\n--\nfromGList :: GList -> IO [Ptr a]\nfromGList glist = do\n glist' <- {#call unsafe list_reverse#} glist\n extractList glist' []\n where\n extractList gl xs\n | gl==nullPtr = return xs\n | otherwise = do\n\tx <- {#get GList.data#} gl\n\tgl' <- {#call unsafe list_delete_link#} gl gl\n\textractList gl' (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers but don't destroy the list.\n--\nreadGSList :: GSList -> IO [Ptr a]\nreadGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#get GSList->next#} gslist\n xs <- readGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers.\n--\nfromGSList :: GSList -> IO [Ptr a]\nfromGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#call unsafe slist_delete_link#} gslist gslist\n xs <- fromGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers and reverse it.\n--\nfromGSListRev :: GSList -> IO [Ptr a]\nfromGSListRev gslist =\n extractList gslist []\n where\n extractList gslist xs\n | gslist==nullPtr = return xs\n | otherwise\t= do\n\tx <- {#get GSList->data#} gslist\n\tgslist' <- {#call unsafe slist_delete_link#} gslist gslist\n\textractList gslist' (castPtr x:xs)\n\n-- Convert an Int into a pointer.\n--\nintToPtr :: Int -> Ptr a\nintToPtr int = plusPtr nullPtr int\n\n\n-- Turn a list of something into a GList.\n--\ntoGList :: [a] -> (a -> Ptr b) -> IO GList\ntoGList xs conv = makeList nullPtr xs\n where\n -- makeList :: GList -> [a] -> IO GList\n makeList current (x:xs) = do\n newHead <- {#call unsafe list_prepend#} current ((castPtr.conv) x)\n makeList newHead xs\n makeList current [] = return current\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"2f09147b29628d8362985cf3f379ebf7b67a2f12","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\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule GDAL.Internal.OGR (\n GeometryType (..)\n , Geometry\n , ROGeometry\n , RWGeometry\n , Datasource\n , SQLDialect (..)\n , WkbByteOrder (..)\n , Layer\n , RODatasource\n , RWDatasource\n , ROLayer\n , RWLayer\n\n , unDatasource\n , unLayer\n , withLockedDatasourcePtr\n , openReadOnly\n , openReadWrite\n , withLockedLayerPtr\n\n , createFromWktIO\n , createFromWkbIO\n , exportToWktIO\n , exportToWkbIO\n\n , createFromWkt\n , createFromWkb\n , exportToWkt\n , exportToWkb\n\n , unsafeThawGeometry\n , unsafeFreezeGeometry\n\n , getLayer\n , getLayerByName\n , executeSQL\n , layerCount\n , datasourceName\n\n , registerAllDrivers\n , cleanupAll\n) where\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM, when, void, (<=<), (>=>))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCString, unpack)\nimport Data.ByteString.Unsafe (\n unsafeUseAsCString\n , unsafeUseAsCStringLen\n , unsafePackMallocCStringLen\n )\nimport Data.Coerce (coerce)\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CUChar(..))\nimport Foreign.Ptr (FunPtr, Ptr, nullPtr, castPtr)\nimport qualified Foreign.Concurrent as FConc\nimport Foreign.ForeignPtr (\n ForeignPtr\n , withForeignPtr\n , newForeignPtr\n , newForeignPtr_\n )\nimport Foreign.Marshal.Alloc (alloca, mallocBytes)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Storable (peek, poke)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.OSR\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.Util\n\n#include \"ogr_api.h\"\n\n{#context prefix = \"OGR\" #}\n\n{#fun OGRRegisterAll as registerAllDrivers {} -> `()' #}\n{#fun OGRCleanupAll as cleanupAll {} -> `()' #}\n\n\n{#pointer OGRDataSourceH as Datasource foreign newtype nocode#}\n\nnewtype Datasource s (t::AccessMode) a\n = Datasource (Mutex, Ptr (Datasource s t a))\n\nunDatasource :: Datasource s t a -> Ptr (Datasource s t a)\nunDatasource (Datasource (_,p)) = p\n\ntype RODatasource s = Datasource s ReadOnly\ntype RWDatasource s = Datasource s ReadWrite\n\nwithLockedDatasourcePtr\n :: Datasource s t a -> (Ptr (Datasource s t a) -> IO b) -> IO b\nwithLockedDatasourcePtr (Datasource (m,p)) f = withMutex m (f p)\n\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n{#enum define WkbByteOrder\n { wkbXDR as WkbXDR\n , wkbNDR as WkbNDR\n } deriving (Eq, Show) #}\n\nopenReadOnly :: String -> GDAL s (RODatasource s a)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDatasource s a)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (Datasource s t a)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" (c_open p' (fromEnumC m) nullPtr)\n newDatasourceHandle ptr `catch` (\\NullDatasource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\nforeign import ccall safe \"ogr_api.h OGROpen\" c_open\n :: CString -> CInt -> Ptr () -> IO (Ptr (Datasource s t a))\n\nnewDatasourceHandle :: Ptr (Datasource s t a) -> GDAL s (Datasource s t a)\nnewDatasourceHandle p\n | p==nullPtr = throwBindingException NullDatasource\n | otherwise = do\n registerFinalizer (c_releaseDatasource p)\n m <- liftIO newMutex\n return $ Datasource (m,p)\n\nforeign import ccall safe \"ogr_api.h OGRReleaseDataSource\"\n c_releaseDatasource :: Ptr (Datasource s t a) -> IO ()\n\n\n{#pointer OGRLayerH as Layer newtype nocode#}\n\nnewtype (Layer s (t::AccessMode) a)\n = Layer (Mutex, Ptr (Layer s t a))\n\nunLayer :: Layer s t a -> Ptr (Layer s t a)\nunLayer (Layer (_,p)) = p\n\nwithLockedLayerPtr\n :: Layer s t a -> (Ptr (Layer s t a) -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\ngetLayer :: Int -> Datasource s t a -> GDAL s (Layer s t a)\ngetLayer layer (Datasource (m,dp)) = liftIO $ do\n p <- throwIfError \"getLayer\" (c_getLayer dp (fromIntegral layer))\n when (p==nullPtr) $ throwBindingException (InvalidLayerIndex layer)\n return (Layer (m, p))\n\nforeign import ccall safe \"ogr_api.h OGR_DS_GetLayer\" c_getLayer\n :: Ptr (Datasource s t a) -> CInt -> IO (Ptr (Layer s t a))\n\ngetLayerByName :: String -> Datasource s t a -> GDAL s (Layer s t a)\ngetLayerByName layer (Datasource (m,dp)) = liftIO $\n withCString layer $ \\lyr -> do\n p <- throwIfError \"getLayerByName\" (c_getLayerByName dp lyr)\n when (p==nullPtr) $ throwBindingException (InvalidLayerName layer)\n return (Layer (m,p))\n\nforeign import ccall safe \"ogr_api.h OGR_DS_GetLayerByName\" c_getLayerByName\n :: Ptr (Datasource s t a) -> CString -> IO (Ptr (Layer s t a))\n\n\nlayerCount :: Datasource s t a -> GDAL s Int\nlayerCount = liftM fromIntegral . liftIO . c_getLayerCount . unDatasource\n\nforeign import ccall unsafe \"ogr_api.h OGR_DS_GetLayerCount\" c_getLayerCount\n :: Ptr (Datasource s t a) -> IO CInt\n\ndatasourceName :: Datasource s t a -> GDAL s String\ndatasourceName = liftIO . (peekCString <=< c_getName . unDatasource)\n\nforeign import ccall unsafe \"ogr_api.h OGR_DS_GetName\" c_getName\n :: Ptr (Datasource s t a) -> IO CString\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> String -> Maybe ROGeometry -> RODatasource s a\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(Datasource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullPtr) $ throwBindingException NullLayer\n registerFinalizer (c_releaseResultSet dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n withLockedDatasourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n withCString query $ \\sQuery ->\n throwIfError \"executeSQL\" (c_executeSQL dsPtr sQuery sFilter sDialect)\n\nforeign import ccall safe \"ogr_api.h OGR_DS_ExecuteSQL\"\n c_executeSQL\n :: Ptr (RODatasource s a) -> CString -> Ptr ROGeometry -> CString\n -> IO (Ptr (ROLayer s a))\n\nforeign import ccall safe \"ogr_api.h OGR_DS_ReleaseResultSet\"\n c_releaseResultSet\n :: Ptr (RODatasource s a) -> Ptr (ROLayer s a) -> IO ()\n\n\n\nnewtype Geometry (t::AccessMode) = Geometry (ForeignPtr (Geometry t))\n\nwithMaybeGeometry :: Maybe (Geometry t) -> (Ptr (Geometry t) -> IO a) -> IO a\nwithMaybeGeometry (Just (Geometry ptr)) = withForeignPtr ptr\nwithMaybeGeometry Nothing = ($ nullPtr)\n\nwithGeometry :: Geometry t -> (Ptr (Geometry t) -> IO a) -> IO a\nwithGeometry (Geometry ptr) = withForeignPtr ptr\n\ntype ROGeometry = Geometry ReadOnly\ntype RWGeometry = Geometry ReadWrite\n\nforeign import ccall \"ogr_api.h &OGR_G_DestroyGeometry\"\n c_destroyGeometry :: FunPtr (Ptr (Geometry t) -> IO ())\n\nnewGeometryHandle :: Ptr (Geometry t) -> IO (Geometry t)\nnewGeometryHandle p\n | p==nullPtr = throwBindingException NullGeometry\n | otherwise = Geometry <$> newForeignPtr c_destroyGeometry p\n\ncreateFromWkb\n :: ByteString -> Maybe SpatialReference -> Either OGRError ROGeometry\ncreateFromWkb bs = unsafePerformIO . createFromWkbIO bs\n\ncreateFromWkbIO\n :: ByteString -> Maybe SpatialReference -> IO (Either OGRError (Geometry t))\ncreateFromWkbIO bs mSrs =\n alloca $ \\gPtr ->\n unsafeUseAsCStringLen bs $ \\(sPtr, len) ->\n withMaybeSpatialReference mSrs $ \\srs ->\n checkOGRError\n (c_createFromWkb sPtr srs gPtr (fromIntegral len))\n (peek gPtr >>= newGeometryHandle)\n\nforeign import ccall unsafe \"ogr_api.h OGR_G_CreateFromWkb\"\n c_createFromWkb ::\n CString -> Ptr SpatialReference -> Ptr (Ptr (Geometry t)) -> CInt -> IO CInt\n\n\ncreateFromWkt\n :: ByteString -> Maybe SpatialReference -> Either OGRError ROGeometry\ncreateFromWkt bs = unsafePerformIO . createFromWktIO bs\n\ncreateFromWktIO\n :: ByteString -> Maybe SpatialReference -> IO (Either OGRError (Geometry t))\ncreateFromWktIO bs mSrs =\n alloca $ \\gPtr ->\n alloca $ \\sPtrPtr ->\n unsafeUseAsCString bs $ \\sPtr ->\n withMaybeSpatialReference mSrs $ \\srs ->\n checkOGRError\n (poke sPtrPtr sPtr >> c_createFromWkt sPtrPtr srs gPtr)\n (peek gPtr >>= newGeometryHandle)\n\nforeign import ccall unsafe \"ogr_api.h OGR_G_CreateFromWkt\"\n c_createFromWkt ::\n Ptr CString -> Ptr SpatialReference -> Ptr (Ptr (Geometry t)) -> IO CInt\n\nunsafeFreezeGeometry :: RWGeometry -> ROGeometry\nunsafeFreezeGeometry = coerce\n\nunsafeThawGeometry :: RWGeometry -> ROGeometry\nunsafeThawGeometry = coerce\n\nwithMaybeSpatialReference\n :: Maybe SpatialReference -> (Ptr SpatialReference -> IO a) -> IO a\nwithMaybeSpatialReference Nothing = ($ nullPtr)\nwithMaybeSpatialReference (Just s) = withSpatialReference s\n\npeekAndPack :: Ptr CString -> IO ByteString\npeekAndPack = peek >=> packCString\n\nexportToWktIO :: Geometry t -> IO ByteString\nexportToWktIO g = withGeometry g $ \\gPtr -> alloca $ \\sPtrPtr -> do\n void $ {#call OGR_G_ExportToWkt as ^ #} (castPtr gPtr) sPtrPtr\n peekAndPack sPtrPtr\n\nexportToWkt :: ROGeometry -> ByteString\nexportToWkt = unsafePerformIO . exportToWktIO\n\nexportToWkbIO :: WkbByteOrder -> Geometry t -> IO ByteString\nexportToWkbIO bo g = withGeometry g $ \\gPtr -> do\n len <- liftM fromIntegral ({#call OGR_G_WkbSize as ^ #} (castPtr gPtr))\n buf <- mallocBytes len\n void $ {#call OGR_G_ExportToWkb as ^ #} (castPtr gPtr) (fromEnumC bo) buf\n unsafePackMallocCStringLen (castPtr buf, len)\n\nexportToWkb :: WkbByteOrder -> ROGeometry -> ByteString\nexportToWkb bo = unsafePerformIO . exportToWkbIO bo\n\ngeomEqIO :: Geometry t -> Geometry t1 -> IO Bool\ngeomEqIO a b = withGeometry a $ \\aPtr -> withGeometry b $ \\bPtr ->\n liftM toBool ({#call OGR_G_Equals as ^#} (castPtr aPtr) (castPtr bPtr))\n\ninstance Show ROGeometry where\n show = unpack . exportToWkt\n\ninstance Eq ROGeometry where\n a == b = unsafePerformIO (geomEqIO a b)\n\n{#enum OGRwkbGeometryType as GeometryType {underscoreToCase}#}\n\ninstance Show GeometryType where\n show s = unsafePerformIO $\n {#call unsafe OGRGeometryTypeToName as ^#} s' >>= peekCString\n where s' = fromEnumC s\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule GDAL.Internal.OGR (\n GeometryType (..)\n , Geometry\n , ROGeometry\n , RWGeometry\n , Datasource\n , SQLDialect (..)\n , WkbByteOrder (..)\n , Layer\n , RODatasource\n , RWDatasource\n , ROLayer\n , RWLayer\n\n , unDatasource\n , unLayer\n , withLockedDatasourcePtr\n , openReadOnly\n , openReadWrite\n , withLockedLayerPtr\n\n , createFromWktIO\n , createFromWkbIO\n , exportToWktIO\n , exportToWkbIO\n\n , createFromWkt\n , createFromWkb\n , exportToWkt\n , exportToWkb\n\n , unsafeThawGeometry\n , unsafeFreezeGeometry\n\n , getLayer\n , getLayerByName\n , executeSQL\n , layerCount\n , datasourceName\n\n , registerAllDrivers\n , cleanupAll\n) where\n\nimport Control.Monad (liftM, when, void, (<=<), (>=>))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCString, unpack)\nimport Data.ByteString.Unsafe (\n unsafeUseAsCString\n , unsafeUseAsCStringLen\n , unsafePackMallocCStringLen\n )\nimport Data.Coerce (coerce)\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CUChar(..))\nimport Foreign.Ptr (FunPtr, Ptr, nullPtr, castPtr)\nimport qualified Foreign.Concurrent as FConc\nimport Foreign.ForeignPtr (\n ForeignPtr\n , withForeignPtr\n , newForeignPtr\n , newForeignPtr_\n )\nimport Foreign.Marshal.Alloc (alloca, mallocBytes)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Storable (peek, poke)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.OSR\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.Util\n\n#include \"ogr_api.h\"\n\n{#context prefix = \"OGR\" #}\n\n{#fun OGRRegisterAll as registerAllDrivers {} -> `()' #}\n{#fun OGRCleanupAll as cleanupAll {} -> `()' #}\n\n\n{#pointer OGRDataSourceH as Datasource foreign newtype nocode#}\n\nnewtype Datasource s (t::AccessMode) a\n = Datasource (Mutex, Ptr (Datasource s t a))\n\nunDatasource :: Datasource s t a -> Ptr (Datasource s t a)\nunDatasource (Datasource (_,p)) = p\n\ntype RODatasource s = Datasource s ReadOnly\ntype RWDatasource s = Datasource s ReadWrite\n\nwithLockedDatasourcePtr\n :: Datasource s t a -> (Ptr (Datasource s t a) -> IO b) -> IO b\nwithLockedDatasourcePtr (Datasource (m,p)) f = withMutex m (f p)\n\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n{#enum define WkbByteOrder\n { wkbXDR as WkbXDR\n , wkbNDR as WkbNDR\n } deriving (Eq, Show) #}\n\nopenReadOnly :: String -> GDAL s (RODatasource s a)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDatasource s a)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (Datasource s t a)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" (c_open p' (fromEnumC m) nullPtr)\n newDatasourceHandle ptr `catch` (\\NullDatasource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\nforeign import ccall safe \"ogr_api.h OGROpen\" c_open\n :: CString -> CInt -> Ptr () -> IO (Ptr (Datasource s t a))\n\nnewDatasourceHandle :: Ptr (Datasource s t a) -> GDAL s (Datasource s t a)\nnewDatasourceHandle p\n | p==nullPtr = throwBindingException NullDatasource\n | otherwise = do\n registerFinalizer (c_releaseDatasource p)\n m <- liftIO newMutex\n return $ Datasource (m,p)\n\nforeign import ccall safe \"ogr_api.h OGRReleaseDataSource\"\n c_releaseDatasource :: Ptr (Datasource s t a) -> IO ()\n\n\n{#pointer OGRLayerH as Layer newtype nocode#}\n\nnewtype (Layer s (t::AccessMode) a)\n = Layer (Mutex, Ptr (Layer s t a))\n\nunLayer :: Layer s t a -> Ptr (Layer s t a)\nunLayer (Layer (_,p)) = p\n\nwithLockedLayerPtr\n :: Layer s t a -> (Ptr (Layer s t a) -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\ngetLayer :: Int -> Datasource s t a -> GDAL s (Layer s t a)\ngetLayer layer (Datasource (m,dp)) = liftIO $ do\n p <- throwIfError \"getLayer\" (c_getLayer dp (fromIntegral layer))\n when (p==nullPtr) $ throwBindingException (InvalidLayerIndex layer)\n return (Layer (m, p))\n\nforeign import ccall safe \"ogr_api.h OGR_DS_GetLayer\" c_getLayer\n :: Ptr (Datasource s t a) -> CInt -> IO (Ptr (Layer s t a))\n\ngetLayerByName :: String -> Datasource s t a -> GDAL s (Layer s t a)\ngetLayerByName layer (Datasource (m,dp)) = liftIO $\n withCString layer $ \\lyr -> do\n p <- throwIfError \"getLayerByName\" (c_getLayerByName dp lyr)\n when (p==nullPtr) $ throwBindingException (InvalidLayerName layer)\n return (Layer (m,p))\n\nforeign import ccall safe \"ogr_api.h OGR_DS_GetLayerByName\" c_getLayerByName\n :: Ptr (Datasource s t a) -> CString -> IO (Ptr (Layer s t a))\n\n\nlayerCount :: Datasource s t a -> GDAL s Int\nlayerCount = liftM fromIntegral . liftIO . c_getLayerCount . unDatasource\n\nforeign import ccall unsafe \"ogr_api.h OGR_DS_GetLayerCount\" c_getLayerCount\n :: Ptr (Datasource s t a) -> IO CInt\n\ndatasourceName :: Datasource s t a -> GDAL s String\ndatasourceName = liftIO . (peekCString <=< c_getName . unDatasource)\n\nforeign import ccall unsafe \"ogr_api.h OGR_DS_GetName\" c_getName\n :: Ptr (Datasource s t a) -> IO CString\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> String -> Maybe ROGeometry -> RODatasource s a\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(Datasource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullPtr) $ throwBindingException NullLayer\n registerFinalizer (c_releaseResultSet dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n withLockedDatasourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n withCString query $ \\sQuery ->\n throwIfError \"executeSQL\" (c_executeSQL dsPtr sQuery sFilter sDialect)\n\nforeign import ccall safe \"ogr_api.h OGR_DS_ExecuteSQL\"\n c_executeSQL\n :: Ptr (RODatasource s a) -> CString -> Ptr ROGeometry -> CString\n -> IO (Ptr (ROLayer s a))\n\nforeign import ccall safe \"ogr_api.h OGR_DS_ReleaseResultSet\"\n c_releaseResultSet\n :: Ptr (RODatasource s a) -> Ptr (ROLayer s a) -> IO ()\n\n\n\nnewtype Geometry (t::AccessMode) = Geometry (ForeignPtr (Geometry t))\n\nwithMaybeGeometry :: Maybe (Geometry t) -> (Ptr (Geometry t) -> IO a) -> IO a\nwithMaybeGeometry (Just (Geometry ptr)) = withForeignPtr ptr\nwithMaybeGeometry Nothing = ($ nullPtr)\n\nwithGeometry :: Geometry t -> (Ptr (Geometry t) -> IO a) -> IO a\nwithGeometry (Geometry ptr) = withForeignPtr ptr\n\ntype ROGeometry = Geometry ReadOnly\ntype RWGeometry = Geometry ReadWrite\n\nforeign import ccall \"ogr_api.h &OGR_G_DestroyGeometry\"\n c_destroyGeometry :: FunPtr (Ptr (Geometry t) -> IO ())\n\nnewGeometryHandle :: Ptr (Geometry t) -> IO (Geometry t)\nnewGeometryHandle p\n | p==nullPtr = throwBindingException NullGeometry\n | otherwise = Geometry <$> newForeignPtr c_destroyGeometry p\n\ncreateFromWkb\n :: ByteString -> Maybe SpatialReference -> Either OGRError ROGeometry\ncreateFromWkb bs = unsafePerformIO . createFromWkbIO bs\n\ncreateFromWkbIO\n :: ByteString -> Maybe SpatialReference -> IO (Either OGRError (Geometry t))\ncreateFromWkbIO bs mSrs =\n alloca $ \\gPtr ->\n unsafeUseAsCStringLen bs $ \\(sPtr, len) ->\n withMaybeSpatialReference mSrs $ \\srs ->\n checkOGRError\n (c_createFromWkb sPtr srs gPtr (fromIntegral len))\n (peek gPtr >>= newGeometryHandle)\n\nforeign import ccall unsafe \"ogr_api.h OGR_G_CreateFromWkb\"\n c_createFromWkb ::\n CString -> Ptr SpatialReference -> Ptr (Ptr (Geometry t)) -> CInt -> IO CInt\n\n\ncreateFromWkt\n :: ByteString -> Maybe SpatialReference -> Either OGRError ROGeometry\ncreateFromWkt bs = unsafePerformIO . createFromWktIO bs\n\ncreateFromWktIO\n :: ByteString -> Maybe SpatialReference -> IO (Either OGRError (Geometry t))\ncreateFromWktIO bs mSrs =\n alloca $ \\gPtr ->\n alloca $ \\sPtrPtr ->\n unsafeUseAsCString bs $ \\sPtr ->\n withMaybeSpatialReference mSrs $ \\srs ->\n checkOGRError\n (poke sPtrPtr sPtr >> c_createFromWkt sPtrPtr srs gPtr)\n (peek gPtr >>= newGeometryHandle)\n\nforeign import ccall unsafe \"ogr_api.h OGR_G_CreateFromWkt\"\n c_createFromWkt ::\n Ptr CString -> Ptr SpatialReference -> Ptr (Ptr (Geometry t)) -> IO CInt\n\nunsafeFreezeGeometry :: RWGeometry -> ROGeometry\nunsafeFreezeGeometry = coerce\n\nunsafeThawGeometry :: RWGeometry -> ROGeometry\nunsafeThawGeometry = coerce\n\nwithMaybeSpatialReference\n :: Maybe SpatialReference -> (Ptr SpatialReference -> IO a) -> IO a\nwithMaybeSpatialReference Nothing = ($ nullPtr)\nwithMaybeSpatialReference (Just s) = withSpatialReference s\n\npeekAndPack :: Ptr CString -> IO ByteString\npeekAndPack = peek >=> packCString\n\nexportToWktIO :: Geometry t -> IO ByteString\nexportToWktIO g = withGeometry g $ \\gPtr -> alloca $ \\sPtrPtr -> do\n void $ {#call OGR_G_ExportToWkt as ^ #} (castPtr gPtr) sPtrPtr\n peekAndPack sPtrPtr\n\nexportToWkt :: ROGeometry -> ByteString\nexportToWkt = unsafePerformIO . exportToWktIO\n\nexportToWkbIO :: WkbByteOrder -> Geometry t -> IO ByteString\nexportToWkbIO bo g = withGeometry g $ \\gPtr -> do\n len <- liftM fromIntegral ({#call OGR_G_WkbSize as ^ #} (castPtr gPtr))\n buf <- mallocBytes len\n void $ {#call OGR_G_ExportToWkb as ^ #} (castPtr gPtr) (fromEnumC bo) buf\n unsafePackMallocCStringLen (castPtr buf, len)\n\nexportToWkb :: WkbByteOrder -> ROGeometry -> ByteString\nexportToWkb bo = unsafePerformIO . exportToWkbIO bo\n\ngeomEqIO :: Geometry t -> Geometry t1 -> IO Bool\ngeomEqIO a b = withGeometry a $ \\aPtr -> withGeometry b $ \\bPtr ->\n liftM toBool ({#call OGR_G_Equals as ^#} (castPtr aPtr) (castPtr bPtr))\n\ninstance Show ROGeometry where\n show = unpack . exportToWkt\n\ninstance Eq ROGeometry where\n a == b = unsafePerformIO (geomEqIO a b)\n\n{#enum OGRwkbGeometryType as GeometryType {underscoreToCase}#}\n\ninstance Show GeometryType where\n show s = unsafePerformIO $\n {#call unsafe OGRGeometryTypeToName as ^#} s' >>= peekCString\n where s' = fromEnumC s\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"07e6089d4f48bee19096ad2496f2b1e2ac671864","subject":"change for new cudd version","message":"change for new cudd version\n","repos":"maweki\/haskell_cudd,adamwalker\/haskell_cudd","old_file":"CuddReorder.chs","new_file":"CuddReorder.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadSiftMaxVar,\n cuddSetSiftMaxVar,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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\nimport Control.Monad.ST.Lazy\n\nimport CuddInternal\nimport CuddHook\n\n#include \n#include \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> STDdManager s u -> ST s j\nreadIntegral f (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> STDdManager s u -> i -> ST s ()\nsetIntegral f (STDdManager m) v = unsafeIOToST $ f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> STDdManager s u -> ST s f\nreadFloat f (STDdManager m) = unsafeIOToST $ liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> STDdManager s u -> r -> ST s ()\nsetFloat f (STDdManager m) v = unsafeIOToST $ f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: STDdManager s u -> ST s (Int, CuddReorderingType)\ncuddReorderingStatus (STDdManager m) = unsafeIOToST $ do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: STDdManager s u -> CuddReorderingType -> ST s ()\ncuddAutodynEnable (STDdManager m) t = unsafeIOToST $ c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: STDdManager s u -> ST s ()\ncuddAutodynDisable (STDdManager m) = unsafeIOToST $ c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: STDdManager s u -> CuddReorderingType -> Int -> ST s Int\ncuddReduceHeap (STDdManager m) typ minsize = unsafeIOToST $ liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: STDdManager s u -> Int -> Int -> Int -> ST s (Ptr ())\ncuddMakeTreeNode (STDdManager m) low size typ = unsafeIOToST $ do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: STDdManager s u -> ST s Int\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CUInt)\n\ncuddReadReorderings :: STDdManager s u -> ST s Int\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: STDdManager s u -> ST s Int\ncuddEnableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: STDdManager s u -> ST s Int\ncuddDisableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: STDdManager s u -> ST s Int\ncuddReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: STDdManager s u -> ST s Int\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: STDdManager s u -> ST s Int\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: STDdManager s u -> ST s ()\ncuddTurnOffCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: STDdManager s u -> ST s ()\ncuddTurnOnCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: STDdManager s u -> ST s Int\ncuddDeadAreCounted (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: STDdManager s u -> ST s Int\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: STDdManager s u -> ST s Int\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxVar :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: STDdManager s u -> ST s Int\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: STDdManager s u -> Int -> ST s ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: STDdManager s u -> ST s Double\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: STDdManager s u -> ST s Double\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: STDdManager s u -> ST s Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: STDdManager s u -> Int -> ST s ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: STDdManager s u -> ST s Int\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: STDdManager s u -> Int -> ST s ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: STDdManager s u -> ST s Int\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: STDdManager s u -> Int -> ST s ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: STDdManager s u -> ST s Int\nregReordGCHook m = do\n hk <- unsafeIOToST $ makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadSiftMaxVar,\n cuddSetSiftMaxVar,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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\nimport Control.Monad.ST.Lazy\n\nimport CuddInternal\nimport CuddHook\n\n#include \n#include \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> STDdManager s u -> ST s j\nreadIntegral f (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> STDdManager s u -> i -> ST s ()\nsetIntegral f (STDdManager m) v = unsafeIOToST $ f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> STDdManager s u -> ST s f\nreadFloat f (STDdManager m) = unsafeIOToST $ liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> STDdManager s u -> r -> ST s ()\nsetFloat f (STDdManager m) v = unsafeIOToST $ f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: STDdManager s u -> ST s (Int, CuddReorderingType)\ncuddReorderingStatus (STDdManager m) = unsafeIOToST $ do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: STDdManager s u -> CuddReorderingType -> ST s ()\ncuddAutodynEnable (STDdManager m) t = unsafeIOToST $ c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: STDdManager s u -> ST s ()\ncuddAutodynDisable (STDdManager m) = unsafeIOToST $ c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: STDdManager s u -> CuddReorderingType -> Int -> ST s Int\ncuddReduceHeap (STDdManager m) typ minsize = unsafeIOToST $ liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: STDdManager s u -> Int -> Int -> Int -> ST s (Ptr ())\ncuddMakeTreeNode (STDdManager m) low size typ = unsafeIOToST $ do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: STDdManager s u -> ST s Int\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: STDdManager s u -> ST s Int\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: STDdManager s u -> ST s Int\ncuddEnableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: STDdManager s u -> ST s Int\ncuddDisableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: STDdManager s u -> ST s Int\ncuddReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: STDdManager s u -> ST s Int\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: STDdManager s u -> ST s Int\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: STDdManager s u -> ST s ()\ncuddTurnOffCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: STDdManager s u -> ST s ()\ncuddTurnOnCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: STDdManager s u -> ST s Int\ncuddDeadAreCounted (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: STDdManager s u -> ST s Int\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: STDdManager s u -> ST s Int\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxVar :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: STDdManager s u -> ST s Int\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: STDdManager s u -> Int -> ST s ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: STDdManager s u -> ST s Double\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: STDdManager s u -> ST s Double\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: STDdManager s u -> ST s Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: STDdManager s u -> Int -> ST s ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: STDdManager s u -> ST s Int\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: STDdManager s u -> Int -> ST s ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: STDdManager s u -> ST s Int\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: STDdManager s u -> Int -> ST s ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: STDdManager s u -> ST s Int\nregReordGCHook m = do\n hk <- unsafeIOToST $ makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"a6ab59f9086c4f7ba190ec869cc5be960ba89119","subject":"Documentation fixes","message":"Documentation fixes\n","repos":"hamishmack\/haskell-gi-base,hamishmack\/haskell-gi,ford-prefect\/haskell-gi,hamishmack\/haskell-gi,ford-prefect\/haskell-gi","old_file":"GI\/Utils\/GError.chs","new_file":"GI\/Utils\/GError.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}\n\n-- | To catch GError exceptions use the\n-- catchGError* or handleGError* functions. They work in a similar\n-- way to the standard 'Control.Exception.catch' and\n-- 'Control.Exception.handle' functions.\n--\n-- To catch just a single specific error use 'catchGErrorJust' \\\/\n-- 'handleGErrorJust'. To catch any error in a particular error domain\n-- use 'catchGErrorJustDomain' \\\/ 'handleGErrorJustDomain'\n--\n-- For convenience, generated code also includes specialized variants\n-- of 'catchGErrorJust' \\\/ 'handleGErrorJust' for each error type. For\n-- example, for errors of type 'GI.GdkPixbuf.PixbufError' one could\n-- invoke 'GI.GdkPixbuf.catchPixbufError' \\\/\n-- 'GI.GdkPixbuf.handlePixbufError'. The definition is simply\n--\n-- > catchPixbufError :: IO a -> (PixbufError -> GErrorMessage -> IO a) -> IO a\n-- > catchPixbufError = catchGErrorJustDomain\n--\n-- Notice that the type is suitably specialized, so only\n-- errors of type 'GI.GdkPixbuf.PixbufError' will be caught.\nmodule GI.Utils.GError\n (\n -- * Unpacking GError\n --\n GError(..)\n , gerrorDomain\n , gerrorCode\n , gerrorMessage\n\n , GErrorDomain\n , GErrorCode\n , GErrorMessage\n\n -- * Catching GError exceptions\n , catchGErrorJust\n , catchGErrorJustDomain\n\n , handleGErrorJust\n , handleGErrorJustDomain\n\n -- * Creating new 'GError's\n , gerrorNew\n\n -- * Implementation specific details\n -- | The following are used in the implementation\n -- of the bindings, and are in general not necessary for using the\n -- API.\n , GErrorClass(..)\n\n , propagateGError\n , checkGError\n\n ) where\n\n#if __GLASGOW_HASKELL__ < 710\nimport Control.Applicative ((<$>))\n#endif\n\nimport Foreign (poke, peek)\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr)\nimport Foreign.Ptr (Ptr, plusPtr, nullPtr)\nimport Foreign.C\nimport Control.Exception\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\n\nimport GI.Utils.BasicTypes (BoxedObject(..), GType(..))\nimport GI.Utils.BasicConversions (withTextCString, cstringToText)\nimport GI.Utils.ManagedPtr (wrapBoxed)\nimport GI.Utils.Utils (allocMem, freeMem)\n\n#include \n\n-- | A GError, consisting of a domain, code and a human readable\n-- message. These can be accessed by 'gerrorDomain', 'gerrorCode' and\n-- 'gerrorMessage' below.\nnewtype GError = GError (ForeignPtr GError)\n deriving (Typeable, Show)\n\ninstance Exception GError\n\nforeign import ccall \"g_error_get_type\" g_error_get_type :: IO GType\n\ninstance BoxedObject GError where\n boxedType _ = g_error_get_type\n\n-- | A GQuark.\ntype GQuark = {# type GQuark #}\n\n-- | A code used to identify the \"namespace\" of the error. Within each error\n-- domain all the error codes are defined in an enumeration. Each gtk\\\/gnome\n-- module that uses GErrors has its own error domain. The rationale behind\n-- using error domains is so that each module can organise its own error codes\n-- without having to coordinate on a global error code list.\ntype GErrorDomain = GQuark\n\n-- | A code to identify a specific error within a given 'GErrorDomain'. Most of\n-- time you will not need to deal with this raw code since there is an\n-- enumeration type for each error domain. Of course which enumeration to use\n-- depends on the error domain, but if you use 'catchGErrorJustDomain' or\n-- 'handleGErrorJustDomain', this is worked out for you automatically.\ntype GErrorCode = {# type gint #}\n\n-- | A human readable error message.\ntype GErrorMessage = Text\n\nforeign import ccall \"g_error_new_literal\" g_error_new_literal ::\n GQuark -> GErrorCode -> CString -> IO (Ptr GError)\n\n-- | Create a new 'GError'.\ngerrorNew :: GErrorDomain -> GErrorCode -> GErrorMessage -> IO GError\ngerrorNew domain code message =\n withTextCString message $ \\cstring ->\n g_error_new_literal domain code cstring >>= wrapBoxed GError\n\n-- | Return the domain for the given `GError`. This is a GQuark, a\n-- textual representation can be obtained with\n-- `GI.GLib.quarkToString`.\ngerrorDomain :: GError -> IO GQuark\ngerrorDomain (GError fptr) =\n withForeignPtr fptr $ \\ptr ->\n peek $ ptr `plusPtr` {# offsetof GError->domain #}\n\n-- | The numeric code for the given `GError`.\ngerrorCode :: GError -> IO GErrorCode\ngerrorCode (GError fptr) =\n withForeignPtr fptr $ \\ptr ->\n peek $ ptr `plusPtr` {# offsetof GError->code #}\n\n-- | A text message describing the `GError`.\ngerrorMessage :: GError -> IO GErrorMessage\ngerrorMessage (GError fptr) =\n withForeignPtr fptr $ \\ptr ->\n (peek $ ptr `plusPtr` {# offsetof GError->message #}) >>= cstringToText\n\n-- | Each error domain's error enumeration type should be an instance of this\n-- class. This class helps to hide the raw error and domain codes from the\n-- user.\n--\n-- Example for 'GI.GdkPixbuf.PixbufError':\n--\n-- > instance GErrorClass PixbufError where\n-- > gerrorClassDomain _ = \"gdk-pixbuf-error-quark\"\n--\nclass Enum err => GErrorClass err where\n gerrorClassDomain :: err -> Text -- ^ This must not use the value of its\n -- parameter so that it is safe to pass\n -- 'undefined'.\n\nforeign import ccall unsafe \"g_quark_try_string\" g_quark_try_string ::\n CString -> IO GQuark\n\n-- | Given the string representation of an error domain returns the\n-- corresponding error quark.\ngErrorQuarkFromDomain :: Text -> IO GQuark\ngErrorQuarkFromDomain domain = withTextCString domain g_quark_try_string\n\n-- | This will catch just a specific GError exception. If you need to catch a\n-- range of related errors, 'catchGErrorJustDomain' is probably more\n-- appropriate. Example:\n--\n-- > do image <- catchGErrorJust PixbufErrorCorruptImage\n-- > loadImage\n-- > (\\errorMessage -> do log errorMessage\n-- > return mssingImagePlaceholder)\n--\ncatchGErrorJust :: GErrorClass err => err -- ^ The error to catch\n -> IO a -- ^ The computation to run\n -> (GErrorMessage -> IO a) -- ^ Handler to invoke if\n -- an exception is raised\n -> IO a\ncatchGErrorJust code action handler = do\n domainQuark <- gErrorQuarkFromDomain $ gerrorClassDomain code\n catch action (handler' domainQuark)\n where handler' quark gerror = do\n domain <- gerrorDomain gerror\n code' <- gerrorCode gerror\n if domain == quark && code' == (fromIntegral . fromEnum) code\n then gerrorMessage gerror >>= handler\n else throw gerror -- Pass it on\n\n-- | Catch all GErrors from a particular error domain. The handler function\n-- should just deal with one error enumeration type. If you need to catch\n-- errors from more than one error domain, use this function twice with an\n-- appropriate handler functions for each.\n--\n-- > catchGErrorJustDomain\n-- > loadImage\n-- > (\\err message -> case err of\n-- > PixbufErrorCorruptImage -> ...\n-- > PixbufErrorInsufficientMemory -> ...\n-- > PixbufErrorUnknownType -> ...\n-- > _ -> ...)\n--\ncatchGErrorJustDomain :: forall err a. GErrorClass err =>\n IO a -- ^ The computation to run\n -> (err -> GErrorMessage -> IO a) -- ^ Handler to invoke if an exception is raised\n -> IO a\ncatchGErrorJustDomain action handler = do\n domainQuark <- gErrorQuarkFromDomain $ gerrorClassDomain (undefined::err)\n catch action (handler' domainQuark)\n where handler' quark gerror = do\n domain <- gerrorDomain gerror\n if domain == quark\n then do\n code <- (toEnum . fromIntegral) <$> gerrorCode gerror\n msg <- gerrorMessage gerror\n handler code msg\n else throw gerror\n\n-- | A verson of 'handleGErrorJust' with the arguments swapped around.\nhandleGErrorJust :: GErrorClass err => err -> (GErrorMessage -> IO a) -> IO a -> IO a\nhandleGErrorJust code = flip (catchGErrorJust code)\n\n-- | A verson of 'catchGErrorJustDomain' with the arguments swapped around.\nhandleGErrorJustDomain :: GErrorClass err => (err -> GErrorMessage -> IO a) -> IO a -> IO a\nhandleGErrorJustDomain = flip catchGErrorJustDomain\n\n-- | Run the given function catching possible 'GError's in its\n-- execution. If a 'GError' is emitted this throws the corresponding\n-- exception.\npropagateGError :: (Ptr (Ptr GError) -> IO a) -> IO a\npropagateGError f = checkGError f throw\n\n-- | Like 'propagateGError', but allows to specify a custom handler\n-- instead of just throwing the exception.\ncheckGError :: (Ptr (Ptr GError) -> IO a) -> (GError -> IO a) -> IO a\ncheckGError f handler = do\n gerrorPtr <- allocMem\n poke gerrorPtr nullPtr\n result <- f gerrorPtr\n gerror <- peek gerrorPtr\n freeMem gerrorPtr\n if gerror \/= nullPtr\n then wrapBoxed GError gerror >>= handler\n else return result\n","old_contents":"{-# LANGUAGE DeriveDataTypeable, ScopedTypeVariables #-}\n\n-- | To catch GError exceptions use the\n-- catchGError* or handleGError* functions. They work in a similar\n-- way to the standard 'Control.Exception.catch' and\n-- 'Control.Exception.handle' functions.\n--\n-- To catch just a single specific error use 'catchGErrorJust' \\\/\n-- 'handleGErrorJust'. To catch any error in a particular error domain\n-- use 'catchGErrorJustDomain' \\\/ 'handleGErrorJustDomain'\n--\n-- For convenience, generated code also includes specialized variants\n-- of 'catchGErrorJust' \\\/ 'handleGErrorJust' for each error type. For\n-- example, for errors of type 'GI.GdkPixbuf.PixbufError' one could\n-- invoke 'GI.GdkPixbuf.catchPixbufError' \\\/\n-- 'GI.GdkPixbuf.handlePixbufError'. The definition is simply\n--\n-- > catchPixbufError :: IO a -> (PixbufError -> GErrorMessage -> IO a) -> IO a\n-- > catchPixbufError = catchGErrorJustDomain\n--\n-- Notice that the type is suitably specialized, so only\n-- errors of type 'GI.GdkPixbuf.PixbufError' will be caught.\nmodule GI.Utils.GError\n (\n -- * Unpacking GError\n --\n GError(..)\n , gerrorDomain\n , gerrorCode\n , gerrorMessage\n\n , GErrorDomain\n , GErrorCode\n , GErrorMessage\n\n -- * Catching GError exceptions\n , catchGErrorJust\n , catchGErrorJustDomain\n\n , handleGErrorJust\n , handleGErrorJustDomain\n\n -- * Creating new 'GError's\n , gerrorNew\n\n -- * Implementation specific details\n -- | The following are used in the implementation\n -- of the bindings, and are in general not necessary for using the\n -- API.\n , GErrorClass(..)\n\n , propagateGError\n , checkGError\n\n ) where\n\n#if __GLASGOW_HASKELL__ < 710\nimport Control.Applicative ((<$>))\n#endif\n\nimport Foreign (poke, peek)\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr)\nimport Foreign.Ptr (Ptr, plusPtr, nullPtr)\nimport Foreign.C\nimport Control.Exception\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\n\nimport GI.Utils.BasicTypes (BoxedObject(..), GType(..))\nimport GI.Utils.BasicConversions (withTextCString, cstringToText)\nimport GI.Utils.ManagedPtr (wrapBoxed)\nimport GI.Utils.Utils (allocMem, freeMem)\n\n#include \n\n-- | A GError, consisting of a domain, code and a human readable\n-- message. These can be accessed by 'gerrorDomain', 'gerrorCode' and\n-- 'gerrorMessage' below.\nnewtype GError = GError (ForeignPtr GError)\n deriving (Typeable, Show)\n\ninstance Exception GError\n\nforeign import ccall \"g_error_get_type\" g_error_get_type :: IO GType\n\ninstance BoxedObject GError where\n boxedType _ = g_error_get_type\n\n-- | A GQuark.\ntype GQuark = {# type GQuark #}\n\n-- | A code used to identify the \\'namespace\\' of the error. Within each error\n-- domain all the error codes are defined in an enumeration. Each gtk\\\/gnome\n-- module that uses GErrors has its own error domain. The rationale behind\n-- using error domains is so that each module can organise its own error codes\n-- without having to coordinate on a global error code list.\ntype GErrorDomain = GQuark\n\n-- | A code to identify a specific error within a given 'GErrorDomain'. Most of\n-- time you will not need to deal with this raw code since there is an\n-- enumeration type for each error domain. Of course which enumeraton to use\n-- depends on the error domain, but if you use 'catchGErrorJustDomain' or\n-- 'handleGErrorJustDomain', this is worked out for you automatically.\ntype GErrorCode = {# type gint #}\n\n-- | A human readable error message.\ntype GErrorMessage = Text\n\nforeign import ccall \"g_error_new_literal\" g_error_new_literal ::\n GQuark -> GErrorCode -> CString -> IO (Ptr GError)\n\n-- | Create a new 'GError'.\ngerrorNew :: GErrorDomain -> GErrorCode -> GErrorMessage -> IO GError\ngerrorNew domain code message =\n withTextCString message $ \\cstring ->\n g_error_new_literal domain code cstring >>= wrapBoxed GError\n\n-- | Return the domain for the given `GError`. This is a GQuark, a\n-- textual representation can be obtained with\n-- `GI.GLib.quarkToString`.\ngerrorDomain :: GError -> IO GQuark\ngerrorDomain (GError fptr) =\n withForeignPtr fptr $ \\ptr ->\n peek $ ptr `plusPtr` {# offsetof GError->domain #}\n\n-- | The numeric code for the given `GError`.\ngerrorCode :: GError -> IO GErrorCode\ngerrorCode (GError fptr) =\n withForeignPtr fptr $ \\ptr ->\n peek $ ptr `plusPtr` {# offsetof GError->code #}\n\n-- | A text message describing the `GError`.\ngerrorMessage :: GError -> IO GErrorMessage\ngerrorMessage (GError fptr) =\n withForeignPtr fptr $ \\ptr ->\n (peek $ ptr `plusPtr` {# offsetof GError->message #}) >>= cstringToText\n\n-- | Each error domain's error enumeration type should be an instance of this\n-- class. This class helps to hide the raw error and domain codes from the\n-- user.\n--\n-- Example for 'GI.GdkPixbuf.PixbufError':\n--\n-- > instance GErrorClass PixbufError where\n-- > gerrorClassDomain _ = \"gdk-pixbuf-error-quark\"\n--\nclass Enum err => GErrorClass err where\n gerrorClassDomain :: err -> Text -- ^ This must not use the value of its\n -- parameter so that it is safe to pass\n -- 'undefined'.\n\nforeign import ccall unsafe \"g_quark_try_string\" g_quark_try_string ::\n CString -> IO GQuark\n\n-- | Given the string representation of an error domain returns the\n-- corresponding error quark.\ngErrorQuarkFromDomain :: Text -> IO GQuark\ngErrorQuarkFromDomain domain = withTextCString domain g_quark_try_string\n\n-- | This will catch just a specific GError exception. If you need to catch a\n-- range of related errors, 'catchGErrorJustDomain' is probably more\n-- appropriate. Example:\n--\n-- > do image <- catchGErrorJust PixbufErrorCorruptImage\n-- > loadImage\n-- > (\\errorMessage -> do log errorMessage\n-- > return mssingImagePlaceholder)\n--\ncatchGErrorJust :: GErrorClass err => err -- ^ The error to catch\n -> IO a -- ^ The computation to run\n -> (GErrorMessage -> IO a) -- ^ Handler to invoke if\n -- an exception is raised\n -> IO a\ncatchGErrorJust code action handler = do\n domainQuark <- gErrorQuarkFromDomain $ gerrorClassDomain code\n catch action (handler' domainQuark)\n where handler' quark gerror = do\n domain <- gerrorDomain gerror\n code' <- gerrorCode gerror\n if domain == quark && code' == (fromIntegral . fromEnum) code\n then gerrorMessage gerror >>= handler\n else throw gerror -- Pass it on\n\n-- | Catch all GErrors from a particular error domain. The handler function\n-- should just deal with one error enumeration type. If you need to catch\n-- errors from more than one error domain, use this function twice with an\n-- appropriate handler functions for each.\n--\n-- > catchGErrorJustDomain\n-- > loadImage\n-- > (\\err message -> case err of\n-- > PixbufErrorCorruptImage -> ...\n-- > PixbufErrorInsufficientMemory -> ...\n-- > PixbufErrorUnknownType -> ...\n-- > _ -> ...)\n--\ncatchGErrorJustDomain :: forall err a. GErrorClass err =>\n IO a -- ^ The computation to run\n -> (err -> GErrorMessage -> IO a) -- ^ Handler to invoke if an exception is raised\n -> IO a\ncatchGErrorJustDomain action handler = do\n domainQuark <- gErrorQuarkFromDomain $ gerrorClassDomain (undefined::err)\n catch action (handler' domainQuark)\n where handler' quark gerror = do\n domain <- gerrorDomain gerror\n if domain == quark\n then do\n code <- (toEnum . fromIntegral) <$> gerrorCode gerror\n msg <- gerrorMessage gerror\n handler code msg\n else throw gerror\n\n-- | A verson of 'handleGErrorJust' with the arguments swapped around.\nhandleGErrorJust :: GErrorClass err => err -> (GErrorMessage -> IO a) -> IO a -> IO a\nhandleGErrorJust code = flip (catchGErrorJust code)\n\n-- | A verson of 'catchGErrorJustDomain' with the arguments swapped around.\nhandleGErrorJustDomain :: GErrorClass err => (err -> GErrorMessage -> IO a) -> IO a -> IO a\nhandleGErrorJustDomain = flip catchGErrorJustDomain\n\n-- | Run the given function catching possible GErrors in its\n-- execution. If a GError is emitted this throws the corresponding\n-- exception.\npropagateGError :: (Ptr (Ptr GError) -> IO a) -> IO a\npropagateGError f = checkGError f throw\n\n-- | Like propagateGError, but allows to specify a custom handler\n-- instead of just throwing the exception.\ncheckGError :: (Ptr (Ptr GError) -> IO a) -> (GError -> IO a) -> IO a\ncheckGError f handler = do\n gerrorPtr <- allocMem\n poke gerrorPtr nullPtr\n result <- f gerrorPtr\n gerror <- peek gerrorPtr\n freeMem gerrorPtr\n if gerror \/= nullPtr\n then wrapBoxed GError gerror >>= handler\n else return result\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"dcf9a2d4e3b0e574fa72685a4531420e91b2a989","subject":"Fixed blit","message":"Fixed blit\n","repos":"BeautifulDestinations\/CV,aleator\/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 #-}\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 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\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","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 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\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 blitImg#} 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":"77a598819bb1892631b3618d9bffd6e07a19a4f7","subject":"oops, also export these","message":"oops, also export these\n\nIgnore-this: 3eba30abdf37ffed35ff3f9e909576b5\n\ndarcs-hash:20091207083756-9241b-f3504b0f4db3a786b86f0c0a2f74e155d58e7d54.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Stream.chs","new_file":"Foreign\/CUDA\/Driver\/Stream.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Stream\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Stream management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Stream\n (\n Stream, StreamFlags,\n withStream,\n create, destroy, finished, block\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\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-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *CUstream as Stream foreign newtype #}\nwithStream :: Stream -> (Ptr Stream -> IO a) -> IO a\n\nnewStream :: IO Stream\nnewStream = Stream `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\n\n\n--\n-- Possible option flags for stream initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata StreamFlags\n\ninstance Enum StreamFlags where\n\n--------------------------------------------------------------------------------\n-- Stream management\n--------------------------------------------------------------------------------\n\n--\n-- Create a new stream\n--\ncreate :: [StreamFlags] -> IO (Either String Stream)\ncreate flags =\n newStream >>= \\st -> withStream st $ \\s ->\n cuStreamCreate s flags >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right st\n Just e -> Left e\n\n{# fun unsafe cuStreamCreate\n { id `Ptr Stream'\n , combineBitMasks `[StreamFlags]' } -> `Status' cToEnum #}\n\n--\n-- Destroy a stream\n--\ndestroy :: Stream -> IO (Maybe String)\ndestroy st = withStream st $ \\s -> (nothingIfOk `fmap` cuStreamDestroy s)\n\n{# fun unsafe cuStreamDestroy\n { castPtr `Ptr Stream' } -> `Status' cToEnum #}\n\n\n--\n-- Check if all operations in the stream have completed\n--\nfinished :: Stream -> IO (Either String Bool)\nfinished st =\n withStream st $ \\s -> cuStreamQuery s >>= \\rv ->\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (describe rv)\n\n{# fun unsafe cuStreamQuery\n { castPtr `Ptr Stream' } -> `Status' cToEnum #}\n\n\n--\n-- Wait until the device has completed all operations in the Stream\n--\nblock :: Stream -> IO (Maybe String)\nblock st = withStream st $ \\s -> (nothingIfOk `fmap` cuStreamSynchronize s)\n\n{# fun unsafe cuStreamSynchronize\n { castPtr `Ptr Stream' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Stream\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Stream management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Stream\n (\n create, destroy, finished, block\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\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-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *CUstream as Stream foreign newtype #}\nwithStream :: Stream -> (Ptr Stream -> IO a) -> IO a\n\nnewStream :: IO Stream\nnewStream = Stream `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\n\n\n--\n-- Possible option flags for stream initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata StreamFlags\n\ninstance Enum StreamFlags where\n\n--------------------------------------------------------------------------------\n-- Stream management\n--------------------------------------------------------------------------------\n\n--\n-- Create a new stream\n--\ncreate :: [StreamFlags] -> IO (Either String Stream)\ncreate flags =\n newStream >>= \\st -> withStream st $ \\s ->\n cuStreamCreate s flags >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right st\n Just e -> Left e\n\n{# fun unsafe cuStreamCreate\n { id `Ptr Stream'\n , combineBitMasks `[StreamFlags]' } -> `Status' cToEnum #}\n\n--\n-- Destroy a stream\n--\ndestroy :: Stream -> IO (Maybe String)\ndestroy st = withStream st $ \\s -> (nothingIfOk `fmap` cuStreamDestroy s)\n\n{# fun unsafe cuStreamDestroy\n { castPtr `Ptr Stream' } -> `Status' cToEnum #}\n\n\n--\n-- Check if all operations in the stream have completed\n--\nfinished :: Stream -> IO (Either String Bool)\nfinished st =\n withStream st $ \\s -> cuStreamQuery s >>= \\rv ->\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (describe rv)\n\n{# fun unsafe cuStreamQuery\n { castPtr `Ptr Stream' } -> `Status' cToEnum #}\n\n\n--\n-- Wait until the device has completed all operations in the Stream\n--\nblock :: Stream -> IO (Maybe String)\nblock st = withStream st $ \\s -> (nothingIfOk `fmap` cuStreamSynchronize s)\n\n{# fun unsafe cuStreamSynchronize\n { castPtr `Ptr Stream' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5ea763246bb91dcc8d3c25ff9470690c03853034","subject":"implemented foldl' and foldlM' for efficient folding over an entire band's values","message":"implemented foldl' and foldlM' for efficient folding over an entire band's values\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 ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n , foldl'\n , foldlM'\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Band s t b' -> IO (Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Band s t b' -> IO (Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = reader band >>= mask\n where\n mask\n | hasFlag MaskPerDataset = useMaskBand\n | hasFlag MaskNoData = useNoData\n | hasFlag MaskAllValid = useAsIs\n | otherwise = useMaskBand\n hasFlag f = fromEnumC f .&. c_getMaskFlags band == fromEnumC f\n useAsIs = return . St.map Value\n useNoData vs = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand vs = do\n ms <- c_getMaskBand band >>= reader :: IO (Vector Word8)\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n len <- bandBlockLen band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s a b. GDALType a\n => ROBand s a -> (b -> Value a -> b) -> b -> GDAL s b\nfoldl' b f = foldlM' b (\\acc -> return . f acc)\n{-# INLINE foldl' #-}\n\nfoldlM'\n :: forall s a b. GDALType a\n => ROBand s a -> (b -> Value a -> IO b) -> b -> GDAL s b\nfoldlM' b f initialAcc = do\n (nx,ny) <- bandBlockCount b\n (sx,sy) <- bandBlockSize b\n (bx,by) <- bandSize b\n liftIO $ do\n mNodata <- c_bandNodataValue b\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n applyTo i j acc = f acc . toValue =<< peekElemOff ptr (j*sx+i)\n go1 !ox !oy !i !j !acc\n | x == bx = if j+1 < sy\n then go1 ox oy 0 (j+1) acc\n else return acc\n | y == by = return acc\n | i>= go1 ox oy (i+1) j\n | j+1>= go (i+1) j\n | j+1 RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n checkType b\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Band s t b' -> IO (Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Band s t b' -> IO (Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = reader band >>= mask\n where\n mask\n | hasFlag MaskPerDataset = useMaskBand\n | hasFlag MaskNoData = useNoData\n | hasFlag MaskAllValid = useAsIs\n | otherwise = useMaskBand\n hasFlag f = fromEnumC f .&. c_getMaskFlags band == fromEnumC f\n useAsIs = return . St.map Value\n useNoData vs = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand vs = do\n ms <- c_getMaskBand band >>= reader :: IO (Vector Word8)\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n len <- bandBlockLen band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n checkType b\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8e35d63f34245c56d19c1bdf679bbc63dd49acb8","subject":"safer isValidDatatype","message":"safer isValidDatatype\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{-# LANGUAGE RankNTypes #-}\n\nmodule OSGeo.GDAL.Internal (\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 -- 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 s a t) = Band (Ptr ((Band s a t)))\n\nunBand (Band b) = b\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s 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 destroy 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\ncreate\n :: forall t. HasDatatype t\n => String -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate'\n :: forall t. HasDatatype t\n => 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\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\n :: HasDatatype t\n => Int -> Int -> Int -> DriverOptions -> IO (Dataset ReadWrite 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 -> (forall s. Band s 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 s a t))\n\n\nbandDatatype :: (Band s a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s 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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s a t) -> CInt\n\n\nbandNodataValue :: (Band s 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 s a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s 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 s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s 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 s 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\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 s b a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand' = readBand\n\nreadBand :: forall s a b t. HasDatatype a\n => (Band s 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 s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall s a. HasDatatype a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall s a t. HasDatatype a\n => (RWBand s 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 s 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\n\nreadBandBlock\n :: forall s a t. HasDatatype t\n => Band s a t -> Int -> Int -> IOVector t\nreadBandBlock 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 s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock :: HasDatatype t => RWBand s t -> Int -> Int -> Vector t -> IO ()\nwriteBandBlock 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 s t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\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 s a t v. Typeable v\n => Band s a t -> v -> Bool\nisValidDatatype b v\n = let vt = typeOf v\n in case bandDatatype b of\n GDT_Byte -> vt == typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> vt == typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> vt == typeOf (undefined :: Vector Word32)\n GDT_Int16 -> vt == typeOf (undefined :: Vector Int16)\n GDT_Int32 -> vt == typeOf (undefined :: Vector Int32)\n GDT_Float32 -> vt == typeOf (undefined :: Vector Float)\n GDT_Float64 -> vt == typeOf (undefined :: Vector Double)\n GDT_CInt16 -> vt == typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> vt == typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> vt == typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> vt == typeOf (undefined :: Vector (GComplex Double))\n _ -> False\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{-# LANGUAGE RankNTypes #-}\n\nmodule OSGeo.GDAL.Internal (\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 -- 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 s a t) = Band (Ptr ((Band s a t)))\n\nunBand (Band b) = b\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s 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 destroy 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\ncreate\n :: forall t. HasDatatype t\n => String -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate'\n :: forall t. HasDatatype t\n => 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\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\n :: HasDatatype t\n => Int -> Int -> Int -> DriverOptions -> IO (Dataset ReadWrite 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 -> (forall s. Band s 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 s a t))\n\n\nbandDatatype :: (Band s a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s 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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s a t) -> CInt\n\n\nbandNodataValue :: (Band s 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 s a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s 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 s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s 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 s 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\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 s b a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand' = readBand\n\nreadBand :: forall s a b t. HasDatatype a\n => (Band s 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 s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall s a. HasDatatype a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall s a t. HasDatatype a\n => (RWBand s 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 s 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\n\nreadBandBlock\n :: forall s a t. HasDatatype t\n => Band s a t -> Int -> Int -> IOVector t\nreadBandBlock 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 s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock :: HasDatatype t => RWBand s t -> Int -> Int -> Vector t -> IO ()\nwriteBandBlock 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 s t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\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 s a t v. Typeable v\n => Band s 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":"6919e8e243c98558d91192f7984cd646d4ed608a","subject":"Use SourceLanguageClass replace SourceLanguage as function argument.","message":"Use SourceLanguageClass replace SourceLanguage as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.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) 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.SourceLanguage (\n-- * Description\n-- | 'SourceLanguage' encapsulates syntax and highlighting styles for a particular language. Use\n-- 'SourceLanguageManager' to obtain a 'SourceLanguage' instance, and\n-- 'sourceBufferSetLanguage' to apply it to a 'SourceBuffer'.\n\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n sourceLanguageGetStyleName,\n sourceLanguageGetStyleIds,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguageClass sl => sl\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} (toSourceLanguage sl) >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguageClass sl => sl \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} (toSourceLanguage sl) >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguageClass sl => sl \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} (toSourceLanguage sl) >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguageClass sl => sl \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} (toSourceLanguage sl)\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguageClass sl => sl \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or empty if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} (toSourceLanguage sl)) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguageClass sl => sl \n -> IO [String] -- ^ returns an array containing the mime types or empty if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} (toSourceLanguage sl)\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguageClass sl => sl \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} (toSourceLanguage sl)\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Returns the name of the style with ID @styleId@ defined by this language.\nsourceLanguageGetStyleName :: SourceLanguageClass sl => sl \n -> String -- ^ @styleId@ a style ID\n -> IO String -- ^ returns the name of the style with ID @styleId@ defined by this language or empty if the style has no name or there is no style with ID @styleId@ defined by this language. The returned string is owned by the language and must not be modified.\nsourceLanguageGetStyleName sl styleId =\n withUTFString styleId $ \\styleIdPtr ->\n {#call gtk_source_language_get_style_name#}\n (toSourceLanguage sl)\n styleIdPtr\n >>= peekUTFString\n\n-- | Returns the ids of the styles defined by this language.\nsourceLanguageGetStyleIds :: SourceLanguageClass sl => sl \n -> IO [String] -- ^ returns an array containing ids of the styles defined by this language or empty if no style is defined. \nsourceLanguageGetStyleIds sl = do\n globsArray <- {#call gtk_source_language_get_style_ids#} (toSourceLanguage sl)\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: SourceLanguageClass sl => ReadAttr sl Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: SourceLanguageClass sl => ReadAttr sl String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: SourceLanguageClass sl => ReadAttr sl String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: SourceLanguageClass sl => ReadAttr sl String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\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) 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.SourceLanguage (\n-- * Description\n-- | 'SourceLanguage' encapsulates syntax and highlighting styles for a particular language. Use\n-- 'SourceLanguageManager' to obtain a 'SourceLanguage' instance, and\n-- 'sourceBufferSetLanguage' to apply it to a 'SourceBuffer'.\n\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n sourceLanguageGetStyleName,\n sourceLanguageGetStyleIds,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguage\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguage \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguage \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguage \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or empty if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the mime types or empty if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Returns the name of the style with ID @styleId@ defined by this language.\nsourceLanguageGetStyleName :: SourceLanguage \n -> String -- ^ @styleId@ a style ID\n -> IO String -- ^ returns the name of the style with ID @styleId@ defined by this language or empty if the style has no name or there is no style with ID @styleId@ defined by this language. The returned string is owned by the language and must not be modified.\nsourceLanguageGetStyleName sl styleId =\n withUTFString styleId $ \\styleIdPtr ->\n {#call gtk_source_language_get_style_name#}\n sl\n styleIdPtr\n >>= peekUTFString\n\n-- | Returns the ids of the styles defined by this language.\nsourceLanguageGetStyleIds :: SourceLanguage \n -> IO [String] -- ^ returns an array containing ids of the styles defined by this language or empty if no style is defined. \nsourceLanguageGetStyleIds sl = do\n globsArray <- {#call gtk_source_language_get_style_ids#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"598d09f8ef809822f5767ecbce3f04521f9dcf54","subject":"gstreamer: hopefully fix takeObject & peekObject for real this time","message":"gstreamer: hopefully fix takeObject & peekObject for real this time\n\ntakeObject: to be used when a function returns an object that must be unreffed at GC.\n If the object has a floating reference, the float flag is removed.\n\npeekObject: to be used when an object must not be unreffed. A ref is added, and is\n removed at GC. The floating flag is not touched.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n cObjectRef cObject\n takeObject cObject\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat\n newForeignPtr (castPtr cObject) objectFinalizer\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f31bea39a08fd0f78ec1a8c37315387cb682be7c","subject":"Some skeletons for repository stuff","message":"Some skeletons for repository stuff\n","repos":"norm2782\/hgit2","old_file":"git2.chs","new_file":"git2.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.Primitive\nimport Foreign\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: Repository -> String -> IO ()\nopenRepo repo path = undefined -- git_repository_open\n\nopenRepoObjDir :: Repository -> String -> String -> String -> String -> IO (Maybe GitError)\nopenRepoObjDir repo dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: Repository -> String -> ObjDB -> String -> String -> IO (Maybe GitError)\nopenRepoObjDb repo dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> String -> Bool -> String -> IO (Maybe GitError)\ndiscover path startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Index -> Repository -> IO (Maybe GitError)\nindex idx repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.Primitive\nimport Foreign\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\n\nnewtype ODB = ODB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\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\nisEmpty :: Repository -> IO Bool\nisEmpty (Repository r) = return . toBool =<< {#call git_repository_is_empty#} r\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"524a2632f606a2a8b6ee04077cdbd00fac7dd02d","subject":"gstreamer: M.S.G.Core.Clock: a few small doc fixes","message":"gstreamer: M.S.G.Core.Clock: a few small doc fixes","repos":"vincenthz\/webkit","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":"dd36b2cea49870aacc3a51978a04820b25929d16","subject":"reuse datasetProjectionWkt","message":"reuse datasetProjectionWkt\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)\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 (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\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","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.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)\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 :: MonadIO m => Dataset s a t -> m (Maybe SpatialReference)\ndatasetProjection\n = liftIO\n . (maybeSpatialReferenceFromCString <=< {#call GetProjectionRef as ^#})\n . unDataset\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 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 (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\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 :: 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":"ccd573e6d1db154213494ce9e14f321ca4138b58","subject":"Exposed functions for menu item.","message":"Exposed functions for menu item.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Menu_Item.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Menu_Item.chs","new_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.FLTK.LowLevel.Fl_Menu_Item\n (\n menuItemNew,\n menuItemDestroy,\n menuItemNextWithStep,\n menuItemNext,\n menuItemFirst,\n menuItemLabel,\n menuItemSetLabel,\n menuItemSetLabelWithLabeltype,\n menuItemLabeltype,\n menuItemSetLabeltype,\n menuItemLabelcolor,\n menuItemSetLabelcolor,\n menuItemLabelfont,\n menuItemSetLabelfont,\n menuItemLabelsize,\n menuItemSetLabelsize,\n menuItemSetCallback,\n menuItemShortcut,\n menuItemSetShortcut,\n menuItemSubmenu,\n menuItemCheckbox,\n menuItemRadio,\n menuItemValue,\n menuItemSet,\n menuItemClear,\n menuItemSetonly,\n menuItemVisible,\n menuItemShow,\n menuItemHide,\n menuItemActive,\n menuItemActivate,\n menuItemDeactivate,\n menuItemActivevisible,\n menuItemMeasure,\n menuItemDrawWithT,\n menuItemDraw,\n menuItemFlags,\n menuItemSetFlags,\n menuItemText,\n menuItemPulldown,\n menuItemPopup,\n menuItemTestShortcut,\n menuItemFindShortcut,\n menuItemDoCallback,\n menuItemAdd,\n menuItemInsert,\n menuItemSize\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Menu_ItemC.h\"\nimport C2HS hiding (cFromEnum, unsafePerformIO, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n{# fun unsafe Fl_Menu_Item_New as new' { } -> `Ptr ()' id #}\nmenuItemNew :: IO (MenuItem a)\nmenuItemNew = new' >>= toObject\n\n{# fun unsafe Fl_Menu_Item_Destroy as destroy' { id `Ptr ()' } -> `()' id #}\nmenuItemDestroy :: MenuItem a -> IO ()\nmenuItemDestroy menu_item = withObject menu_item $ \\menu_itemPtr -> destroy' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_next_with_step as nextWithStep' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\nmenuItemNextWithStep :: MenuItem a -> Int -> IO (MenuItem a)\nmenuItemNextWithStep menu_item step =\n withObject menu_item $ \\menu_itemPtr -> nextWithStep' menu_itemPtr step >>= toObject\n\n{# fun unsafe Fl_Menu_Item_next as next' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuItemNext :: MenuItem a -> IO (Ptr ())\nmenuItemNext menu_item = withObject menu_item $ \\menu_itemPtr -> next' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_first as first' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuItemFirst :: MenuItem a -> IO (Ptr ())\nmenuItemFirst menu_item = withObject menu_item $ \\menu_itemPtr -> first' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_label as label' { id `Ptr ()' } -> `String' #}\nmenuItemLabel :: MenuItem a -> IO (String)\nmenuItemLabel menu_item = withObject menu_item $ \\menu_itemPtr -> label' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_label as setLabel' { id `Ptr ()',`String' } -> `()' #}\nmenuItemSetLabel :: MenuItem a -> String -> IO ()\nmenuItemSetLabel menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabel' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_set_label_with_labeltype as setLabelWithLabeltype' { id `Ptr ()',cFromEnum `Labeltype',`String' } -> `()' #}\nmenuItemSetLabelWithLabeltype :: MenuItem a -> Labeltype -> String -> IO ()\nmenuItemSetLabelWithLabeltype menu_item labeltype b = withObject menu_item $ \\menu_itemPtr -> setLabelWithLabeltype' menu_itemPtr labeltype b\n\n{# fun unsafe Fl_Menu_Item_labeltype as labeltype' { id `Ptr ()' } -> `Labeltype' cToEnum #}\nmenuItemLabeltype :: MenuItem a -> IO (Labeltype)\nmenuItemLabeltype menu_item = withObject menu_item $ \\menu_itemPtr -> labeltype' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_labeltype as setLabeltype' { id `Ptr ()',cFromEnum `Labeltype' } -> `()' #}\nmenuItemSetLabeltype :: MenuItem a -> Labeltype -> IO ()\nmenuItemSetLabeltype menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabeltype' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_labelcolor as labelcolor' { id `Ptr ()' } -> `Color' cToColor #}\nmenuItemLabelcolor :: MenuItem a -> IO (Color)\nmenuItemLabelcolor menu_item = withObject menu_item $ \\menu_itemPtr -> labelcolor' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_labelcolor as setLabelcolor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\nmenuItemSetLabelcolor :: MenuItem a -> Color -> IO ()\nmenuItemSetLabelcolor menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabelcolor' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_labelfont as labelfont' { id `Ptr ()' } -> `Font' cToFont #}\nmenuItemLabelfont :: MenuItem a -> IO (Font)\nmenuItemLabelfont menu_item = withObject menu_item $ \\menu_itemPtr -> labelfont' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_labelfont as setLabelfont' { id `Ptr ()',cFromFont `Font' } -> `()' #}\nmenuItemSetLabelfont :: MenuItem a -> Font -> IO ()\nmenuItemSetLabelfont menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabelfont' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_labelsize as labelsize' { id `Ptr ()' } -> `CInt' id #}\nmenuItemLabelsize :: MenuItem a -> IO (FontSize)\nmenuItemLabelsize menu_item = withObject menu_item $ \\menu_itemPtr -> labelsize' menu_itemPtr >>= return . FontSize\n\n{# fun unsafe Fl_Menu_Item_set_labelsize as setLabelsize' { id `Ptr ()', id `CInt' } -> `()' #}\nmenuItemSetLabelsize :: MenuItem a -> FontSize -> IO ()\nmenuItemSetLabelsize menu_item (FontSize pix) = withObject menu_item $ \\menu_itemPtr -> setLabelsize' menu_itemPtr pix\n\n{# fun unsafe Fl_Menu_Item_set_callback as setCallback' { id `Ptr ()', id `FunPtr CallbackWithUserDataPrim'} -> `()' #}\nmenuItemSetCallback :: MenuItem a -> (WidgetCallback b) -> IO ()\nmenuItemSetCallback menu_item c = withObject menu_item $ \\menu_itemPtr -> do\n ptr <- toWidgetCallbackPrim c\n setCallback' menu_itemPtr (castFunPtr ptr)\n\n{# fun unsafe Fl_Menu_Item_shortcut as shortcut' { id `Ptr ()' } -> `Int' #}\nmenuItemShortcut :: MenuItem a -> IO (Int)\nmenuItemShortcut menu_item = withObject menu_item $ \\menu_itemPtr -> shortcut' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_shortcut as setShortcut' { id `Ptr ()',`Int' } -> `()' #}\nmenuItemSetShortcut :: MenuItem a -> Int -> IO ()\nmenuItemSetShortcut menu_item s = withObject menu_item $ \\menu_itemPtr -> setShortcut' menu_itemPtr s\n\n{# fun unsafe Fl_Menu_Item_submenu as submenu' { id `Ptr ()' } -> `Int' #}\nmenuItemSubmenu :: MenuItem a -> IO (Int)\nmenuItemSubmenu menu_item = withObject menu_item $ \\menu_itemPtr -> submenu' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_checkbox as checkbox' { id `Ptr ()' } -> `Int' #}\nmenuItemCheckbox :: MenuItem a -> IO (Int)\nmenuItemCheckbox menu_item = withObject menu_item $ \\menu_itemPtr -> checkbox' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_radio as radio' { id `Ptr ()' } -> `Int' #}\nmenuItemRadio :: MenuItem a -> IO (Int)\nmenuItemRadio menu_item = withObject menu_item $ \\menu_itemPtr -> radio' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_value as value' { id `Ptr ()' } -> `Int' #}\nmenuItemValue :: MenuItem a -> IO (Int)\nmenuItemValue menu_item = withObject menu_item $ \\menu_itemPtr -> value' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set as set' { id `Ptr ()' } -> `()' #}\nmenuItemSet :: MenuItem a -> IO ()\nmenuItemSet menu_item = withObject menu_item $ \\menu_itemPtr -> set' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_clear as clear' { id `Ptr ()' } -> `()' #}\nmenuItemClear :: MenuItem a -> IO ()\nmenuItemClear menu_item = withObject menu_item $ \\menu_itemPtr -> clear' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_setonly as setonly' { id `Ptr ()' } -> `()' #}\nmenuItemSetonly :: MenuItem a -> IO ()\nmenuItemSetonly menu_item = withObject menu_item $ \\menu_itemPtr -> setonly' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_visible as visible' { id `Ptr ()' } -> `Int' #}\nmenuItemVisible :: MenuItem a -> IO (Int)\nmenuItemVisible menu_item = withObject menu_item $ \\menu_itemPtr -> visible' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_show as show' { id `Ptr ()' } -> `()' #}\nmenuItemShow :: MenuItem a -> IO ()\nmenuItemShow menu_item = withObject menu_item $ \\menu_itemPtr -> show' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_hide as hide' { id `Ptr ()' } -> `()' #}\nmenuItemHide :: MenuItem a -> IO ()\nmenuItemHide menu_item = withObject menu_item $ \\menu_itemPtr -> hide' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_active as active' { id `Ptr ()' } -> `Int' #}\nmenuItemActive :: MenuItem a -> IO (Int)\nmenuItemActive menu_item = withObject menu_item $ \\menu_itemPtr -> active' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_activate as activate' { id `Ptr ()' } -> `()' #}\nmenuItemActivate :: MenuItem a -> IO ()\nmenuItemActivate menu_item = withObject menu_item $ \\menu_itemPtr -> activate' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_deactivate as deactivate' { id `Ptr ()' } -> `()' #}\nmenuItemDeactivate :: MenuItem a -> IO ()\nmenuItemDeactivate menu_item = withObject menu_item $ \\menu_itemPtr -> deactivate' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_activevisible as activevisible' { id `Ptr ()' } -> `Int' #}\nmenuItemActivevisible :: MenuItem a -> IO (Int)\nmenuItemActivevisible menu_item = withObject menu_item $ \\menu_itemPtr -> activevisible' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_measure as measure' { id `Ptr ()',alloca- `Int' peekIntConv*,id `Ptr ()' } -> `()' #}\nmenuItemMeasure :: MenuItem a -> MenuPrim a -> IO (Int)\nmenuItemMeasure menu_item menu = withObject menu_item $ \\menu_itemPtr -> withObject menu $ \\menuPtr -> measure' menu_itemPtr menuPtr\n\n{# fun unsafe Fl_Menu_Item_draw_with_t as drawWithT' { id `Ptr ()',`Int',`Int',`Int',`Int',id `Ptr ()',`Int' } -> `()' #}\nmenuItemDrawWithT :: MenuItem a -> Rectangle -> MenuPrim a -> Int -> IO ()\nmenuItemDrawWithT menu_item rectangle menu t =\n let (x_pos', y_pos', width', height') = fromRectangle rectangle in\n withObject menu_item $ \\menu_itemPtr -> withObject menu $ \\menuPtr -> drawWithT' menu_itemPtr x_pos' y_pos' width' height' menuPtr t\n\n{# fun unsafe Fl_Menu_Item_draw as draw' { id `Ptr ()',`Int',`Int',`Int',`Int',id `Ptr ()' } -> `()' #}\nmenuItemDraw :: MenuItem a -> Rectangle -> MenuPrim a -> IO ()\nmenuItemDraw menu_item rectangle menu =\n let (x_pos', y_pos', width', height') = fromRectangle rectangle in\n withObject menu_item $ \\menu_itemPtr ->\n withObject menu $ \\menuPtr -> draw' menu_itemPtr x_pos' y_pos' width' height' menuPtr\n\n{# fun unsafe Fl_Menu_Item_flags as flags' { id `Ptr ()' } -> `Int' #}\nmenuItemFlags :: MenuItem a -> IO (Int)\nmenuItemFlags menu_item = withObject menu_item $ \\menu_itemPtr -> flags' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_flags as setFlags' { id `Ptr ()',`Int' } -> `()' #}\nmenuItemSetFlags :: MenuItem a -> Int -> IO ()\nmenuItemSetFlags menu_item flags = withObject menu_item $ \\menu_itemPtr -> setFlags' menu_itemPtr flags\n\n{# fun unsafe Fl_Menu_Item_text as text' { id `Ptr ()' } -> `String' #}\nmenuItemText :: MenuItem a -> IO (String)\nmenuItemText menu_item = withObject menu_item $ \\menu_itemPtr -> text' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_pulldown_with_args as pulldownWithArgs' { id `Ptr ()',`Int',`Int',`Int',`Int',id `Ptr ()', id `Ptr ()', id `Ptr ()', fromBool `Bool'} -> `Ptr ()' id #}\nmenuItemPulldown :: MenuItem a -> Rectangle -> Maybe (MenuItem a) -> Maybe (MenuPrim b) -> Maybe (MenuItem c) -> Maybe Bool -> IO (MenuItem b)\nmenuItemPulldown menu_item rectangle picked template_menu title menu_barFlag =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n menu_bar = maybe False id menu_barFlag\n in\n withObject menu_item $ \\menu_itemPtr ->\n withMaybeObject picked $ \\pickedPtr ->\n withMaybeObject template_menu $ \\template_menuPtr ->\n withMaybeObject title $ \\titlePtr ->\n pulldownWithArgs' menu_itemPtr x_pos y_pos width height pickedPtr template_menuPtr titlePtr menu_bar >>= toObject\n\n{# fun unsafe Fl_Menu_Item_popup_with_args as popupWithArgs' { id `Ptr ()',`Int',`Int', id `Ptr CChar' , id `Ptr ()', id `Ptr ()'} -> `Ptr ()' id #}\nmenuItemPopup :: MenuItem a -> Position -> Maybe String -> Maybe (MenuItem a) -> Maybe (MenuPrim b) -> IO (MenuItem c)\nmenuItemPopup menu_item (Position (X x_pos) (Y y_pos)) title picked template_menu =\n withObject menu_item $ \\menu_itemPtr ->\n withMaybeObject picked $ \\pickedPtr ->\n withMaybeObject template_menu $ \\template_menuPtr ->\n maybeNew newCString title >>= \\titlePtr ->\n popupWithArgs' menu_itemPtr x_pos y_pos titlePtr pickedPtr template_menuPtr >>= toObject\n\n{# fun unsafe Fl_Menu_Item_test_shortcut as testShortcut' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuItemTestShortcut :: MenuItem a -> IO (MenuItem a)\nmenuItemTestShortcut menu_item = withObject menu_item $ \\menu_itemPtr -> testShortcut' menu_itemPtr >>= toObject\n\n{# fun unsafe Fl_Menu_Item_find_shortcut_with_ip_require_alt as findShortcutWithIpRequireAlt' { id `Ptr ()',id `Ptr CInt',`Bool' } -> `Ptr ()' id #}\nmenuItemFindShortcut :: MenuItem a -> Maybe Int -> Bool -> IO (MenuItem a)\nmenuItemFindShortcut menu_item index require_alt =\n withObject menu_item $ \\menu_itemPtr ->\n maybeNew (new . fromIntegral) index >>= \\index_Ptr ->\n findShortcutWithIpRequireAlt' menu_itemPtr index_Ptr require_alt >>= toObject\n\n{# fun unsafe Fl_Menu_Item_do_callback as doCallback' { id `Ptr ()',id `Ptr ()' } -> `()' #}\nmenuItemDoCallback :: MenuItem a -> Widget a -> IO ()\nmenuItemDoCallback menu_item o = withObject menu_item $ \\menu_itemPtr -> withObject o $ \\oPtr -> doCallback' menu_itemPtr oPtr\n\n{# fun unsafe Fl_Menu_Item_insert_with_flags as insertWithFlags' { id `Ptr ()',`Int',`String',`Int',id `FunPtr CallbackWithUserDataPrim',`Int'} -> `Int' #}\n{# fun unsafe Fl_Menu_Item_add_with_flags as addWithFlags' { id `Ptr ()',`String',`Int',id `FunPtr CallbackWithUserDataPrim',`Int'} -> `Int' #}\n{# fun unsafe Fl_Menu_Item_add_with_shortcutname_flags as addWithShortcutnameFlags' { id `Ptr ()',`String',`String',id `FunPtr CallbackWithUserDataPrim',`Int' } -> `Int' #}\nmenuItemAdd :: MenuItem a -> String -> Shortcut -> (WidgetCallback b) -> [MenuProps] -> IO (Int)\nmenuItemAdd menu_item name shortcut cb flags =\n withObject menu_item $ \\menu_itemPtr -> do\n let combinedFlags = foldl1WithDefault 0 (.|.) (map fromEnum flags)\n ptr <- toWidgetCallbackPrim cb\n case shortcut of\n KeySequence (ShortcutKeySequence codes char) ->\n if (not $ null codes) then\n addWithFlags'\n menu_itemPtr\n name\n (sum $ map fromEnum codes ++ [(maybe 0 fromEnum char)])\n (castFunPtr ptr)\n combinedFlags\n else error \"Shortcut codes cannot be empty\"\n KeyFormat format ->\n if (not $ null format) then\n addWithShortcutnameFlags'\n menu_itemPtr\n name\n format\n (castFunPtr ptr)\n combinedFlags\n else error \"Shortcut format string cannot be empty\"\n\nmenuItemInsert :: MenuItem a -> Int -> String -> ShortcutKeySequence -> (WidgetCallback b) -> [MenuProps] -> IO (Int)\nmenuItemInsert menu_item index name (ShortcutKeySequence codes char) cb flags =\n withObject menu_item $ \\menu_itemPtr ->\n if (not $ null codes) then do\n let combinedFlags = foldl1WithDefault 0 (.|.) (map fromEnum flags)\n ptr <- toWidgetCallbackPrim cb\n insertWithFlags'\n menu_itemPtr\n index\n name\n (sum $ map fromEnum codes ++ [(maybe 0 fromEnum char)])\n (castFunPtr ptr)\n combinedFlags\n else error \"Shortcut codes cannot be empty\"\n\n{# fun unsafe Fl_Menu_Item_size as size' { id `Ptr ()' } -> `Int' #}\nmenuItemSize :: MenuItem a -> IO (Int)\nmenuItemSize menu_item = withObject menu_item $ \\menu_itemPtr -> size' menu_itemPtr\n","old_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.FLTK.LowLevel.Fl_Menu_Item\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Menu_ItemC.h\"\nimport C2HS hiding (cFromEnum, unsafePerformIO, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n{# fun unsafe Fl_Menu_Item_next_with_step as nextWithStep' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\nmenuItemNextWithStep :: MenuItem a -> Int -> IO (MenuItem a)\nmenuItemNextWithStep menu_item step =\n withObject menu_item $ \\menu_itemPtr -> nextWithStep' menu_itemPtr step >>= toObject\n\n{# fun unsafe Fl_Menu_Item_next as next' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuItemNext :: MenuItem a -> IO (Ptr ())\nmenuItemNext menu_item = withObject menu_item $ \\menu_itemPtr -> next' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_first as first' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuItemFirst :: MenuItem a -> IO (Ptr ())\nmenuItemFirst menu_item = withObject menu_item $ \\menu_itemPtr -> first' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_label as label' { id `Ptr ()' } -> `String' #}\nmenuItemLabel :: MenuItem a -> IO (String)\nmenuItemLabel menu_item = withObject menu_item $ \\menu_itemPtr -> label' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_label as setLabel' { id `Ptr ()',`String' } -> `()' #}\nmenuItemSetLabel :: MenuItem a -> String -> IO ()\nmenuItemSetLabel menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabel' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_set_label_with_labeltype as setLabelWithLabeltype' { id `Ptr ()',cFromEnum `Labeltype',`String' } -> `()' #}\nmenuItemSetLabelWithLabeltype :: MenuItem a -> Labeltype -> String -> IO ()\nmenuItemSetLabelWithLabeltype menu_item labeltype b = withObject menu_item $ \\menu_itemPtr -> setLabelWithLabeltype' menu_itemPtr labeltype b\n\n{# fun unsafe Fl_Menu_Item_labeltype as labeltype' { id `Ptr ()' } -> `Labeltype' cToEnum #}\nmenuItemLabeltype :: MenuItem a -> IO (Labeltype)\nmenuItemLabeltype menu_item = withObject menu_item $ \\menu_itemPtr -> labeltype' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_labeltype as setLabeltype' { id `Ptr ()',cFromEnum `Labeltype' } -> `()' #}\nmenuItemSetLabeltype :: MenuItem a -> Labeltype -> IO ()\nmenuItemSetLabeltype menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabeltype' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_labelcolor as labelcolor' { id `Ptr ()' } -> `Color' cToColor #}\nmenuItemLabelcolor :: MenuItem a -> IO (Color)\nmenuItemLabelcolor menu_item = withObject menu_item $ \\menu_itemPtr -> labelcolor' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_labelcolor as setLabelcolor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\nmenuItemSetLabelcolor :: MenuItem a -> Color -> IO ()\nmenuItemSetLabelcolor menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabelcolor' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_labelfont as labelfont' { id `Ptr ()' } -> `Font' cToFont #}\nmenuItemLabelfont :: MenuItem a -> IO (Font)\nmenuItemLabelfont menu_item = withObject menu_item $ \\menu_itemPtr -> labelfont' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_labelfont as setLabelfont' { id `Ptr ()',cFromFont `Font' } -> `()' #}\nmenuItemSetLabelfont :: MenuItem a -> Font -> IO ()\nmenuItemSetLabelfont menu_item a = withObject menu_item $ \\menu_itemPtr -> setLabelfont' menu_itemPtr a\n\n{# fun unsafe Fl_Menu_Item_labelsize as labelsize' { id `Ptr ()' } -> `CInt' id #}\nmenuItemLabelsize :: MenuItem a -> IO (FontSize)\nmenuItemLabelsize menu_item = withObject menu_item $ \\menu_itemPtr -> labelsize' menu_itemPtr >>= return . FontSize\n\n{# fun unsafe Fl_Menu_Item_set_labelsize as setLabelsize' { id `Ptr ()', id `CInt' } -> `()' #}\nmenuItemSetLabelsize :: MenuItem a -> FontSize -> IO ()\nmenuItemSetLabelsize menu_item (FontSize pix) = withObject menu_item $ \\menu_itemPtr -> setLabelsize' menu_itemPtr pix\n\n{# fun unsafe Fl_Menu_Item_set_callback as setCallback' { id `Ptr ()', id `FunPtr CallbackWithUserDataPrim'} -> `()' #}\nmenuItemSetCallback :: MenuItem a -> (WidgetCallback b) -> IO ()\nmenuItemSetCallback menu_item c = withObject menu_item $ \\menu_itemPtr -> do\n ptr <- toWidgetCallbackPrim c\n setCallback' menu_itemPtr (castFunPtr ptr)\n\n{# fun unsafe Fl_Menu_Item_shortcut as shortcut' { id `Ptr ()' } -> `Int' #}\nmenuItemShortcut :: MenuItem a -> IO (Int)\nmenuItemShortcut menu_item = withObject menu_item $ \\menu_itemPtr -> shortcut' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_shortcut as setShortcut' { id `Ptr ()',`Int' } -> `()' #}\nmenuItemSetShortcut :: MenuItem a -> Int -> IO ()\nmenuItemSetShortcut menu_item s = withObject menu_item $ \\menu_itemPtr -> setShortcut' menu_itemPtr s\n\n{# fun unsafe Fl_Menu_Item_submenu as submenu' { id `Ptr ()' } -> `Int' #}\nmenuItemSubmenu :: MenuItem a -> IO (Int)\nmenuItemSubmenu menu_item = withObject menu_item $ \\menu_itemPtr -> submenu' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_checkbox as checkbox' { id `Ptr ()' } -> `Int' #}\nmenuItemCheckbox :: MenuItem a -> IO (Int)\nmenuItemCheckbox menu_item = withObject menu_item $ \\menu_itemPtr -> checkbox' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_radio as radio' { id `Ptr ()' } -> `Int' #}\nmenuItemRadio :: MenuItem a -> IO (Int)\nmenuItemRadio menu_item = withObject menu_item $ \\menu_itemPtr -> radio' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_value as value' { id `Ptr ()' } -> `Int' #}\nmenuItemValue :: MenuItem a -> IO (Int)\nmenuItemValue menu_item = withObject menu_item $ \\menu_itemPtr -> value' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set as set' { id `Ptr ()' } -> `()' #}\nmenuItemSet :: MenuItem a -> IO ()\nmenuItemSet menu_item = withObject menu_item $ \\menu_itemPtr -> set' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_clear as clear' { id `Ptr ()' } -> `()' #}\nmenuItemClear :: MenuItem a -> IO ()\nmenuItemClear menu_item = withObject menu_item $ \\menu_itemPtr -> clear' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_setonly as setonly' { id `Ptr ()' } -> `()' #}\nmenuItemSetonly :: MenuItem a -> IO ()\nmenuItemSetonly menu_item = withObject menu_item $ \\menu_itemPtr -> setonly' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_visible as visible' { id `Ptr ()' } -> `Int' #}\nmenuItemVisible :: MenuItem a -> IO (Int)\nmenuItemVisible menu_item = withObject menu_item $ \\menu_itemPtr -> visible' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_show as show' { id `Ptr ()' } -> `()' #}\nmenuItemShow :: MenuItem a -> IO ()\nmenuItemShow menu_item = withObject menu_item $ \\menu_itemPtr -> show' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_hide as hide' { id `Ptr ()' } -> `()' #}\nmenuItemHide :: MenuItem a -> IO ()\nmenuItemHide menu_item = withObject menu_item $ \\menu_itemPtr -> hide' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_active as active' { id `Ptr ()' } -> `Int' #}\nmenuItemActive :: MenuItem a -> IO (Int)\nmenuItemActive menu_item = withObject menu_item $ \\menu_itemPtr -> active' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_activate as activate' { id `Ptr ()' } -> `()' #}\nmenuItemActivate :: MenuItem a -> IO ()\nmenuItemActivate menu_item = withObject menu_item $ \\menu_itemPtr -> activate' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_deactivate as deactivate' { id `Ptr ()' } -> `()' #}\nmenuItemDeactivate :: MenuItem a -> IO ()\nmenuItemDeactivate menu_item = withObject menu_item $ \\menu_itemPtr -> deactivate' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_activevisible as activevisible' { id `Ptr ()' } -> `Int' #}\nmenuItemActivevisible :: MenuItem a -> IO (Int)\nmenuItemActivevisible menu_item = withObject menu_item $ \\menu_itemPtr -> activevisible' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_measure as measure' { id `Ptr ()',alloca- `Int' peekIntConv*,id `Ptr ()' } -> `()' #}\nmenuItemMeasure :: MenuItem a -> MenuPrim a -> IO (Int)\nmenuItemMeasure menu_item menu = withObject menu_item $ \\menu_itemPtr -> withObject menu $ \\menuPtr -> measure' menu_itemPtr menuPtr\n\n{# fun unsafe Fl_Menu_Item_draw_with_t as drawWithT' { id `Ptr ()',`Int',`Int',`Int',`Int',id `Ptr ()',`Int' } -> `()' #}\nmenuItemDrawWithT :: MenuItem a -> Rectangle -> MenuPrim a -> Int -> IO ()\nmenuItemDrawWithT menu_item rectangle menu t =\n let (x_pos', y_pos', width', height') = fromRectangle rectangle in\n withObject menu_item $ \\menu_itemPtr -> withObject menu $ \\menuPtr -> drawWithT' menu_itemPtr x_pos' y_pos' width' height' menuPtr t\n\n{# fun unsafe Fl_Menu_Item_draw as draw' { id `Ptr ()',`Int',`Int',`Int',`Int',id `Ptr ()' } -> `()' #}\nmenuItemDraw :: MenuItem a -> Rectangle -> MenuPrim a -> IO ()\nmenuItemDraw menu_item rectangle menu =\n let (x_pos', y_pos', width', height') = fromRectangle rectangle in\n withObject menu_item $ \\menu_itemPtr ->\n withObject menu $ \\menuPtr -> draw' menu_itemPtr x_pos' y_pos' width' height' menuPtr\n\n{# fun unsafe Fl_Menu_Item_flags as flags' { id `Ptr ()' } -> `Int' #}\nmenuItemFlags :: MenuItem a -> IO (Int)\nmenuItemFlags menu_item = withObject menu_item $ \\menu_itemPtr -> flags' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_set_flags as setFlags' { id `Ptr ()',`Int' } -> `()' #}\nmenuItemSetFlags :: MenuItem a -> Int -> IO ()\nmenuItemSetFlags menu_item flags = withObject menu_item $ \\menu_itemPtr -> setFlags' menu_itemPtr flags\n\n{# fun unsafe Fl_Menu_Item_text as text' { id `Ptr ()' } -> `String' #}\nmenuItemText :: MenuItem a -> IO (String)\nmenuItemText menu_item = withObject menu_item $ \\menu_itemPtr -> text' menu_itemPtr\n\n{# fun unsafe Fl_Menu_Item_pulldown_with_args as pulldownWithArgs' { id `Ptr ()',`Int',`Int',`Int',`Int',id `Ptr ()', id `Ptr ()', id `Ptr ()', fromBool `Bool'} -> `Ptr ()' id #}\nmenuItemPulldown :: MenuItem a -> Rectangle -> Maybe (MenuItem a) -> Maybe (MenuPrim b) -> Maybe (MenuItem c) -> Maybe Bool -> IO (MenuItem b)\nmenuItemPulldown menu_item rectangle picked template_menu title menu_barFlag =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n menu_bar = maybe False id menu_barFlag\n in\n withObject menu_item $ \\menu_itemPtr ->\n withMaybeObject picked $ \\pickedPtr ->\n withMaybeObject template_menu $ \\template_menuPtr ->\n withMaybeObject title $ \\titlePtr ->\n pulldownWithArgs' menu_itemPtr x_pos y_pos width height pickedPtr template_menuPtr titlePtr menu_bar >>= toObject\n\n{# fun unsafe Fl_Menu_Item_popup_with_args as popupWithArgs' { id `Ptr ()',`Int',`Int', id `Ptr CChar' , id `Ptr ()', id `Ptr ()'} -> `Ptr ()' id #}\nmenuItemPopup :: MenuItem a -> Position -> Maybe String -> Maybe (MenuItem a) -> Maybe (MenuPrim b) -> IO (MenuItem c)\nmenuItemPopup menu_item (Position (X x_pos) (Y y_pos)) title picked template_menu =\n withObject menu_item $ \\menu_itemPtr ->\n withMaybeObject picked $ \\pickedPtr ->\n withMaybeObject template_menu $ \\template_menuPtr ->\n maybeNew newCString title >>= \\titlePtr ->\n popupWithArgs' menu_itemPtr x_pos y_pos titlePtr pickedPtr template_menuPtr >>= toObject\n\n{# fun unsafe Fl_Menu_Item_test_shortcut as testShortcut' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuItemTestShortcut :: MenuItem a -> IO (MenuItem a)\nmenuItemTestShortcut menu_item = withObject menu_item $ \\menu_itemPtr -> testShortcut' menu_itemPtr >>= toObject\n\n{# fun unsafe Fl_Menu_Item_find_shortcut_with_ip_require_alt as findShortcutWithIpRequireAlt' { id `Ptr ()',id `Ptr CInt',`Bool' } -> `Ptr ()' id #}\nmenuItemFindShortcut :: MenuItem a -> Maybe Int -> Bool -> IO (MenuItem a)\nmenuItemFindShortcut menu_item index require_alt =\n withObject menu_item $ \\menu_itemPtr ->\n maybeNew (new . fromIntegral) index >>= \\index_Ptr ->\n findShortcutWithIpRequireAlt' menu_itemPtr index_Ptr require_alt >>= toObject\n\n{# fun unsafe Fl_Menu_Item_do_callback as doCallback' { id `Ptr ()',id `Ptr ()' } -> `()' #}\nmenuItemDoCallback :: MenuItem a -> Widget a -> IO ()\nmenuItemDoCallback menu_item o = withObject menu_item $ \\menu_itemPtr -> withObject o $ \\oPtr -> doCallback' menu_itemPtr oPtr\n\n{# fun unsafe Fl_Menu_Item_insert_with_flags as insertWithFlags' { id `Ptr ()',`Int',`String',`Int',id `FunPtr CallbackWithUserDataPrim',`Int'} -> `Int' #}\n{# fun unsafe Fl_Menu_Item_add_with_flags as addWithFlags' { id `Ptr ()',`String',`Int',id `FunPtr CallbackWithUserDataPrim',`Int'} -> `Int' #}\n{# fun unsafe Fl_Menu_Item_add_with_shortcutname_flags as addWithShortcutnameFlags' { id `Ptr ()',`String',`String',id `FunPtr CallbackWithUserDataPrim',`Int' } -> `Int' #}\nmenuItemAdd :: MenuItem a -> String -> Shortcut -> (WidgetCallback b) -> [MenuProps] -> IO (Int)\nmenuItemAdd menu_item name shortcut cb flags =\n withObject menu_item $ \\menu_itemPtr -> do\n let combinedFlags = foldl1WithDefault 0 (.|.) (map fromEnum flags)\n ptr <- toWidgetCallbackPrim cb\n case shortcut of\n KeySequence (ShortcutKeySequence codes char) ->\n if (not $ null codes) then\n addWithFlags'\n menu_itemPtr\n name\n (sum $ map fromEnum codes ++ [(maybe 0 fromEnum char)])\n (castFunPtr ptr)\n combinedFlags\n else error \"Shortcut codes cannot be empty\"\n KeyFormat format ->\n if (not $ null format) then\n addWithShortcutnameFlags'\n menu_itemPtr\n name\n format\n (castFunPtr ptr)\n combinedFlags\n else error \"Shortcut format string cannot be empty\"\n\nmenuItemInsert :: MenuItem a -> Int -> String -> ShortcutKeySequence -> (WidgetCallback b) -> [MenuProps] -> IO (Int)\nmenuItemInsert menu_item index name (ShortcutKeySequence codes char) cb flags =\n withObject menu_item $ \\menu_itemPtr ->\n if (not $ null codes) then do\n let combinedFlags = foldl1WithDefault 0 (.|.) (map fromEnum flags)\n ptr <- toWidgetCallbackPrim cb\n insertWithFlags'\n menu_itemPtr\n index\n name\n (sum $ map fromEnum codes ++ [(maybe 0 fromEnum char)])\n (castFunPtr ptr)\n combinedFlags\n else error \"Shortcut codes cannot be empty\"\n\n{# fun unsafe Fl_Menu_Item_size as size' { id `Ptr ()' } -> `Int' #}\nmenuItemSize :: MenuItem a -> IO (Int)\nmenuItemSize menu_item = withObject menu_item $ \\menu_itemPtr -> size' menu_itemPtr\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"17a847c0de2a1c029623889cc0d576f435f4f205","subject":"fmapBand checks band and block sizes","message":"fmapBand checks band and block sizes\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.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 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 = 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":"e0b7f95f7c532e0372ab0908f1a9fa4c736de84f","subject":"An enum and getter for image depth.","message":"An enum and getter for image depth.\n\nAlthough this should be totally useless for the\nuser it is useful for debugging the bindings.","repos":"BeautifulDestinations\/CV,aleator\/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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\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\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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":"486d7a233236f2610baf46dc9df5a7e1a6513521","subject":"Don't bind attributes we don't understand.","message":"Don't bind attributes we don't understand.\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit","old_file":"glib\/System\/Glib\/GValueTypes.chs","new_file":"glib\/System\/Glib\/GValueTypes.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetUChar,\n valueGetUChar,\n valueSetChar,\n valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue (fromIntegral value)\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n liftM fromIntegral $ {# call unsafe value_get_uchar #} gvalue\n\n--these belong somewhere else, are in new c2hs's C2HS module\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\n--valueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar :: GValue -> Char -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue (cFromEnum value)\n\n--valueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar :: GValue -> IO Char\nvalueGetChar gvalue =\n liftM cToEnum $ {# call unsafe value_get_char #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"48dd7ff60cc4e4abfb6ec29ed42e5234d314385d","subject":"gstreamer: small fixes in M.S.G.Core.Event","message":"gstreamer: small fixes in M.S.G.Core.Event","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.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 object describing events that are passed up and down a pipeline.\nmodule Media.Streaming.GStreamer.Core.Event (\n\n-- * Detail\n\n -- | An 'Event' is a message that is passed up and down a pipeline.\n -- \n -- There are a number of predefined events and functions returning\n -- events. To send an event an application will usually use\n -- 'Media.Streaming.GStreamer.Core.Element.elementSendEvent', and\n -- elements will use\n -- 'Media.Streaming.GStreamer.Core.Pad.padSendEvent' or\n -- 'Media.Streaming.GStreamer.Core.padPushEvent'.\n -- \n -- \n\n-- * Types\n Event,\n EventClass,\n EventType(..),\n\n-- * Event Operations\n eventType,\n eventNewCustom,\n eventNewEOS,\n eventNewFlushStart,\n eventNewFlushStop,\n eventNewLatency,\n eventNewNavigation,\n eventNewNewSegment,\n eventNewNewSegmentFull,\n eventNewQOS,\n eventNewSeek,\n eventNewTag,\n eventParseBufferSize,\n eventParseLatency,\n eventParseNewSegment,\n eventParseNewSegmentFull,\n eventParseQOS,\n eventParseSeek,\n eventParseTag,\n eventTypeGetName,\n eventTypeGetFlags,\n ) where\n\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: EventClass event\n => event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject (toEvent event) cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: EventClass event\n => event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} (toEvent event)\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: EventClass event\n => event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} (toEvent event)\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: EventClass event\n => event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} (toEvent event)\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: EventClass event\n => event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} (toEvent event)\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: EventClass event\n => event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} (toEvent event)\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: EventClass event\n => event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} (toEvent event)\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: EventClass event\n => event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} (toEvent event) (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n | otherwise = Nothing\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\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.Event (\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: Event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject event cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: Event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} event\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: Event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} event\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: Event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} event\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: Event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} event\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: Event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} event\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: Event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} event\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: Event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} event (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"95768a2ed8fe1080e1bcfc5cff6a2e2e99536474","subject":"that shouldn't have been commited","message":"that shouldn't have been commited\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 DeriveDataTypeable #-}\n{-# LANGUAGE GADTs #-}\n\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , MaybeIOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , Band\n , Driver\n , ColorTable\n , RasterAttributeTable\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , open\n , openShared\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\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.Concurrent (newMVar, takeMVar, putMVar, MVar)\nimport Control.Exception (finally, bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\nimport Data.Maybe (isJust)\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\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\nforeign import ccall \"wrapper\"\n wrapErrorHandler :: 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{# 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 Band 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 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\ncreate :: String -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO Dataset\ncreate drv path nx ny bands dtype options = do\n d <- driverByName drv\n create' d path nx ny bands dtype options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO 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'} -> `Dataset' newDatasetHandle* #}\n\n{# fun GDALOpen as openShared\n { `String', fromEnumC `Access'} -> `Dataset' newDatasetHandle* #}\n\ncreateCopy' :: Driver -> String -> Dataset -> Bool -> DriverOptions\n -> ProgressFun -> IO 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 = withCCallback wrapProgressFun\n\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ncreateCopy :: String -> String -> Dataset -> Bool -> DriverOptions\n -> IO Dataset\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n 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 Dataset\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) -> IO ())\n\ncreateMem:: Int -> Int -> Int -> Datatype -> DriverOptions -> IO 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 Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $\n {#call unsafe GDALGetGeoTransform as ^#} 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\nsetDatasetGeotransform :: Dataset -> 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\" $\n {#call unsafe GDALSetGeoTransform as ^#} dPtr a\n\nwithBand :: Dataset -> Int -> (Band -> IO a) -> IO a\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- {# call unsafe GDALGetRasterBand as ^ #}\n 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\n{# fun pure unsafe GDALGetRasterDataType as bandDatatype\n { id `Band'} -> `Datatype' toEnumC #}\n\nbandBlockSize :: Band -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr ->\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n {#call unsafe GDALGetBlockSize as ^#} band xPtr yPtr >>\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nbandBlockLen :: Band -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: Band -> (Int, Int)\nbandSize band\n = ( fromIntegral . {# call pure unsafe GDALGetRasterBandXSize as ^#} $ band\n , fromIntegral . {# call pure unsafe GDALGetRasterBandYSize as ^#} $ band\n )\n\nbandNodataValue :: Band -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ {#call unsafe GDALGetRasterNoDataValue as ^#} b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \n{# fun GDALSetRasterNoDataValue as setBandNodataValue\n { id `Band', `Double'} -> `Error' toEnumC #}\n\n{# fun GDALFillRaster as fillBand\n { id `Band', `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 => Band\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 withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\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 throwIfError \"could not read band\" $\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 return $ unsafeFromForeignPtr0 fp (bx * by)\n \nwriteBand :: (Storable a, HasDatatype (Ptr a))\n => Band\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 {#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\n\ndata Block where\n Block :: (Typeable a, Storable a) => Vector a -> Block\n\ntype MaybeIOVector a = IO (Maybe (Vector a))\n\nreadBandBlock :: (Storable a, Typeable a)\n => Band -> Int -> Int -> MaybeIOVector a\nreadBandBlock b x y = do\n block <- readBandBlock' b x y\n liftM (maybe Nothing (\\(Block a) -> cast a)) $ readBandBlock' b x y\n\n\nreadBandBlock' :: Band -> Int -> Int -> IO (Maybe Block)\nreadBandBlock' b x y = \n case bandDatatype b of\n GDT_Byte -> Just . Block <$> (readIt b x y :: IOVector Word8)\n GDT_Int16 -> Just . Block <$> (readIt b x y :: IOVector Int16)\n GDT_Int32 -> Just . Block <$> (readIt b x y :: IOVector Int32)\n GDT_Float32 -> Just . Block <$> (readIt b x y :: IOVector Float)\n GDT_Float64 -> Just . Block <$> (readIt b x y :: IOVector Double)\n GDT_CInt16 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CInt32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n GDT_CFloat32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CFloat64 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n _ -> return Nothing\n where\n readIt :: Storable a => Band -> Int -> Int -> IOVector a\n readIt b x y = do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n {#call GDALReadBlock as ^#}\n b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\ntype IOVector a = IO (Vector a)\n\nwriteBandBlock :: (Storable a, Typeable a)\n => Band\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBandBlock 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 typeOf vec \/= typeOfBand b\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n {#call GDALWriteBlock as ^#}\n b (fromIntegral x) (fromIntegral y) (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 DeriveDataTypeable #-}\n{-# LANGUAGE GADTs #-}\n\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , MaybeIOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , Band\n , Driver\n , ColorTable\n , RasterAttributeTable\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , open\n , openShared\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\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.Concurrent (newMVar, takeMVar, putMVar, MVar, runInBoundThread,\n rtsSupportsBoundThreads)\nimport Control.Exception (finally, bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\nimport Data.Maybe (isJust)\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\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\nforeign import ccall \"wrapper\"\n wrapErrorHandler :: 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{# 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\n = runInBoundThread' $ withMutex m $ withDataset' ds fun\n\nrunInBoundThread' a\n = if rtsSupportsBoundThreads then runInBoundThread a else a\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band 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 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\ncreate :: String -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO Dataset\ncreate drv path nx ny bands dtype options = do\n d <- driverByName drv\n create' d path nx ny bands dtype options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO 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'} -> `Dataset' newDatasetHandle* #}\n\n{# fun GDALOpen as openShared\n { `String', fromEnumC `Access'} -> `Dataset' newDatasetHandle* #}\n\ncreateCopy' :: Driver -> String -> Dataset -> Bool -> DriverOptions\n -> ProgressFun -> IO 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 = withCCallback wrapProgressFun\n\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ncreateCopy :: String -> String -> Dataset -> Bool -> DriverOptions\n -> IO Dataset\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n 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 Dataset\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) -> IO ())\n\ncreateMem:: Int -> Int -> Int -> Datatype -> DriverOptions -> IO 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 Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $\n {#call unsafe GDALGetGeoTransform as ^#} 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\nsetDatasetGeotransform :: Dataset -> 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\" $\n {#call unsafe GDALSetGeoTransform as ^#} dPtr a\n\nwithBand :: Dataset -> Int -> (Band -> IO a) -> IO a\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- {# call unsafe GDALGetRasterBand as ^ #}\n 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\n{# fun pure unsafe GDALGetRasterDataType as bandDatatype\n { id `Band'} -> `Datatype' toEnumC #}\n\nbandBlockSize :: Band -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr ->\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n {#call unsafe GDALGetBlockSize as ^#} band xPtr yPtr >>\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nbandBlockLen :: Band -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: Band -> (Int, Int)\nbandSize band\n = ( fromIntegral . {# call pure unsafe GDALGetRasterBandXSize as ^#} $ band\n , fromIntegral . {# call pure unsafe GDALGetRasterBandYSize as ^#} $ band\n )\n\nbandNodataValue :: Band -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ {#call unsafe GDALGetRasterNoDataValue as ^#} b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \n{# fun GDALSetRasterNoDataValue as setBandNodataValue\n { id `Band', `Double'} -> `Error' toEnumC #}\n\n{# fun GDALFillRaster as fillBand\n { id `Band', `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 => Band\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 withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\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 throwIfError \"could not read band\" $\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 return $ unsafeFromForeignPtr0 fp (bx * by)\n \nwriteBand :: (Storable a, HasDatatype (Ptr a))\n => Band\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 {#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\n\ndata Block where\n Block :: (Typeable a, Storable a) => Vector a -> Block\n\ntype MaybeIOVector a = IO (Maybe (Vector a))\n\nreadBandBlock :: (Storable a, Typeable a)\n => Band -> Int -> Int -> MaybeIOVector a\nreadBandBlock b x y = do\n block <- readBandBlock' b x y\n liftM (maybe Nothing (\\(Block a) -> cast a)) $ readBandBlock' b x y\n\n\nreadBandBlock' :: Band -> Int -> Int -> IO (Maybe Block)\nreadBandBlock' b x y = \n case bandDatatype b of\n GDT_Byte -> Just . Block <$> (readIt b x y :: IOVector Word8)\n GDT_Int16 -> Just . Block <$> (readIt b x y :: IOVector Int16)\n GDT_Int32 -> Just . Block <$> (readIt b x y :: IOVector Int32)\n GDT_Float32 -> Just . Block <$> (readIt b x y :: IOVector Float)\n GDT_Float64 -> Just . Block <$> (readIt b x y :: IOVector Double)\n GDT_CInt16 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CInt32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n GDT_CFloat32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CFloat64 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n _ -> return Nothing\n where\n readIt :: Storable a => Band -> Int -> Int -> IOVector a\n readIt b x y = do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n {#call GDALReadBlock as ^#}\n b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\ntype IOVector a = IO (Vector a)\n\nwriteBandBlock :: (Storable a, Typeable a)\n => Band\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBandBlock 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 typeOf vec \/= typeOfBand b\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n {#call GDALWriteBlock as ^#}\n b (fromIntegral x) (fromIntegral y) (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":"52c4dd66be715f0f16829d922e2262db8b542686","subject":"gstreamer: fix types for event handlers in Element.chs","message":"gstreamer: fix types for event handlers in Element.chs\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" 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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"057b42fa1829f6287a7c1ab47b0c490144ec2a6b","subject":"ghc-7.6\/7.8 import fix","message":"ghc-7.6\/7.8 import fix\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error (\n\n Status(..), CUDAException(..),\n\n cudaError, describe, requireSDK,\n resultIfOk, nothingIfOk\n\n) where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign.C\nimport Foreign.Ptr\nimport Data.Typeable\nimport Control.Exception\nimport System.IO.Unsafe\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n-- |\n-- Return codes from API functions\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- A specially formatted error message\n--\nrequireSDK :: Double -> String -> IO a\nrequireSDK v s = cudaError (\"'\" ++ s ++ \"' requires at least cuda-\" ++ show v)\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorStringWrapper as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\n{-# INLINE resultIfOk #-}\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status, !result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\n{-# INLINE nothingIfOk #-}\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error (\n\n Status(..), CUDAException(..),\n\n cudaError, describe, requireSDK,\n resultIfOk, nothingIfOk\n\n) where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Typeable\nimport Control.Exception\nimport System.IO.Unsafe\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n-- |\n-- Return codes from API functions\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- A specially formatted error message\n--\nrequireSDK :: Double -> String -> IO a\nrequireSDK v s = cudaError (\"'\" ++ s ++ \"' requires at least cuda-\" ++ show v)\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorStringWrapper as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\n{-# INLINE resultIfOk #-}\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status, !result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\n{-# INLINE nothingIfOk #-}\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":"de52a54d60a5405219ed4977217c763294f3789e","subject":"Expose FLInputType constructors","message":"Expose FLInputType constructors\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Input.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Input.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Input\n (\n FlInputType(..),\n -- * Constructor\n inputNew\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Input\n --\n -- $Input\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_InputC.h\"\n#include \"Fl_Input_C.h\"\n#include \"Fl_Int_InputC.h\"\n#include \"Fl_Float_InputC.h\"\n#include \"Fl_Secret_InputC.h\"\n#include \"Fl_Multiline_InputC.h\"\n#include \"Fl_OutputC.h\"\n#include \"Fl_Multiline_OutputC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\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\nimport Graphics.UI.FLTK.LowLevel.Dispatch\n#c\nenum FlInputType {\n FlNormalInput = FL_NORMAL_INPUT,\n FlFloatInput = FL_FLOAT_INPUT,\n FlIntInput = FL_INT_INPUT,\n FlMultilineInput = FL_MULTILINE_INPUT,\n FlSecretInput = FL_SECRET_INPUT,\n FlNormalOutput = FL_NORMAL_OUTPUT,\n FlMultilineOutput = FL_MULTILINE_OUTPUT\n};\n#endc\n{#enum FlInputType {}#}\n{# fun Fl_Input_New as inputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Input_New_WithLabel as inputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Multiline_Input_New as multilineInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Multiline_Input_New_WithLabel as multilineInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Float_Input_New as floatInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Float_Input_New_WithLabel as floatInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Int_Input_New as intInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Int_Input_New_WithLabel as intInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Secret_Input_New as secretInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Secret_Input_New_WithLabel as secretInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Output_New as outputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Output_New_WithLabel as outputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Multiline_Output_New as multilineOutputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Multiline_Output_New_WithLabel as multilineOutputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\ninputNew :: Maybe FlInputType -> Rectangle -> Maybe String -> IO (Ref Input)\ninputNew flInputType rectangle l'=\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n constructor = case flInputType of\n Just FlNormalInput -> maybe inputNew' (\\l -> (\\x y w h -> inputNewWithLabel' x y w h l)) l'\n Just FlFloatInput -> maybe floatInputNew' (\\l -> (\\x y w h -> floatInputNewWithLabel' x y w h l)) l'\n Just FlIntInput -> maybe intInputNew' (\\l -> (\\x y w h -> intInputNewWithLabel' x y w h l)) l'\n Just FlMultilineInput -> maybe multilineInputNew' (\\l -> (\\x y w h -> multilineInputNewWithLabel' x y w h l)) l'\n Just FlSecretInput -> maybe secretInputNew' (\\l -> (\\x y w h -> secretInputNewWithLabel' x y w h l)) l'\n Just FlNormalOutput -> maybe outputNew' (\\l -> (\\x y w h -> outputNewWithLabel' x y w h l)) l'\n Just FlMultilineOutput -> maybe multilineOutputNew' (\\l -> (\\x y w h -> multilineOutputNewWithLabel' x y w h l)) l'\n Nothing -> inputNew'\n in\n constructor x_pos y_pos width height >>= toRef\n\n{# fun Fl_Input_Destroy as inputDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) Input orig impl where\n runOp _ _ win = swapRef win $ \\winPtr -> do\n inputDestroy' winPtr\n return nullPtr\n\n{#fun Fl_Input_handle as inputHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\n{#fun Fl_Secret_Input_handle as secretInputHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO Int)) => Op (Handle ()) Input orig impl where\n runOp _ _ input event =\n withRef\n input\n (\\p -> do\n t <- getInputType input\n case (toEnum (fromIntegral t)) of\n FlSecretInput -> secretInputHandle' p (fromIntegral . fromEnum $ event)\n _ -> inputHandle' p (fromIntegral . fromEnum $ event)\n )\n{# fun unsafe Fl_Input_set_value as setValue' { id `Ptr ()', unsafeToCString `String' } -> `Int' #}\n{# fun unsafe Fl_Input_set_value_with_length as setValueWithLength' { id `Ptr ()', unsafeToCString `String',`Int' } -> `Int' #}\ninstance (impl ~ (String -> Maybe Int -> IO (Int))) => Op (SetValue ()) Input orig impl where\n runOp _ _ input text l' =\n case l' of\n Nothing -> withRef input $ \\inputPtr -> setValue' inputPtr text\n Just l -> withRef input $ \\inputPtr -> setValueWithLength' inputPtr text l\n{# fun unsafe Fl_Input_static_value as staticValue' { id `Ptr ()', unsafeToCString `String' } -> `Int' #}\n{# fun unsafe Fl_Input_static_value_with_length as staticValueWithLength' { id `Ptr ()', unsafeToCString `String',`Int' } -> `Int' #}\ninstance (impl ~ (String -> Maybe Int -> IO (Either NoChange ()))) => Op (StaticValue ()) Input orig impl where\n runOp _ _ input text l'= do\n status' <- case l' of\n Nothing -> withRef input $ \\inputPtr -> staticValue' inputPtr text\n Just l -> withRef input $ \\inputPtr -> staticValueWithLength' inputPtr text l\n return $ successOrNoChange status'\n{# fun unsafe Fl_Input_value as value' { id `Ptr ()' } -> `String' #}\ninstance (impl ~ ( IO (String))) => Op (GetValue ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> value' inputPtr\n{# fun unsafe Fl_Input_index as index' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> IO (Char))) => Op (Index ()) Input orig impl where\n runOp _ _ input i = withRef input $ \\inputPtr -> index' inputPtr i >>= return . toEnum\n{# fun unsafe Fl_Input_set_size as setSize' { id `Ptr ()',`Int',`Int' } -> `()' #}\ninstance (impl ~ (Size -> IO ())) => Op (SetSize ()) Input orig impl where\n runOp _ _ input (Size (Width w') (Height h')) = withRef input $ \\inputPtr -> setSize' inputPtr w' h'\n{# fun unsafe Fl_Input_maximum_size as maximumSize' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetMaximumSize ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> maximumSize' inputPtr\n{# fun unsafe Fl_Input_size as size' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetSize ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> size' inputPtr\n{# fun unsafe Fl_Input_set_maximum_size as setMaximumSize' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetMaximumSize ()) Input orig impl where\n runOp _ _ input m = withRef input $ \\inputPtr -> setMaximumSize' inputPtr m\n{# fun unsafe Fl_Input_position as position' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetPosition ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> position' inputPtr\n{# fun unsafe Fl_Input_mark as mark' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetMark ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> mark' inputPtr\n{# fun unsafe Fl_Input_set_position_with_cursor_mark as setPositionWithCursorMark' { id `Ptr ()',`Int',`Int' } -> `Int' #}\n{# fun unsafe Fl_Input_set_position_n_n as setPositionNN' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> Maybe Int -> IO (Either NoChange ()))) => Op (SetPosition ()) Input orig impl where\n runOp _ _ input point mark = do\n status' <- case mark of\n Just m -> withRef input $ \\inputPtr -> setPositionWithCursorMark' inputPtr point m\n Nothing -> withRef input $ \\inputPtr -> setPositionNN' inputPtr point\n return $ successOrNoChange status'\n{# fun unsafe Fl_Input_set_mark as setMark' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> IO (Either NoChange ()))) => Op (SetMark ()) Input orig impl where\n runOp _ _ input m = withRef input $ \\inputPtr -> setMark' inputPtr m >>= return . successOrNoChange\n{# fun unsafe Fl_Input_replace as replace' { id `Ptr ()',`Int',`Int', unsafeToCString `String' } -> `Int' #}\ninstance (impl ~ (Int -> Int -> String -> IO (Either NoChange ()))) => Op (Replace ()) Input orig impl where\n runOp _ _ input b e text = withRef input $ \\inputPtr -> replace' inputPtr b e text >>= return . successOrNoChange\n{# fun unsafe Fl_Input_cut as cut' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Either NoChange ()))) => Op (Cut ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> cut' inputPtr >>= return . successOrNoChange\n{# fun unsafe Fl_Input_cut_bytes as cutBytes' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> IO (Either NoChange ()))) => Op (CutFromCursor ()) Input orig impl where\n runOp _ _ input n = withRef input $ \\inputPtr -> cutBytes' inputPtr n >>= return . successOrNoChange\n{# fun unsafe Fl_Input_cut_range as cutRange' { id `Ptr ()',`Int',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> Int -> IO (Either NoChange ()))) => Op (CutRange ()) Input orig impl where\n runOp _ _ input a b = withRef input $ \\inputPtr -> cutRange' inputPtr a b >>= return . successOrNoChange\n{# fun unsafe Fl_Input_insert as insert' { id `Ptr ()', unsafeToCString `String' } -> `Int' #}\ninstance (impl ~ (String -> IO (Either NoChange ()))) => Op (Insert ()) Input orig impl where\n runOp _ _ input t = withRef input $ \\inputPtr -> insert' inputPtr t >>= return . successOrNoChange\n{# fun unsafe Fl_Input_insert_with_length as insertWithLength' { id `Ptr ()', unsafeToCString `String',`Int' } -> `Int' #}\ninstance (impl ~ (String -> Int -> IO (Either NoChange ()))) => Op (InsertWithLength ()) Input orig impl where\n runOp _ _ input t l = withRef input $ \\inputPtr -> insertWithLength' inputPtr t l >>= return . successOrNoChange\n{# fun unsafe Fl_Input_copy as copy' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Clipboard -> IO (Either NoChange ()))) => Op (Copy ()) Input orig impl where\n runOp _ _ input clipboard = do\n status' <- case clipboard of\n InternalClipboard -> withRef input $ \\inputPtr -> copy' inputPtr 1\n SharedClipboard -> withRef input $ \\inputPtr -> copy' inputPtr 0\n return $ successOrNoChange status'\n{# fun unsafe Fl_Input_undo as undo' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Either NoChange ()))) => Op (Undo ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> undo' inputPtr >>= return . successOrNoChange\n{# fun unsafe Fl_Input_copy_cuts as copyCuts' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Either NoChange ()))) => Op (CopyCuts ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> copyCuts' inputPtr >>= return . successOrNoChange\n{# fun unsafe Fl_Input_shortcut as shortcut' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetShortcut ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> shortcut' inputPtr\n{# fun unsafe Fl_Input_set_shortcut as setShortcut' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetShortcut ()) Input orig impl where\n runOp _ _ input s = withRef input $ \\inputPtr -> setShortcut' inputPtr s\n{# fun unsafe Fl_Input_textfont as textfont' { id `Ptr ()' } -> `Font' cToFont #}\ninstance (impl ~ ( IO (Font))) => Op (GetTextfont ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> textfont' inputPtr\n{# fun unsafe Fl_Input_set_textfont as setTextfont' { id `Ptr ()',cFromFont `Font' } -> `()' #}\ninstance (impl ~ (Font -> IO ())) => Op (SetTextfont ()) Input orig impl where\n runOp _ _ input s = withRef input $ \\inputPtr -> setTextfont' inputPtr s\n{# fun unsafe Fl_Input_textsize as textsize' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ ( IO (FontSize))) => Op (GetTextsize ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> textsize' inputPtr >>= return . FontSize\n{# fun unsafe Fl_Input_set_textsize as setTextsize' { id `Ptr ()', id `CInt' } -> `()' #}\ninstance (impl ~ (FontSize -> IO ())) => Op (SetTextsize ()) Input orig impl where\n runOp _ _ input (FontSize s) = withRef input $ \\inputPtr -> setTextsize' inputPtr s\n{# fun unsafe Fl_Input_textcolor as textcolor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ ( IO (Color))) => Op (GetTextcolor ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> textcolor' inputPtr\n{# fun unsafe Fl_Input_set_textcolor as setTextcolor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ninstance (impl ~ (Color -> IO ())) => Op (SetTextcolor ()) Input orig impl where\n runOp _ _ input n = withRef input $ \\inputPtr -> setTextcolor' inputPtr n\n{# fun unsafe Fl_Input_cursor_color as cursorColor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ ( IO (Color))) => Op (GetCursorColor ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> cursorColor' inputPtr\n{# fun unsafe Fl_Input_set_cursor_color as setCursorColor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ninstance (impl ~ (Color -> IO ())) => Op (SetCursorColor ()) Input orig impl where\n runOp _ _ input n = withRef input $ \\inputPtr -> setCursorColor' inputPtr n\n{# fun unsafe Fl_Input_input_type as inputType' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetInputType ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> inputType' inputPtr\n{# fun unsafe Fl_Input_set_input_type as setInputType' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetInputType ()) Input orig impl where\n runOp _ _ input t = withRef input $ \\inputPtr -> setInputType' inputPtr t\n{# fun unsafe Fl_Input_readonly as readonly' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetReadonly ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> readonly' inputPtr\n{# fun unsafe Fl_Input_set_readonly as setReadonly' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetReadonly ()) Input orig impl where\n runOp _ _ input b = withRef input $ \\inputPtr -> setReadonly' inputPtr b\n{# fun unsafe Fl_Input_wrap as wrap' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetWrap ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> wrap' inputPtr\n{# fun unsafe Fl_Input_set_wrap as setWrap' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetWrap ()) Input orig impl where\n runOp _ _ input b = withRef input $ \\inputPtr -> setWrap' inputPtr b\n{# fun unsafe Fl_Input_tab_nav as tabNav' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (GetTabNav ()) Input orig impl where\n runOp _ _ input val = withRef input $ \\inputPtr -> tabNav' inputPtr val\n{# fun unsafe Fl_Input_set_tab_nav as setTabNav' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (SetTabNav ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> setTabNav' inputPtr\n\n-- $Input\n-- @\n--\n-- copy :: 'Ref' 'Input' -> 'Clipboard' -> 'IO' ('Either' 'NoChange' ())\n--\n-- copyCuts :: 'Ref' 'Input' -> 'IO' ('Either' 'NoChange' ())\n--\n-- cut :: 'Ref' 'Input' -> 'IO' ('Either' 'NoChange' ())\n--\n-- cutFromCursor :: 'Ref' 'Input' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- cutRange :: 'Ref' 'Input' -> 'Int' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- destroy :: 'Ref' 'Input' -> 'IO' ()\n--\n-- getCursorColor :: 'Ref' 'Input' -> 'IO' 'Color'\n--\n-- getInputType :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getMark :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getMaximumSize :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getPosition :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getReadonly :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getShortcut :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getSize :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getTabNav :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- getTextcolor :: 'Ref' 'Input' -> 'IO' 'Color'\n--\n-- getTextfont :: 'Ref' 'Input' -> 'IO' 'Font'\n--\n-- getTextsize :: 'Ref' 'Input' -> 'IO' 'FontSize'\n--\n-- getValue :: 'Ref' 'Input' -> 'IO' 'String'\n--\n-- getWrap :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- handle :: 'Ref' 'Input' -> 'Event' -> 'IO' 'Int'\n--\n-- index :: 'Ref' 'Input' -> 'Int' -> 'IO' 'Char'\n--\n-- insert :: 'Ref' 'Input' -> 'String' -> 'IO' ('Either' 'NoChange' ())\n--\n-- insertWithLength :: 'Ref' 'Input' -> 'String' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- replace :: 'Ref' 'Input' -> 'Int' -> 'Int' -> 'String' -> 'IO' ('Either' 'NoChange' ())\n--\n-- setCursorColor :: 'Ref' 'Input' -> 'Color' -> 'IO' ()\n--\n-- setInputType :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setMark :: 'Ref' 'Input' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- setMaximumSize :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setPosition :: 'Ref' 'Input' -> 'Int' -> 'Maybe' 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- setReadonly :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setShortcut :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setSize :: 'Ref' 'Input' -> 'Size' -> 'IO' ()\n--\n-- setTabNav :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- setTextcolor :: 'Ref' 'Input' -> 'Color' -> 'IO' ()\n--\n-- setTextfont :: 'Ref' 'Input' -> 'Font' -> 'IO' ()\n--\n-- setTextsize :: 'Ref' 'Input' -> 'FontSize' -> 'IO' ()\n--\n-- setValue :: 'Ref' 'Input' -> 'String' -> 'Maybe' 'Int' -> 'IO' 'Int'\n--\n-- setWrap :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- staticValue :: 'Ref' 'Input' -> 'String' -> 'Maybe' 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- undo :: 'Ref' 'Input' -> 'IO' ('Either' 'NoChange' ())\n--\n-- @\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Input\"\n-- @","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Input\n (\n FlInputType,\n -- * Constructor\n inputNew\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Input\n --\n -- $Input\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_InputC.h\"\n#include \"Fl_Input_C.h\"\n#include \"Fl_Int_InputC.h\"\n#include \"Fl_Float_InputC.h\"\n#include \"Fl_Secret_InputC.h\"\n#include \"Fl_Multiline_InputC.h\"\n#include \"Fl_OutputC.h\"\n#include \"Fl_Multiline_OutputC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\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\nimport Graphics.UI.FLTK.LowLevel.Dispatch\n#c\nenum FlInputType {\n FlNormalInput = FL_NORMAL_INPUT,\n FlFloatInput = FL_FLOAT_INPUT,\n FlIntInput = FL_INT_INPUT,\n FlMultilineInput = FL_MULTILINE_INPUT,\n FlSecretInput = FL_SECRET_INPUT,\n FlNormalOutput = FL_NORMAL_OUTPUT,\n FlMultilineOutput = FL_MULTILINE_OUTPUT\n};\n#endc\n{#enum FlInputType {}#}\n{# fun Fl_Input_New as inputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Input_New_WithLabel as inputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Multiline_Input_New as multilineInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Multiline_Input_New_WithLabel as multilineInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Float_Input_New as floatInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Float_Input_New_WithLabel as floatInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Int_Input_New as intInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Int_Input_New_WithLabel as intInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Secret_Input_New as secretInputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Secret_Input_New_WithLabel as secretInputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Output_New as outputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Output_New_WithLabel as outputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\n{# fun Fl_Multiline_Output_New as multilineOutputNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Multiline_Output_New_WithLabel as multilineOutputNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\ninputNew :: Maybe FlInputType -> Rectangle -> Maybe String -> IO (Ref Input)\ninputNew flInputType rectangle l'=\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n constructor = case flInputType of\n Just FlNormalInput -> maybe inputNew' (\\l -> (\\x y w h -> inputNewWithLabel' x y w h l)) l'\n Just FlFloatInput -> maybe floatInputNew' (\\l -> (\\x y w h -> floatInputNewWithLabel' x y w h l)) l'\n Just FlIntInput -> maybe intInputNew' (\\l -> (\\x y w h -> intInputNewWithLabel' x y w h l)) l'\n Just FlMultilineInput -> maybe multilineInputNew' (\\l -> (\\x y w h -> multilineInputNewWithLabel' x y w h l)) l'\n Just FlSecretInput -> maybe secretInputNew' (\\l -> (\\x y w h -> secretInputNewWithLabel' x y w h l)) l'\n Just FlNormalOutput -> maybe outputNew' (\\l -> (\\x y w h -> outputNewWithLabel' x y w h l)) l'\n Just FlMultilineOutput -> maybe multilineOutputNew' (\\l -> (\\x y w h -> multilineOutputNewWithLabel' x y w h l)) l'\n Nothing -> inputNew'\n in\n constructor x_pos y_pos width height >>= toRef\n\n{# fun Fl_Input_Destroy as inputDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) Input orig impl where\n runOp _ _ win = swapRef win $ \\winPtr -> do\n inputDestroy' winPtr\n return nullPtr\n\n{#fun Fl_Input_handle as inputHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\n{#fun Fl_Secret_Input_handle as secretInputHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO Int)) => Op (Handle ()) Input orig impl where\n runOp _ _ input event =\n withRef\n input\n (\\p -> do\n t <- getInputType input\n case (toEnum (fromIntegral t)) of\n FlSecretInput -> secretInputHandle' p (fromIntegral . fromEnum $ event)\n _ -> inputHandle' p (fromIntegral . fromEnum $ event)\n )\n{# fun unsafe Fl_Input_set_value as setValue' { id `Ptr ()', unsafeToCString `String' } -> `Int' #}\n{# fun unsafe Fl_Input_set_value_with_length as setValueWithLength' { id `Ptr ()', unsafeToCString `String',`Int' } -> `Int' #}\ninstance (impl ~ (String -> Maybe Int -> IO (Int))) => Op (SetValue ()) Input orig impl where\n runOp _ _ input text l' =\n case l' of\n Nothing -> withRef input $ \\inputPtr -> setValue' inputPtr text\n Just l -> withRef input $ \\inputPtr -> setValueWithLength' inputPtr text l\n{# fun unsafe Fl_Input_static_value as staticValue' { id `Ptr ()', unsafeToCString `String' } -> `Int' #}\n{# fun unsafe Fl_Input_static_value_with_length as staticValueWithLength' { id `Ptr ()', unsafeToCString `String',`Int' } -> `Int' #}\ninstance (impl ~ (String -> Maybe Int -> IO (Either NoChange ()))) => Op (StaticValue ()) Input orig impl where\n runOp _ _ input text l'= do\n status' <- case l' of\n Nothing -> withRef input $ \\inputPtr -> staticValue' inputPtr text\n Just l -> withRef input $ \\inputPtr -> staticValueWithLength' inputPtr text l\n return $ successOrNoChange status'\n{# fun unsafe Fl_Input_value as value' { id `Ptr ()' } -> `String' #}\ninstance (impl ~ ( IO (String))) => Op (GetValue ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> value' inputPtr\n{# fun unsafe Fl_Input_index as index' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> IO (Char))) => Op (Index ()) Input orig impl where\n runOp _ _ input i = withRef input $ \\inputPtr -> index' inputPtr i >>= return . toEnum\n{# fun unsafe Fl_Input_set_size as setSize' { id `Ptr ()',`Int',`Int' } -> `()' #}\ninstance (impl ~ (Size -> IO ())) => Op (SetSize ()) Input orig impl where\n runOp _ _ input (Size (Width w') (Height h')) = withRef input $ \\inputPtr -> setSize' inputPtr w' h'\n{# fun unsafe Fl_Input_maximum_size as maximumSize' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetMaximumSize ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> maximumSize' inputPtr\n{# fun unsafe Fl_Input_size as size' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetSize ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> size' inputPtr\n{# fun unsafe Fl_Input_set_maximum_size as setMaximumSize' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetMaximumSize ()) Input orig impl where\n runOp _ _ input m = withRef input $ \\inputPtr -> setMaximumSize' inputPtr m\n{# fun unsafe Fl_Input_position as position' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetPosition ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> position' inputPtr\n{# fun unsafe Fl_Input_mark as mark' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetMark ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> mark' inputPtr\n{# fun unsafe Fl_Input_set_position_with_cursor_mark as setPositionWithCursorMark' { id `Ptr ()',`Int',`Int' } -> `Int' #}\n{# fun unsafe Fl_Input_set_position_n_n as setPositionNN' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> Maybe Int -> IO (Either NoChange ()))) => Op (SetPosition ()) Input orig impl where\n runOp _ _ input point mark = do\n status' <- case mark of\n Just m -> withRef input $ \\inputPtr -> setPositionWithCursorMark' inputPtr point m\n Nothing -> withRef input $ \\inputPtr -> setPositionNN' inputPtr point\n return $ successOrNoChange status'\n{# fun unsafe Fl_Input_set_mark as setMark' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> IO (Either NoChange ()))) => Op (SetMark ()) Input orig impl where\n runOp _ _ input m = withRef input $ \\inputPtr -> setMark' inputPtr m >>= return . successOrNoChange\n{# fun unsafe Fl_Input_replace as replace' { id `Ptr ()',`Int',`Int', unsafeToCString `String' } -> `Int' #}\ninstance (impl ~ (Int -> Int -> String -> IO (Either NoChange ()))) => Op (Replace ()) Input orig impl where\n runOp _ _ input b e text = withRef input $ \\inputPtr -> replace' inputPtr b e text >>= return . successOrNoChange\n{# fun unsafe Fl_Input_cut as cut' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Either NoChange ()))) => Op (Cut ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> cut' inputPtr >>= return . successOrNoChange\n{# fun unsafe Fl_Input_cut_bytes as cutBytes' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> IO (Either NoChange ()))) => Op (CutFromCursor ()) Input orig impl where\n runOp _ _ input n = withRef input $ \\inputPtr -> cutBytes' inputPtr n >>= return . successOrNoChange\n{# fun unsafe Fl_Input_cut_range as cutRange' { id `Ptr ()',`Int',`Int' } -> `Int' #}\ninstance (impl ~ (Int -> Int -> IO (Either NoChange ()))) => Op (CutRange ()) Input orig impl where\n runOp _ _ input a b = withRef input $ \\inputPtr -> cutRange' inputPtr a b >>= return . successOrNoChange\n{# fun unsafe Fl_Input_insert as insert' { id `Ptr ()', unsafeToCString `String' } -> `Int' #}\ninstance (impl ~ (String -> IO (Either NoChange ()))) => Op (Insert ()) Input orig impl where\n runOp _ _ input t = withRef input $ \\inputPtr -> insert' inputPtr t >>= return . successOrNoChange\n{# fun unsafe Fl_Input_insert_with_length as insertWithLength' { id `Ptr ()', unsafeToCString `String',`Int' } -> `Int' #}\ninstance (impl ~ (String -> Int -> IO (Either NoChange ()))) => Op (InsertWithLength ()) Input orig impl where\n runOp _ _ input t l = withRef input $ \\inputPtr -> insertWithLength' inputPtr t l >>= return . successOrNoChange\n{# fun unsafe Fl_Input_copy as copy' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Clipboard -> IO (Either NoChange ()))) => Op (Copy ()) Input orig impl where\n runOp _ _ input clipboard = do\n status' <- case clipboard of\n InternalClipboard -> withRef input $ \\inputPtr -> copy' inputPtr 1\n SharedClipboard -> withRef input $ \\inputPtr -> copy' inputPtr 0\n return $ successOrNoChange status'\n{# fun unsafe Fl_Input_undo as undo' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Either NoChange ()))) => Op (Undo ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> undo' inputPtr >>= return . successOrNoChange\n{# fun unsafe Fl_Input_copy_cuts as copyCuts' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Either NoChange ()))) => Op (CopyCuts ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> copyCuts' inputPtr >>= return . successOrNoChange\n{# fun unsafe Fl_Input_shortcut as shortcut' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetShortcut ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> shortcut' inputPtr\n{# fun unsafe Fl_Input_set_shortcut as setShortcut' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetShortcut ()) Input orig impl where\n runOp _ _ input s = withRef input $ \\inputPtr -> setShortcut' inputPtr s\n{# fun unsafe Fl_Input_textfont as textfont' { id `Ptr ()' } -> `Font' cToFont #}\ninstance (impl ~ ( IO (Font))) => Op (GetTextfont ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> textfont' inputPtr\n{# fun unsafe Fl_Input_set_textfont as setTextfont' { id `Ptr ()',cFromFont `Font' } -> `()' #}\ninstance (impl ~ (Font -> IO ())) => Op (SetTextfont ()) Input orig impl where\n runOp _ _ input s = withRef input $ \\inputPtr -> setTextfont' inputPtr s\n{# fun unsafe Fl_Input_textsize as textsize' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ ( IO (FontSize))) => Op (GetTextsize ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> textsize' inputPtr >>= return . FontSize\n{# fun unsafe Fl_Input_set_textsize as setTextsize' { id `Ptr ()', id `CInt' } -> `()' #}\ninstance (impl ~ (FontSize -> IO ())) => Op (SetTextsize ()) Input orig impl where\n runOp _ _ input (FontSize s) = withRef input $ \\inputPtr -> setTextsize' inputPtr s\n{# fun unsafe Fl_Input_textcolor as textcolor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ ( IO (Color))) => Op (GetTextcolor ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> textcolor' inputPtr\n{# fun unsafe Fl_Input_set_textcolor as setTextcolor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ninstance (impl ~ (Color -> IO ())) => Op (SetTextcolor ()) Input orig impl where\n runOp _ _ input n = withRef input $ \\inputPtr -> setTextcolor' inputPtr n\n{# fun unsafe Fl_Input_cursor_color as cursorColor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ ( IO (Color))) => Op (GetCursorColor ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> cursorColor' inputPtr\n{# fun unsafe Fl_Input_set_cursor_color as setCursorColor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ninstance (impl ~ (Color -> IO ())) => Op (SetCursorColor ()) Input orig impl where\n runOp _ _ input n = withRef input $ \\inputPtr -> setCursorColor' inputPtr n\n{# fun unsafe Fl_Input_input_type as inputType' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetInputType ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> inputType' inputPtr\n{# fun unsafe Fl_Input_set_input_type as setInputType' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetInputType ()) Input orig impl where\n runOp _ _ input t = withRef input $ \\inputPtr -> setInputType' inputPtr t\n{# fun unsafe Fl_Input_readonly as readonly' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetReadonly ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> readonly' inputPtr\n{# fun unsafe Fl_Input_set_readonly as setReadonly' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetReadonly ()) Input orig impl where\n runOp _ _ input b = withRef input $ \\inputPtr -> setReadonly' inputPtr b\n{# fun unsafe Fl_Input_wrap as wrap' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetWrap ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> wrap' inputPtr\n{# fun unsafe Fl_Input_set_wrap as setWrap' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetWrap ()) Input orig impl where\n runOp _ _ input b = withRef input $ \\inputPtr -> setWrap' inputPtr b\n{# fun unsafe Fl_Input_tab_nav as tabNav' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (GetTabNav ()) Input orig impl where\n runOp _ _ input val = withRef input $ \\inputPtr -> tabNav' inputPtr val\n{# fun unsafe Fl_Input_set_tab_nav as setTabNav' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (SetTabNav ()) Input orig impl where\n runOp _ _ input = withRef input $ \\inputPtr -> setTabNav' inputPtr\n\n-- $Input\n-- @\n--\n-- copy :: 'Ref' 'Input' -> 'Clipboard' -> 'IO' ('Either' 'NoChange' ())\n--\n-- copyCuts :: 'Ref' 'Input' -> 'IO' ('Either' 'NoChange' ())\n--\n-- cut :: 'Ref' 'Input' -> 'IO' ('Either' 'NoChange' ())\n--\n-- cutFromCursor :: 'Ref' 'Input' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- cutRange :: 'Ref' 'Input' -> 'Int' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- destroy :: 'Ref' 'Input' -> 'IO' ()\n--\n-- getCursorColor :: 'Ref' 'Input' -> 'IO' 'Color'\n--\n-- getInputType :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getMark :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getMaximumSize :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getPosition :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getReadonly :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getShortcut :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getSize :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- getTabNav :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- getTextcolor :: 'Ref' 'Input' -> 'IO' 'Color'\n--\n-- getTextfont :: 'Ref' 'Input' -> 'IO' 'Font'\n--\n-- getTextsize :: 'Ref' 'Input' -> 'IO' 'FontSize'\n--\n-- getValue :: 'Ref' 'Input' -> 'IO' 'String'\n--\n-- getWrap :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- handle :: 'Ref' 'Input' -> 'Event' -> 'IO' 'Int'\n--\n-- index :: 'Ref' 'Input' -> 'Int' -> 'IO' 'Char'\n--\n-- insert :: 'Ref' 'Input' -> 'String' -> 'IO' ('Either' 'NoChange' ())\n--\n-- insertWithLength :: 'Ref' 'Input' -> 'String' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- replace :: 'Ref' 'Input' -> 'Int' -> 'Int' -> 'String' -> 'IO' ('Either' 'NoChange' ())\n--\n-- setCursorColor :: 'Ref' 'Input' -> 'Color' -> 'IO' ()\n--\n-- setInputType :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setMark :: 'Ref' 'Input' -> 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- setMaximumSize :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setPosition :: 'Ref' 'Input' -> 'Int' -> 'Maybe' 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- setReadonly :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setShortcut :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- setSize :: 'Ref' 'Input' -> 'Size' -> 'IO' ()\n--\n-- setTabNav :: 'Ref' 'Input' -> 'IO' 'Int'\n--\n-- setTextcolor :: 'Ref' 'Input' -> 'Color' -> 'IO' ()\n--\n-- setTextfont :: 'Ref' 'Input' -> 'Font' -> 'IO' ()\n--\n-- setTextsize :: 'Ref' 'Input' -> 'FontSize' -> 'IO' ()\n--\n-- setValue :: 'Ref' 'Input' -> 'String' -> 'Maybe' 'Int' -> 'IO' 'Int'\n--\n-- setWrap :: 'Ref' 'Input' -> 'Int' -> 'IO' ()\n--\n-- staticValue :: 'Ref' 'Input' -> 'String' -> 'Maybe' 'Int' -> 'IO' ('Either' 'NoChange' ())\n--\n-- undo :: 'Ref' 'Input' -> 'IO' ('Either' 'NoChange' ())\n--\n-- @\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Input\"\n-- @","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"f6737c485200a3ebc48e3c115e0e9dae57257d8a","subject":"Fixed Widget function documentation","message":"Fixed Widget function documentation\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Widget.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Widget.chs","new_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Widget\n (\n -- * Constructor\n widgetCustom,\n widgetMaker,\n -- * Custom\n CustomWidgetFuncs(..),\n defaultCustomWidgetFuncs,\n fillCustomWidgetFunctionStruct,\n customWidgetFunctionStruct,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Widget Functions\n --\n -- $widgetfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\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.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\n\ntype RectangleFPrim = Ptr () -> CInt -> CInt -> CInt -> CInt -> IO ()\n\nforeign import ccall \"wrapper\"\n mkWidgetEventHandler :: (Ptr () -> CInt -> IO CInt) -> IO (FunPtr (Ptr () -> CInt -> IO CInt))\nforeign import ccall \"wrapper\"\n mkRectanglePtr :: RectangleFPrim -> IO (FunPtr RectangleFPrim)\n\ntoRectangleFPrim :: (Ref a -> Rectangle -> IO ()) ->\n IO (FunPtr (Ptr () -> CInt -> CInt -> CInt -> CInt -> IO ()))\ntoRectangleFPrim f = mkRectanglePtr $ \\wPtr x_pos y_pos width height ->\n let rectangle = toRectangle (fromIntegral x_pos,\n fromIntegral y_pos,\n fromIntegral width,\n fromIntegral height)\n in do\n fptr <- wrapNonNull wPtr \"Null Pointer. toRectangleFPrim\"\n f (wrapInRef fptr) rectangle\n\ntoEventHandlerPrim :: (Ref a -> Event -> IO (Either UnknownEvent ())) ->\n IO (FunPtr (Ptr () -> CInt -> IO CInt))\ntoEventHandlerPrim f = mkWidgetEventHandler $\n \\wPtr eventNumber ->\n let event = cToEnum (eventNumber :: CInt)\n in do\n fptr <- wrapNonNull wPtr \"Null Pointer: toEventHandlerPrim\"\n result <- f (wrapInRef fptr) event\n return (either (\\_ -> fromIntegral (0::CInt)) (const (fromIntegral (1::CInt))) result)\n\n-- | Overrideable 'Widget' functions\n-- | Do not create this directly. Instead use `defaultWidgetCustomFuncs`\ndata CustomWidgetFuncs a =\n CustomWidgetFuncs\n {\n -- | See \n handleCustom :: Maybe (Ref a -> Event -> IO (Either UnknownEvent ()))\n -- | See \n ,resizeCustom :: Maybe (Ref a -> Rectangle -> IO ())\n -- | See \n ,showCustom :: Maybe (Ref a -> IO ())\n -- | See \n ,hideCustom :: Maybe (Ref a -> IO ())\n }\n\n-- | Fill up a struct with pointers to functions on the Haskell side that will get called instead of the default ones.\n--\n-- Fill up the 'Widget' part the function pointer struct.\n--\n-- Only of interest to 'Widget' contributors\nfillCustomWidgetFunctionStruct :: forall a. (Parent a Widget) =>\n Ptr () ->\n Maybe (Ref a -> IO ()) ->\n CustomWidgetFuncs a ->\n IO ()\nfillCustomWidgetFunctionStruct structPtr _draw' (CustomWidgetFuncs _handle' _resize' _show' _hide') = do\n toCallbackPrim `orNullFunPtr` _draw' >>= {#set fl_Widget_Virtual_Funcs->draw#} structPtr\n toEventHandlerPrim `orNullFunPtr` _handle' >>= {#set fl_Widget_Virtual_Funcs->handle#} structPtr\n toRectangleFPrim `orNullFunPtr` _resize' >>= {#set fl_Widget_Virtual_Funcs->resize#} structPtr\n toCallbackPrim `orNullFunPtr` _show' >>= {#set fl_Widget_Virtual_Funcs->show#} structPtr\n toCallbackPrim `orNullFunPtr` _hide' >>= {#set fl_Widget_Virtual_Funcs->hide#} structPtr\n\n{# fun Fl_Widget_default_virtual_funcs as virtualFuncs' {} -> `Ptr ()' id #}\n\n-- | Given a record of functions, return a pointer to a struct with function pointers back to those functions.\n--\n-- Only of interest to 'Widget' contributors.\ncustomWidgetFunctionStruct :: forall a. (Parent a Widget) =>\n Maybe (Ref a -> IO ()) ->\n CustomWidgetFuncs a ->\n IO (Ptr ())\ncustomWidgetFunctionStruct draw' customWidgetFuncs' = do\n p <- virtualFuncs'\n fillCustomWidgetFunctionStruct p draw' customWidgetFuncs'\n return p\n\n-- | An empty set of functions to pass to 'widgetCustom'.\ndefaultCustomWidgetFuncs :: forall a. (Parent a Widget) => CustomWidgetFuncs a\ndefaultCustomWidgetFuncs =\n CustomWidgetFuncs\n Nothing\n Nothing\n Nothing\n Nothing\n\n-- | Lots of 'Widget' subclasses have the same constructor parameters. This function consolidates them.\n--\n-- Only of interest to 'Widget' contributors.\nwidgetMaker :: forall a. (Parent a Widget) =>\n Rectangle -- ^ Position and size\n -> Maybe T.Text -- ^ Title\n -> Maybe (Ref a -> IO ()) -- ^ Custom drawing function\n -> Maybe (CustomWidgetFuncs a) -- ^ Custom functions\n -> (Int -> Int -> Int -> Int -> Ptr () -> IO ( Ptr () )) -- ^ Foreign constructor to call if only custom functions are given\n -> (Int -> Int -> Int -> Int -> T.Text -> Ptr () -> IO ( Ptr () )) -- ^ Foreign constructor to call if both title and custom functions are given\n -> IO (Ref a) -- ^ Reference to the widget\nwidgetMaker rectangle _label' draw' customFuncs' newWithCustomFuncs' newWithCustomFuncsLabel' =\n do\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n ptr <- customWidgetFunctionStruct draw' (maybe defaultCustomWidgetFuncs id customFuncs')\n widget <- maybe (newWithCustomFuncs' x_pos y_pos width height (castPtr ptr))\n (\\l -> newWithCustomFuncsLabel' x_pos y_pos width height l (castPtr ptr))\n _label'\n toRef widget\n\n{# fun Fl_OverriddenWidget_New_WithLabel as overriddenWidgetNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWidget_New as overriddenWidgetNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n-- | Widget constructor.\nwidgetCustom :: Rectangle -- ^ The bounds of this widget\n -> Maybe T.Text -- ^ The widget label\n -> (Ref Widget -> IO ()) -- ^ Custom drawing function\n -> CustomWidgetFuncs Widget -- ^ Other custom functions\n -> IO (Ref Widget)\nwidgetCustom rectangle l' draw' funcs' =\n widgetMaker\n rectangle\n l'\n (Just draw')\n (Just funcs')\n overriddenWidgetNew'\n overriddenWidgetNewWithLabel'\n\n{# fun Fl_Widget_Destroy as widgetDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ IO ()) => Op (Destroy ()) Widget orig impl where\n runOp _ _ win = swapRef win $ \\winPtr -> do\n widgetDestroy' winPtr\n return nullPtr\n\n{#fun Fl_Widget_handle as widgetHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) Widget orig impl where\n runOp _ _ widget event = withRef widget (\\p -> widgetHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n{#fun Fl_Widget_parent as widgetParent' { id `Ptr ()'} -> `Ptr ()' id #}\ninstance (impl ~ IO (Maybe (Ref Group))) => Op (GetParent ()) Widget orig impl where\n runOp _ _ widget = withRef widget widgetParent' >>= toMaybeRef\n\n{#fun Fl_Widget_set_parent as widgetSetParent' { id `Ptr ()', id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Group, impl ~ (Maybe (Ref a) -> IO ())) => Op (SetParent ()) Widget orig impl where\n runOp _ _ widget group =\n withRef widget\n (\\widgetPtr ->\n withMaybeRef group (\\groupPtr ->\n widgetSetParent' widgetPtr groupPtr\n )\n )\n{# fun Fl_Widget_type as type' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ IO (Word8)) => Op (GetType_ ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr\n{# fun Fl_Widget_set_type as setType' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Word8 -> IO ())) => Op (SetType ()) Widget orig impl where\n runOp _ _ widget t = withRef widget $ \\widgetPtr -> setType' widgetPtr t\n{# fun Fl_Widget_draw_label as drawLabel' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_label_with_xywh_alignment as drawLabelWithXywhAlignment' { id `Ptr ()',`Int',`Int',`Int',`Int', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Maybe (Rectangle,Alignments) -> IO ())) => Op (DrawLabel ()) Widget orig impl where\n runOp _ _ widget Nothing = withRef widget $ \\widgetPtr -> drawLabel' widgetPtr\n runOp _ _ widget (Just (rectangle,align_)) = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n drawLabelWithXywhAlignment' widgetPtr x_pos y_pos w_pos h_pos (alignmentsToInt align_)\n\n{# fun Fl_Widget_x as x' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetX ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> x' widgetPtr\n{# fun Fl_Widget_y as y' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetY ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> y' widgetPtr\n{# fun Fl_Widget_w as w' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetW ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> w' widgetPtr\n{# fun Fl_Widget_h as h' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetH ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> h' widgetPtr\ninstance (\n Match obj ~ FindOp orig orig (GetX ()),\n Match obj ~ FindOp orig orig (GetY ()),\n Match obj ~ FindOp orig orig (GetW ()),\n Match obj ~ FindOp orig orig (GetH ()),\n Op (GetX ()) obj orig (IO Int),\n Op (GetY ()) obj orig (IO Int),\n Op (GetW ()) obj orig (IO Int),\n Op (GetH ()) obj orig (IO Int),\n impl ~ IO Rectangle\n )\n =>\n Op (GetRectangle ()) Widget orig impl where\n runOp _ _ widget = do\n _x <- getX (castTo widget :: Ref orig)\n _y <- getY (castTo widget :: Ref orig)\n _w <- getW (castTo widget :: Ref orig)\n _h <- getH (castTo widget :: Ref orig)\n return (toRectangle (_x,_y,_w,_h))\n{# fun Fl_Widget_set_align as setAlign' { id `Ptr ()', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Alignments -> IO ())) => Op (SetAlign ()) Widget orig impl where\n runOp _ _ widget _align = withRef widget $ \\widgetPtr -> setAlign' widgetPtr (alignmentsToInt _align)\n{# fun Fl_Widget_align as align' { id `Ptr ()' } -> `CUInt' id #}\ninstance (impl ~ IO Alignments) => Op (GetAlign ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> align' widgetPtr >>= return . intToAlignments . fromIntegral\n{# fun Fl_Widget_box as box' { id `Ptr ()' } -> `Boxtype' cToEnum #}\ninstance (impl ~ IO (Boxtype)) => Op (GetBox ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> box' widgetPtr\n{# fun Fl_Widget_set_box as setBox' { id `Ptr ()',cFromEnum `Boxtype' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Boxtype -> IO ())) => Op (SetBox ()) Widget orig impl where\n runOp _ _ widget new_box = withRef widget $ \\widgetPtr -> setBox' widgetPtr new_box\n{# fun Fl_Widget_color as color' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ IO (Color)) => Op (GetColor ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> color' widgetPtr\n{# fun Fl_Widget_set_color as setColor' { id `Ptr ()',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Color -> IO ())) => Op (SetColor ()) Widget orig impl where\n runOp _ _ widget bg = withRef widget $ \\widgetPtr -> setColor' widgetPtr bg\n{# fun Fl_Widget_set_color_with_bg_sel as setColorWithBgSel' { id `Ptr ()',cFromColor `Color',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Color -> Color -> IO ())) => Op (SetColorWithBgSel ()) Widget orig impl where\n runOp _ _ widget bg a = withRef widget $ \\widgetPtr -> setColorWithBgSel' widgetPtr bg a\n{# fun Fl_Widget_selection_color as selectionColor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ IO (Color)) => Op (GetSelectionColor ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> selectionColor' widgetPtr\n{# fun Fl_Widget_set_selection_color as setSelectionColor' { id `Ptr ()',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Color -> IO ())) => Op (SetSelectionColor ()) Widget orig impl where\n runOp _ _ widget a = withRef widget $ \\widgetPtr -> setSelectionColor' widgetPtr a\n{# fun Fl_Widget_label as label' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ IO T.Text) => Op (GetLabel ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> label' widgetPtr\n{# fun Fl_Widget_copy_label as copyLabel' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (CopyLabel ()) Widget orig impl where\n runOp _ _ widget new_label = withRef widget $ \\widgetPtr -> copyLabel' widgetPtr new_label\n{# fun Fl_Widget_set_label as setLabel' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( T.Text -> IO ())) => Op (SetLabel ()) Widget orig impl where\n runOp _ _ widget text = withRef widget $ \\widgetPtr -> setLabel' widgetPtr text\n{# fun Fl_Widget_labeltype as labeltype' { id `Ptr ()' } -> `Labeltype' cToEnum #}\ninstance (impl ~ (IO (Labeltype))) => Op (GetLabeltype ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labeltype' widgetPtr\n{# fun Fl_Widget_set_labeltype as setLabeltype' { id `Ptr ()',cFromEnum `Labeltype' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Labeltype -> IO ())) => Op (SetLabeltype ()) Widget orig impl where\n runOp _ _ widget a = withRef widget $ \\widgetPtr -> setLabeltype' widgetPtr a\n{# fun Fl_Widget_labelcolor as labelcolor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ (IO (Color))) => Op (GetLabelcolor ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labelcolor' widgetPtr\n{# fun Fl_Widget_set_labelcolor as setLabelcolor' { id `Ptr ()',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Color -> IO ())) => Op (SetLabelcolor ()) Widget orig impl where\n runOp _ _ widget c = withRef widget $ \\widgetPtr -> setLabelcolor' widgetPtr c\n{# fun Fl_Widget_labelfont as labelfont' { id `Ptr ()' } -> `Font' cToFont #}\ninstance (impl ~ (IO (Font))) => Op (GetLabelfont ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labelfont' widgetPtr\n{# fun Fl_Widget_set_labelfont as setLabelfont' { id `Ptr ()',cFromFont `Font' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Font -> IO ())) => Op (SetLabelfont ()) Widget orig impl where\n runOp _ _ widget c = withRef widget $ \\widgetPtr -> setLabelfont' widgetPtr c\n{# fun Fl_Widget_labelsize as labelsize' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ (IO (FontSize))) => Op (GetLabelsize ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labelsize' widgetPtr >>= return . FontSize\n{# fun Fl_Widget_set_labelsize as setLabelsize' { id `Ptr ()',id `CInt' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( FontSize -> IO ())) => Op (SetLabelsize ()) Widget orig impl where\n runOp _ _ widget (FontSize pix) = withRef widget $ \\widgetPtr -> setLabelsize' widgetPtr pix\n{# fun Fl_Widget_image as image' { id `Ptr ()' } -> `(Ref Image)' unsafeToRef #}\ninstance (impl ~ (IO (Ref Image))) => Op (GetImage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> image' widgetPtr\n{# fun Fl_Widget_set_image as setImage' { id `Ptr ()',id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (Parent a Image, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetImage ()) Widget orig impl where\n runOp _ _ widget pix = withRef widget $ \\widgetPtr -> withMaybeRef pix $ \\pixPtr -> setImage' widgetPtr pixPtr\n{# fun Fl_Widget_deimage as deimage' { id `Ptr ()' } -> `(Ref Image)' unsafeToRef #}\ninstance (impl ~ (IO (Ref Image))) => Op (GetDeimage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> deimage' widgetPtr\n{# fun Fl_Widget_set_deimage as setDeimage' { id `Ptr ()',id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (Parent a Image, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetDeimage ()) Widget orig impl where\n runOp _ _ widget pix = withRef widget $ \\widgetPtr -> withMaybeRef pix $ \\pixPtr -> setDeimage' widgetPtr pixPtr\n{# fun Fl_Widget_tooltip as tooltip' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ (IO T.Text)) => Op (GetTooltip ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> tooltip' widgetPtr\n{# fun Fl_Widget_copy_tooltip as copyTooltip' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( T.Text -> IO ())) => Op (CopyTooltip ()) Widget orig impl where\n runOp _ _ widget text = withRef widget $ \\widgetPtr -> copyTooltip' widgetPtr text\n{# fun Fl_Widget_set_tooltip as setTooltip' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( T.Text -> IO ())) => Op (SetTooltip ()) Widget orig impl where\n runOp _ _ widget text = withRef widget $ \\widgetPtr -> setTooltip' widgetPtr text\n{# fun Fl_Widget_when as when' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ IO [When]) => Op (GetWhen ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr ->\n when' widgetPtr >>= return . extract allWhen\n{# fun Fl_Widget_set_when as setWhen' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [When] -> IO ())) => Op (SetWhen ()) Widget orig impl where\n runOp _ _ widget i = withRef widget $ \\widgetPtr ->\n setWhen' widgetPtr (fromIntegral . combine $ i)\n{# fun Fl_Widget_do_callback as do_callback' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (DoCallback ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> do_callback' widgetPtr\n{# fun Fl_Widget_visible as visible' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO Bool)) => Op (GetVisible ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> visible' widgetPtr\n{# fun Fl_Widget_visible_r as visibleR' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO Bool)) => Op (GetVisibleR ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> visibleR' widgetPtr\n{# fun Fl_Widget_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidgetSuper ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> showSuper' widgetPtr\n{# fun Fl_Widget_show as show' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> show' widgetPtr\n{# fun Fl_Widget_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (HideSuper ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> hideSuper' widgetPtr\n{# fun Fl_Widget_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Hide ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> hide' widgetPtr\n{# fun Fl_Widget_set_visible as setVisible' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetVisible ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setVisible' widgetPtr\n{# fun Fl_Widget_clear_visible as clearVisible' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearVisible ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearVisible' widgetPtr\n{# fun Fl_Widget_active as active' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (Active ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> active' widgetPtr\n{# fun Fl_Widget_active_r as activeR' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (ActiveR ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> activeR' widgetPtr\n{# fun Fl_Widget_activate as activate' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Activate ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> activate' widgetPtr\n{# fun Fl_Widget_deactivate as deactivate' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Deactivate ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> deactivate' widgetPtr\n{# fun Fl_Widget_output as output' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ (IO (Int))) => Op (GetOutput ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> output' widgetPtr\n{# fun Fl_Widget_set_output as setOutput' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetOutput ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setOutput' widgetPtr\n{# fun Fl_Widget_clear_output as clearOutput' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearOutput ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearOutput' widgetPtr\n{# fun Fl_Widget_takesevents as takesevents' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (Takesevents ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> takesevents' widgetPtr\n{# fun Fl_Widget_set_active as setActive' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetActive ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setActive' widgetPtr\n{# fun Fl_Widget_clear_active as clearActive' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearActive ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearActive' widgetPtr\n{# fun Fl_Widget_set_changed as setChanged' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetChanged ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setChanged' widgetPtr\n{# fun Fl_Widget_clear_changed as clearChanged' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearChanged ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearChanged' widgetPtr\n{# fun Fl_Widget_changed as changed' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (Changed ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> changed' widgetPtr\n{# fun Fl_Widget_take_focus as takeFocus' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ (IO (Either NoChange ()))) => Op (TakeFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> takeFocus' widgetPtr >>= return . successOrNoChange\n{# fun Fl_Widget_set_visible_focus as setVisibleFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetVisibleFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setVisibleFocus' widgetPtr\n{# fun Fl_Widget_clear_visible_focus as clearVisibleFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearVisibleFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearVisibleFocus' widgetPtr\n{# fun Fl_Widget_modify_visible_focus as modifyVisibleFocus' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (ModifyVisibleFocus ()) Widget orig impl where\n runOp _ _ widget v = withRef widget $ \\widgetPtr -> modifyVisibleFocus' widgetPtr v\n{# fun Fl_Widget_visible_focus as visibleFocus' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (GetVisibleFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> visibleFocus' widgetPtr\n{# fun Fl_Widget_contains as contains' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO Int)) => Op (Contains ()) Widget orig impl where\n runOp _ _ widget otherWidget = withRef widget $ \\widgetPtr -> withRef otherWidget $ \\otherWidgetPtr -> contains' widgetPtr otherWidgetPtr\n{# fun Fl_Widget_inside as inside' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Inside ()) Widget orig impl where\n runOp _ _ widget otherWidget = withRef widget $ \\widgetPtr -> withRef otherWidget $ \\otherWidgetPtr -> inside' widgetPtr otherWidgetPtr\n{# fun Fl_Widget_redraw as redraw' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Redraw ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> redraw' widgetPtr\n{# fun Fl_Widget_redraw_label as redrawLabel' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (RedrawLabel ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> redrawLabel' widgetPtr\n{# fun Fl_Widget_damage as damage' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ (IO ([Damage]))) => Op (GetDamage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> do\n d <- damage' widgetPtr\n return (extract allDamages (fromIntegral d))\n{# fun Fl_Widget_clear_damage_with_bitmask as clearDamageWithBitmask' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [Damage] -> IO ())) => Op (ClearDamageExcept ()) Widget orig impl where\n runOp _ _ widget damages = withRef widget $ \\widgetPtr -> clearDamageWithBitmask' widgetPtr (fromIntegral (combine damages))\n{# fun Fl_Widget_clear_damage as clearDamage' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearDamage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearDamage' widgetPtr\n{# fun Fl_Widget_damage_with_text as damageWithText' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [Damage] -> IO ())) => Op (SetDamage ()) Widget orig impl where\n runOp _ _ widget damages = withRef widget $ \\widgetPtr -> damageWithText' widgetPtr (fromIntegral (combine damages))\n{# fun Fl_Widget_damage_inside_widget as damageInsideWidget' { id `Ptr ()',`Word8',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [Damage] -> Rectangle -> IO ())) => Op (SetDamageInside ()) Widget orig impl where\n runOp _ _ widget damages rectangle = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n damageInsideWidget' widgetPtr (fromIntegral (combine damages)) x_pos y_pos w_pos h_pos\n{# fun Fl_Widget_measure_label as measureLabel' {id `Ptr ()',alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' #}\ninstance (impl ~ ( IO (Size))) => Op (MeasureLabel ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> measureLabel' widgetPtr >>= \\(width, height) -> return $ Size (Width width) (Height height)\n{# fun Fl_Widget_window as window' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Window)))) => Op (GetWindow ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> window' widgetPtr >>= toMaybeRef\n{# fun Fl_Widget_top_window as topWindow' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Window)))) => Op (GetTopWindow ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> (topWindow' widgetPtr) >>= toMaybeRef\n{# fun Fl_Widget_top_window_offset as topWindowOffset' { id `Ptr ()',alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv* } -> `()' #}\ninstance (impl ~ ( IO (Position))) => Op (GetTopWindowOffset ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> topWindowOffset' widgetPtr >>= \\(x_pos,y_pos) -> return $ Position (X x_pos) (Y y_pos)\n{# fun Fl_Widget_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Rectangle -> IO ())) => Op (ResizeSuper ()) Widget orig impl where\n runOp _ _ widget rectangle = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n resizeSuper' widgetPtr x_pos y_pos w_pos h_pos\n{# fun Fl_Widget_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Rectangle -> IO ())) => Op (Resize ()) Widget orig impl where\n runOp _ _ widget rectangle = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n resize' widgetPtr x_pos y_pos w_pos h_pos\n{# fun Fl_Widget_set_callback as setCallback' { id `Ptr ()', id `FunPtr CallbackWithUserDataPrim'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ ((Ref orig -> IO ()) -> IO ())) => Op (SetCallback ()) Widget orig impl where\n runOp _ _ widget callback = withRef widget $ \\widgetPtr -> do\n ptr <- toCallbackPrimWithUserData callback\n setCallback' widgetPtr (castFunPtr ptr)\n\n{# fun Fl_Widget_has_callback as hasCallback' { id `Ptr ()' } -> `CInt' #}\ninstance (impl ~ (IO (Bool))) => Op (HasCallback ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> do\n res <- hasCallback' widgetPtr\n return $ if (res == 0) then False else True\n{# fun Fl_Widget_draw_box as widgetDrawBox' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_box_with_tc as widgetDrawBoxWithTC' { id `Ptr ()', cFromEnum `Boxtype', cFromColor`Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_box_with_txywhc as widgetDrawBoxWithTXywhC' { id `Ptr ()', cFromEnum `Boxtype', `Int',`Int',`Int',`Int', cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (DrawBox ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> widgetDrawBox' widgetPtr\ninstance (impl ~ ( Boxtype -> Color -> Maybe Rectangle -> IO ())) => Op (DrawBoxWithBoxtype ()) Widget orig impl where\n runOp _ _ widget bx c Nothing =\n withRef widget $ \\widgetPtr -> widgetDrawBoxWithTC' widgetPtr bx c\n runOp _ _ widget bx c (Just r) =\n withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n widgetDrawBoxWithTXywhC' widgetPtr bx x_pos y_pos w_pos h_pos c\n{# fun Fl_Widget_draw_backdrop as widgetDrawBackdrop' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (DrawBackdrop ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> widgetDrawBackdrop' widgetPtr\n\n{# fun Fl_Widget_draw_focus as widgetDrawFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_focus_with_txywh as widgetDrawFocusWithTXywh' { id `Ptr ()', cFromEnum `Boxtype', `Int', `Int', `Int', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Maybe (Boxtype, Rectangle) -> IO ())) => Op (DrawFocus ()) Widget orig impl where\n runOp _ _ widget Nothing =\n withRef widget $ \\ widgetPtr -> widgetDrawFocus' widgetPtr\n runOp _ _ widget (Just (bx, r)) =\n withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n widgetDrawFocusWithTXywh' widgetPtr bx x_pos y_pos w_pos h_pos\n\n-- $widgetfunctions\n-- @\n-- activate :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- active :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- activeR :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- changed :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- clearActive :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearChanged :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearDamage :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearDamageExcept :: 'Ref' 'Widget' -> ['Damage'] -> 'IO' ()\n--\n-- clearOutput :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearVisible :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearVisibleFocus :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- contains:: ('Parent' a 'Widget') => 'Ref' 'Widget' -> 'Ref' a -> 'IO' 'Int'\n--\n-- copyLabel :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- copyTooltip :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- deactivate :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- doCallback :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- drawBackdrop :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- drawBox :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- drawBoxWithBoxtype :: 'Ref' 'Widget' -> 'Boxtype' -> 'Color' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- drawFocus :: 'Ref' 'Widget' -> 'Maybe' ('Boxtype', 'Rectangle') -> 'IO' ()\n--\n-- drawLabel :: 'Ref' 'Widget' -> 'Maybe' ('Rectangle,Alignments') -> 'IO' ()\n--\n-- getAlign :: 'Ref' 'Widget' -> 'IO' 'Alignments'\n--\n-- getBox :: 'Ref' 'Widget' -> 'IO' ('Boxtype')\n--\n-- getColor :: 'Ref' 'Widget' -> 'IO' ('Color')\n--\n-- getDamage :: 'Ref' 'Widget' -> 'IO' (['Damage')]\n--\n-- getDeimage :: 'Ref' 'Widget' -> 'IO' ('Ref' 'Image')\n--\n-- getH :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getImage :: 'Ref' 'Widget' -> 'IO' ('Ref' 'Image')\n--\n-- getLabel :: 'Ref' 'Widget' -> 'IO' 'T.Text'\n--\n-- getLabelcolor :: 'Ref' 'Widget' -> 'IO' ('Color')\n--\n-- getLabelfont :: 'Ref' 'Widget' -> 'IO' ('Font')\n--\n-- getLabelsize :: 'Ref' 'Widget' -> 'IO' ('FontSize')\n--\n-- getLabeltype :: 'Ref' 'Widget' -> 'IO' ('Labeltype')\n--\n-- getOutput :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getParent :: 'Ref' 'Widget' -> 'IO' ('Maybe' ('Ref' 'Group'))\n--\n-- getRectangle:: ('Match' obj ~ 'FindOp' orig orig ('GetX' ()), 'Match' obj ~ 'FindOp' orig orig ('GetY' ()), 'Match' obj ~ 'FindOp' orig orig ('GetW' ()), 'Match' obj ~ 'FindOp' orig orig ('GetH' ()), 'Op' ('GetX' ()) obj orig ('IO' 'Int',) 'Op' ('GetY' ()) obj orig ('IO' 'Int',) 'Op' ('GetW' ()) obj orig ('IO' 'Int',) 'Op' ('GetH' ()) obj orig ('IO' 'Int',)) => 'Ref' 'Widget' -> 'IO' 'Rectangle'\n--\n-- getSelectionColor :: 'Ref' 'Widget' -> 'IO' ('Color')\n--\n-- getTooltip :: 'Ref' 'Widget' -> 'IO' 'T.Text'\n--\n-- getTopWindow :: 'Ref' 'Widget' -> 'IO' ('Maybe' ('Ref' 'Window'))\n--\n-- getTopWindowOffset :: 'Ref' 'Widget' -> 'IO' ('Position')\n--\n-- getType_ :: 'Ref' 'Widget' -> 'IO' ('Word8')\n--\n-- getVisible :: 'Ref' 'Widget' -> 'IO' 'Bool'\n--\n-- getVisibleFocus :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- getVisibleR :: 'Ref' 'Widget' -> 'IO' 'Bool'\n--\n-- getW :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getWhen :: 'Ref' 'Widget' -> 'IO' ['When']\n--\n-- getWindow :: 'Ref' 'Widget' -> 'IO' ('Maybe' ('Ref' 'Window'))\n--\n-- getX :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getY :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- handle :: 'Ref' 'Widget' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n--\n-- hasCallback :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- hide :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- hideSuper :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- inside:: ('Parent' a 'Widget') => 'Ref' 'Widget' -> 'Ref' a -> 'IO' ('Int')\n--\n-- measureLabel :: 'Ref' 'Widget' -> 'IO' ('Size')\n--\n-- modifyVisibleFocus :: 'Ref' 'Widget' -> 'Int' -> 'IO' ()\n--\n-- redraw :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- redrawLabel :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- resize :: 'Ref' 'Widget' -> 'Rectangle' -> 'IO' ()\n--\n-- resizeSuper :: 'Ref' 'Widget' -> 'Rectangle' -> 'IO' ()\n--\n-- setActive :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setAlign :: 'Ref' 'Widget' -> 'Alignments' -> 'IO' ()\n--\n-- setBox :: 'Ref' 'Widget' -> 'Boxtype' -> 'IO' ()\n--\n-- setCallback :: 'Ref' 'Widget' -> ('Ref' orig -> 'IO' ()) -> 'IO' ()\n--\n-- setChanged :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setColor :: 'Ref' 'Widget' -> 'Color' -> 'IO' ()\n--\n-- setColorWithBgSel :: 'Ref' 'Widget' -> 'Color' -> 'Color' -> 'IO' ()\n--\n-- setDamage :: 'Ref' 'Widget' -> ['Damage'] -> 'IO' ()\n--\n-- setDamageInside :: 'Ref' 'Widget' -> ['Damage'] -> 'Rectangle' -> 'IO' ()\n--\n-- setDeimage:: ('Parent' a 'Image') => 'Ref' 'Widget' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setImage:: ('Parent' a 'Image') => 'Ref' 'Widget' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setLabel :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- setLabelcolor :: 'Ref' 'Widget' -> 'Color' -> 'IO' ()\n--\n-- setLabelfont :: 'Ref' 'Widget' -> 'Font' -> 'IO' ()\n--\n-- setLabelsize :: 'Ref' 'Widget' -> 'FontSize' -> 'IO' ()\n--\n-- setLabeltype :: 'Ref' 'Widget' -> 'Labeltype' -> 'IO' ()\n--\n-- setOutput :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setParent:: ('Parent' a 'Group') => 'Ref' 'Widget' -> 'Maybe' ('Ref' a) -> 'IO' ()\n--\n-- setSelectionColor :: 'Ref' 'Widget' -> 'Color' -> 'IO' ()\n--\n-- setTooltip :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- setType :: 'Ref' 'Widget' -> 'Word8' -> 'IO' ()\n--\n-- setVisible :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setVisibleFocus :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setWhen :: 'Ref' 'Widget' -> ['When'] -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- showWidgetSuper :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- takeFocus :: 'Ref' 'Widget' -> 'IO' ('Either' 'NoChange' ())\n--\n-- takesevents :: 'Ref' 'Widget' -> 'IO' ('Bool')\n-- @\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- @\n","old_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Widget\n (\n -- * Constructor\n widgetCustom,\n widgetMaker,\n -- * Custom\n CustomWidgetFuncs(..),\n defaultCustomWidgetFuncs,\n fillCustomWidgetFunctionStruct,\n customWidgetFunctionStruct,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Widget Functions\n --\n -- $widgetfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\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.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\n\ntype RectangleFPrim = Ptr () -> CInt -> CInt -> CInt -> CInt -> IO ()\n\nforeign import ccall \"wrapper\"\n mkWidgetEventHandler :: (Ptr () -> CInt -> IO CInt) -> IO (FunPtr (Ptr () -> CInt -> IO CInt))\nforeign import ccall \"wrapper\"\n mkRectanglePtr :: RectangleFPrim -> IO (FunPtr RectangleFPrim)\n\ntoRectangleFPrim :: (Ref a -> Rectangle -> IO ()) ->\n IO (FunPtr (Ptr () -> CInt -> CInt -> CInt -> CInt -> IO ()))\ntoRectangleFPrim f = mkRectanglePtr $ \\wPtr x_pos y_pos width height ->\n let rectangle = toRectangle (fromIntegral x_pos,\n fromIntegral y_pos,\n fromIntegral width,\n fromIntegral height)\n in do\n fptr <- wrapNonNull wPtr \"Null Pointer. toRectangleFPrim\"\n f (wrapInRef fptr) rectangle\n\ntoEventHandlerPrim :: (Ref a -> Event -> IO (Either UnknownEvent ())) ->\n IO (FunPtr (Ptr () -> CInt -> IO CInt))\ntoEventHandlerPrim f = mkWidgetEventHandler $\n \\wPtr eventNumber ->\n let event = cToEnum (eventNumber :: CInt)\n in do\n fptr <- wrapNonNull wPtr \"Null Pointer: toEventHandlerPrim\"\n result <- f (wrapInRef fptr) event\n return (either (\\_ -> fromIntegral (0::CInt)) (const (fromIntegral (1::CInt))) result)\n\n-- | Overrideable 'Widget' functions\n-- | Do not create this directly. Instead use `defaultWidgetCustomFuncs`\ndata CustomWidgetFuncs a =\n CustomWidgetFuncs\n {\n -- | See \n handleCustom :: Maybe (Ref a -> Event -> IO (Either UnknownEvent ()))\n -- | See \n ,resizeCustom :: Maybe (Ref a -> Rectangle -> IO ())\n -- | See \n ,showCustom :: Maybe (Ref a -> IO ())\n -- | See \n ,hideCustom :: Maybe (Ref a -> IO ())\n }\n\n-- | Fill up a struct with pointers to functions on the Haskell side that will get called instead of the default ones.\n--\n-- Fill up the 'Widget' part the function pointer struct.\n--\n-- Only of interest to 'Widget' contributors\nfillCustomWidgetFunctionStruct :: forall a. (Parent a Widget) =>\n Ptr () ->\n Maybe (Ref a -> IO ()) ->\n CustomWidgetFuncs a ->\n IO ()\nfillCustomWidgetFunctionStruct structPtr _draw' (CustomWidgetFuncs _handle' _resize' _show' _hide') = do\n toCallbackPrim `orNullFunPtr` _draw' >>= {#set fl_Widget_Virtual_Funcs->draw#} structPtr\n toEventHandlerPrim `orNullFunPtr` _handle' >>= {#set fl_Widget_Virtual_Funcs->handle#} structPtr\n toRectangleFPrim `orNullFunPtr` _resize' >>= {#set fl_Widget_Virtual_Funcs->resize#} structPtr\n toCallbackPrim `orNullFunPtr` _show' >>= {#set fl_Widget_Virtual_Funcs->show#} structPtr\n toCallbackPrim `orNullFunPtr` _hide' >>= {#set fl_Widget_Virtual_Funcs->hide#} structPtr\n\n{# fun Fl_Widget_default_virtual_funcs as virtualFuncs' {} -> `Ptr ()' id #}\n\n-- | Given a record of functions, return a pointer to a struct with function pointers back to those functions.\n--\n-- Only of interest to 'Widget' contributors.\ncustomWidgetFunctionStruct :: forall a. (Parent a Widget) =>\n Maybe (Ref a -> IO ()) ->\n CustomWidgetFuncs a ->\n IO (Ptr ())\ncustomWidgetFunctionStruct draw' customWidgetFuncs' = do\n p <- virtualFuncs'\n fillCustomWidgetFunctionStruct p draw' customWidgetFuncs'\n return p\n\n-- | An empty set of functions to pass to 'widgetCustom'.\ndefaultCustomWidgetFuncs :: forall a. (Parent a Widget) => CustomWidgetFuncs a\ndefaultCustomWidgetFuncs =\n CustomWidgetFuncs\n Nothing\n Nothing\n Nothing\n Nothing\n\n-- | Lots of 'Widget' subclasses have the same constructor parameters. This function consolidates them.\n--\n-- Only of interest to 'Widget' contributors.\nwidgetMaker :: forall a. (Parent a Widget) =>\n Rectangle -- ^ Position and size\n -> Maybe T.Text -- ^ Title\n -> Maybe (Ref a -> IO ()) -- ^ Custom drawing function\n -> Maybe (CustomWidgetFuncs a) -- ^ Custom functions\n -> (Int -> Int -> Int -> Int -> Ptr () -> IO ( Ptr () )) -- ^ Foreign constructor to call if only custom functions are given\n -> (Int -> Int -> Int -> Int -> T.Text -> Ptr () -> IO ( Ptr () )) -- ^ Foreign constructor to call if both title and custom functions are given\n -> IO (Ref a) -- ^ Reference to the widget\nwidgetMaker rectangle _label' draw' customFuncs' newWithCustomFuncs' newWithCustomFuncsLabel' =\n do\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n ptr <- customWidgetFunctionStruct draw' (maybe defaultCustomWidgetFuncs id customFuncs')\n widget <- maybe (newWithCustomFuncs' x_pos y_pos width height (castPtr ptr))\n (\\l -> newWithCustomFuncsLabel' x_pos y_pos width height l (castPtr ptr))\n _label'\n toRef widget\n\n{# fun Fl_OverriddenWidget_New_WithLabel as overriddenWidgetNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWidget_New as overriddenWidgetNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n-- | Widget constructor.\nwidgetCustom :: Rectangle -- ^ The bounds of this widget\n -> Maybe T.Text -- ^ The widget label\n -> (Ref Widget -> IO ()) -- ^ Custom drawing function\n -> CustomWidgetFuncs Widget -- ^ Other custom functions\n -> IO (Ref Widget)\nwidgetCustom rectangle l' draw' funcs' =\n widgetMaker\n rectangle\n l'\n (Just draw')\n (Just funcs')\n overriddenWidgetNew'\n overriddenWidgetNewWithLabel'\n\n{# fun Fl_Widget_Destroy as widgetDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ IO ()) => Op (Destroy ()) Widget orig impl where\n runOp _ _ win = swapRef win $ \\winPtr -> do\n widgetDestroy' winPtr\n return nullPtr\n\n{#fun Fl_Widget_handle as widgetHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) Widget orig impl where\n runOp _ _ widget event = withRef widget (\\p -> widgetHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n{#fun Fl_Widget_parent as widgetParent' { id `Ptr ()'} -> `Ptr ()' id #}\ninstance (impl ~ IO (Maybe (Ref Group))) => Op (GetParent ()) Widget orig impl where\n runOp _ _ widget = withRef widget widgetParent' >>= toMaybeRef\n\n{#fun Fl_Widget_set_parent as widgetSetParent' { id `Ptr ()', id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Group, impl ~ (Maybe (Ref a) -> IO ())) => Op (SetParent ()) Widget orig impl where\n runOp _ _ widget group =\n withRef widget\n (\\widgetPtr ->\n withMaybeRef group (\\groupPtr ->\n widgetSetParent' widgetPtr groupPtr\n )\n )\n{# fun Fl_Widget_type as type' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ IO (Word8)) => Op (GetType_ ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr\n{# fun Fl_Widget_set_type as setType' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Word8 -> IO ())) => Op (SetType ()) Widget orig impl where\n runOp _ _ widget t = withRef widget $ \\widgetPtr -> setType' widgetPtr t\n{# fun Fl_Widget_draw_label as drawLabel' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_label_with_xywh_alignment as drawLabelWithXywhAlignment' { id `Ptr ()',`Int',`Int',`Int',`Int', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Maybe (Rectangle,Alignments) -> IO ())) => Op (DrawLabel ()) Widget orig impl where\n runOp _ _ widget Nothing = withRef widget $ \\widgetPtr -> drawLabel' widgetPtr\n runOp _ _ widget (Just (rectangle,align_)) = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n drawLabelWithXywhAlignment' widgetPtr x_pos y_pos w_pos h_pos (alignmentsToInt align_)\n\n{# fun Fl_Widget_x as x' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetX ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> x' widgetPtr\n{# fun Fl_Widget_y as y' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetY ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> y' widgetPtr\n{# fun Fl_Widget_w as w' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetW ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> w' widgetPtr\n{# fun Fl_Widget_h as h' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ IO (Int)) => Op (GetH ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> h' widgetPtr\ninstance (\n Match obj ~ FindOp orig orig (GetX ()),\n Match obj ~ FindOp orig orig (GetY ()),\n Match obj ~ FindOp orig orig (GetW ()),\n Match obj ~ FindOp orig orig (GetH ()),\n Op (GetX ()) obj orig (IO Int),\n Op (GetY ()) obj orig (IO Int),\n Op (GetW ()) obj orig (IO Int),\n Op (GetH ()) obj orig (IO Int),\n impl ~ IO Rectangle\n )\n =>\n Op (GetRectangle ()) Widget orig impl where\n runOp _ _ widget = do\n _x <- getX (castTo widget :: Ref orig)\n _y <- getY (castTo widget :: Ref orig)\n _w <- getW (castTo widget :: Ref orig)\n _h <- getH (castTo widget :: Ref orig)\n return (toRectangle (_x,_y,_w,_h))\n{# fun Fl_Widget_set_align as setAlign' { id `Ptr ()', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Alignments -> IO ())) => Op (SetAlign ()) Widget orig impl where\n runOp _ _ widget _align = withRef widget $ \\widgetPtr -> setAlign' widgetPtr (alignmentsToInt _align)\n{# fun Fl_Widget_align as align' { id `Ptr ()' } -> `CUInt' id #}\ninstance (impl ~ IO Alignments) => Op (GetAlign ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> align' widgetPtr >>= return . intToAlignments . fromIntegral\n{# fun Fl_Widget_box as box' { id `Ptr ()' } -> `Boxtype' cToEnum #}\ninstance (impl ~ IO (Boxtype)) => Op (GetBox ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> box' widgetPtr\n{# fun Fl_Widget_set_box as setBox' { id `Ptr ()',cFromEnum `Boxtype' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Boxtype -> IO ())) => Op (SetBox ()) Widget orig impl where\n runOp _ _ widget new_box = withRef widget $ \\widgetPtr -> setBox' widgetPtr new_box\n{# fun Fl_Widget_color as color' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ IO (Color)) => Op (GetColor ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> color' widgetPtr\n{# fun Fl_Widget_set_color as setColor' { id `Ptr ()',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Color -> IO ())) => Op (SetColor ()) Widget orig impl where\n runOp _ _ widget bg = withRef widget $ \\widgetPtr -> setColor' widgetPtr bg\n{# fun Fl_Widget_set_color_with_bg_sel as setColorWithBgSel' { id `Ptr ()',cFromColor `Color',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Color -> Color -> IO ())) => Op (SetColorWithBgSel ()) Widget orig impl where\n runOp _ _ widget bg a = withRef widget $ \\widgetPtr -> setColorWithBgSel' widgetPtr bg a\n{# fun Fl_Widget_selection_color as selectionColor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ IO (Color)) => Op (GetSelectionColor ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> selectionColor' widgetPtr\n{# fun Fl_Widget_set_selection_color as setSelectionColor' { id `Ptr ()',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Color -> IO ())) => Op (SetSelectionColor ()) Widget orig impl where\n runOp _ _ widget a = withRef widget $ \\widgetPtr -> setSelectionColor' widgetPtr a\n{# fun Fl_Widget_label as label' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ IO T.Text) => Op (GetLabel ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> label' widgetPtr\n{# fun Fl_Widget_copy_label as copyLabel' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (CopyLabel ()) Widget orig impl where\n runOp _ _ widget new_label = withRef widget $ \\widgetPtr -> copyLabel' widgetPtr new_label\n{# fun Fl_Widget_set_label as setLabel' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( T.Text -> IO ())) => Op (SetLabel ()) Widget orig impl where\n runOp _ _ widget text = withRef widget $ \\widgetPtr -> setLabel' widgetPtr text\n{# fun Fl_Widget_labeltype as labeltype' { id `Ptr ()' } -> `Labeltype' cToEnum #}\ninstance (impl ~ (IO (Labeltype))) => Op (GetLabeltype ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labeltype' widgetPtr\n{# fun Fl_Widget_set_labeltype as setLabeltype' { id `Ptr ()',cFromEnum `Labeltype' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Labeltype -> IO ())) => Op (SetLabeltype ()) Widget orig impl where\n runOp _ _ widget a = withRef widget $ \\widgetPtr -> setLabeltype' widgetPtr a\n{# fun Fl_Widget_labelcolor as labelcolor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ (IO (Color))) => Op (GetLabelcolor ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labelcolor' widgetPtr\n{# fun Fl_Widget_set_labelcolor as setLabelcolor' { id `Ptr ()',cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Color -> IO ())) => Op (SetLabelcolor ()) Widget orig impl where\n runOp _ _ widget c = withRef widget $ \\widgetPtr -> setLabelcolor' widgetPtr c\n{# fun Fl_Widget_labelfont as labelfont' { id `Ptr ()' } -> `Font' cToFont #}\ninstance (impl ~ (IO (Font))) => Op (GetLabelfont ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labelfont' widgetPtr\n{# fun Fl_Widget_set_labelfont as setLabelfont' { id `Ptr ()',cFromFont `Font' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Font -> IO ())) => Op (SetLabelfont ()) Widget orig impl where\n runOp _ _ widget c = withRef widget $ \\widgetPtr -> setLabelfont' widgetPtr c\n{# fun Fl_Widget_labelsize as labelsize' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ (IO (FontSize))) => Op (GetLabelsize ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> labelsize' widgetPtr >>= return . FontSize\n{# fun Fl_Widget_set_labelsize as setLabelsize' { id `Ptr ()',id `CInt' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( FontSize -> IO ())) => Op (SetLabelsize ()) Widget orig impl where\n runOp _ _ widget (FontSize pix) = withRef widget $ \\widgetPtr -> setLabelsize' widgetPtr pix\n{# fun Fl_Widget_image as image' { id `Ptr ()' } -> `(Ref Image)' unsafeToRef #}\ninstance (impl ~ (IO (Ref Image))) => Op (GetImage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> image' widgetPtr\n{# fun Fl_Widget_set_image as setImage' { id `Ptr ()',id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (Parent a Image, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetImage ()) Widget orig impl where\n runOp _ _ widget pix = withRef widget $ \\widgetPtr -> withMaybeRef pix $ \\pixPtr -> setImage' widgetPtr pixPtr\n{# fun Fl_Widget_deimage as deimage' { id `Ptr ()' } -> `(Ref Image)' unsafeToRef #}\ninstance (impl ~ (IO (Ref Image))) => Op (GetDeimage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> deimage' widgetPtr\n{# fun Fl_Widget_set_deimage as setDeimage' { id `Ptr ()',id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (Parent a Image, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetDeimage ()) Widget orig impl where\n runOp _ _ widget pix = withRef widget $ \\widgetPtr -> withMaybeRef pix $ \\pixPtr -> setDeimage' widgetPtr pixPtr\n{# fun Fl_Widget_tooltip as tooltip' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ (IO T.Text)) => Op (GetTooltip ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> tooltip' widgetPtr\n{# fun Fl_Widget_copy_tooltip as copyTooltip' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( T.Text -> IO ())) => Op (CopyTooltip ()) Widget orig impl where\n runOp _ _ widget text = withRef widget $ \\widgetPtr -> copyTooltip' widgetPtr text\n{# fun Fl_Widget_set_tooltip as setTooltip' { id `Ptr ()', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( T.Text -> IO ())) => Op (SetTooltip ()) Widget orig impl where\n runOp _ _ widget text = withRef widget $ \\widgetPtr -> setTooltip' widgetPtr text\n{# fun Fl_Widget_when as when' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ IO [When]) => Op (GetWhen ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr ->\n when' widgetPtr >>= return . extract allWhen\n{# fun Fl_Widget_set_when as setWhen' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [When] -> IO ())) => Op (SetWhen ()) Widget orig impl where\n runOp _ _ widget i = withRef widget $ \\widgetPtr ->\n setWhen' widgetPtr (fromIntegral . combine $ i)\n{# fun Fl_Widget_do_callback as do_callback' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (DoCallback ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> do_callback' widgetPtr\n{# fun Fl_Widget_visible as visible' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO Bool)) => Op (GetVisible ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> visible' widgetPtr\n{# fun Fl_Widget_visible_r as visibleR' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO Bool)) => Op (GetVisibleR ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> visibleR' widgetPtr\n{# fun Fl_Widget_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidgetSuper ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> showSuper' widgetPtr\n{# fun Fl_Widget_show as show' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> show' widgetPtr\n{# fun Fl_Widget_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (HideSuper ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> hideSuper' widgetPtr\n{# fun Fl_Widget_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Hide ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> hide' widgetPtr\n{# fun Fl_Widget_set_visible as setVisible' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetVisible ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setVisible' widgetPtr\n{# fun Fl_Widget_clear_visible as clearVisible' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearVisible ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearVisible' widgetPtr\n{# fun Fl_Widget_active as active' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (Active ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> active' widgetPtr\n{# fun Fl_Widget_active_r as activeR' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (ActiveR ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> activeR' widgetPtr\n{# fun Fl_Widget_activate as activate' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Activate ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> activate' widgetPtr\n{# fun Fl_Widget_deactivate as deactivate' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Deactivate ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> deactivate' widgetPtr\n{# fun Fl_Widget_output as output' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ (IO (Int))) => Op (GetOutput ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> output' widgetPtr\n{# fun Fl_Widget_set_output as setOutput' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetOutput ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setOutput' widgetPtr\n{# fun Fl_Widget_clear_output as clearOutput' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearOutput ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearOutput' widgetPtr\n{# fun Fl_Widget_takesevents as takesevents' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (Takesevents ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> takesevents' widgetPtr\n{# fun Fl_Widget_set_active as setActive' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetActive ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setActive' widgetPtr\n{# fun Fl_Widget_clear_active as clearActive' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearActive ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearActive' widgetPtr\n{# fun Fl_Widget_set_changed as setChanged' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetChanged ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setChanged' widgetPtr\n{# fun Fl_Widget_clear_changed as clearChanged' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearChanged ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearChanged' widgetPtr\n{# fun Fl_Widget_changed as changed' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (Changed ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> changed' widgetPtr\n{# fun Fl_Widget_take_focus as takeFocus' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ (IO (Either NoChange ()))) => Op (TakeFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> takeFocus' widgetPtr >>= return . successOrNoChange\n{# fun Fl_Widget_set_visible_focus as setVisibleFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (SetVisibleFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> setVisibleFocus' widgetPtr\n{# fun Fl_Widget_clear_visible_focus as clearVisibleFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearVisibleFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearVisibleFocus' widgetPtr\n{# fun Fl_Widget_modify_visible_focus as modifyVisibleFocus' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (ModifyVisibleFocus ()) Widget orig impl where\n runOp _ _ widget v = withRef widget $ \\widgetPtr -> modifyVisibleFocus' widgetPtr v\n{# fun Fl_Widget_visible_focus as visibleFocus' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ (IO (Bool))) => Op (GetVisibleFocus ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> visibleFocus' widgetPtr\n{# fun Fl_Widget_contains as contains' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO Int)) => Op (Contains ()) Widget orig impl where\n runOp _ _ widget otherWidget = withRef widget $ \\widgetPtr -> withRef otherWidget $ \\otherWidgetPtr -> contains' widgetPtr otherWidgetPtr\n{# fun Fl_Widget_inside as inside' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Inside ()) Widget orig impl where\n runOp _ _ widget otherWidget = withRef widget $ \\widgetPtr -> withRef otherWidget $ \\otherWidgetPtr -> inside' widgetPtr otherWidgetPtr\n{# fun Fl_Widget_redraw as redraw' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Redraw ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> redraw' widgetPtr\n{# fun Fl_Widget_redraw_label as redrawLabel' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (RedrawLabel ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> redrawLabel' widgetPtr\n{# fun Fl_Widget_damage as damage' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ (IO ([Damage]))) => Op (GetDamage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> do\n d <- damage' widgetPtr\n return (extract allDamages (fromIntegral d))\n{# fun Fl_Widget_clear_damage_with_bitmask as clearDamageWithBitmask' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [Damage] -> IO ())) => Op (ClearDamageExcept ()) Widget orig impl where\n runOp _ _ widget damages = withRef widget $ \\widgetPtr -> clearDamageWithBitmask' widgetPtr (fromIntegral (combine damages))\n{# fun Fl_Widget_clear_damage as clearDamage' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ClearDamage ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> clearDamage' widgetPtr\n{# fun Fl_Widget_damage_with_text as damageWithText' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [Damage] -> IO ())) => Op (SetDamage ()) Widget orig impl where\n runOp _ _ widget damages = withRef widget $ \\widgetPtr -> damageWithText' widgetPtr (fromIntegral (combine damages))\n{# fun Fl_Widget_damage_inside_widget as damageInsideWidget' { id `Ptr ()',`Word8',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( [Damage] -> Rectangle -> IO ())) => Op (SetDamageInside()) Widget orig impl where\n runOp _ _ widget damages rectangle = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n damageInsideWidget' widgetPtr (fromIntegral (combine damages)) x_pos y_pos w_pos h_pos\n{# fun Fl_Widget_measure_label as measureLabel' {id `Ptr ()',alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' #}\ninstance (impl ~ ( IO (Size))) => Op (MeasureLabel ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> measureLabel' widgetPtr >>= \\(width, height) -> return $ Size (Width width) (Height height)\n{# fun Fl_Widget_window as window' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Window)))) => Op (GetWindow ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> window' widgetPtr >>= toMaybeRef\n{# fun Fl_Widget_top_window as topWindow' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Window)))) => Op (GetTopWindow ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> (topWindow' widgetPtr) >>= toMaybeRef\n{# fun Fl_Widget_top_window_offset as topWindowOffset' { id `Ptr ()',alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv* } -> `()' #}\ninstance (impl ~ ( IO (Position))) => Op (GetTopWindowOffset ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> topWindowOffset' widgetPtr >>= \\(x_pos,y_pos) -> return $ Position (X x_pos) (Y y_pos)\n{# fun Fl_Widget_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Rectangle -> IO ())) => Op (ResizeSuper ()) Widget orig impl where\n runOp _ _ widget rectangle = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n resizeSuper' widgetPtr x_pos y_pos w_pos h_pos\n{# fun Fl_Widget_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Rectangle -> IO ())) => Op (Resize ()) Widget orig impl where\n runOp _ _ widget rectangle = withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n resize' widgetPtr x_pos y_pos w_pos h_pos\n{# fun Fl_Widget_set_callback as setCallback' { id `Ptr ()', id `FunPtr CallbackWithUserDataPrim'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ ((Ref orig -> IO ()) -> IO ())) => Op (SetCallback ()) Widget orig impl where\n runOp _ _ widget callback = withRef widget $ \\widgetPtr -> do\n ptr <- toCallbackPrimWithUserData callback\n setCallback' widgetPtr (castFunPtr ptr)\n\n{# fun Fl_Widget_has_callback as hasCallback' { id `Ptr ()' } -> `CInt' #}\ninstance (impl ~ (IO (Bool))) => Op (HasCallback ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> do\n res <- hasCallback' widgetPtr\n return $ if (res == 0) then False else True\n{# fun Fl_Widget_draw_box as widgetDrawBox' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_box_with_tc as widgetDrawBoxWithTC' { id `Ptr ()', cFromEnum `Boxtype', cFromColor`Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_box_with_txywhc as widgetDrawBoxWithTXywhC' { id `Ptr ()', cFromEnum `Boxtype', `Int',`Int',`Int',`Int', cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (DrawBox ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> widgetDrawBox' widgetPtr\ninstance (impl ~ ( Boxtype -> Color -> Maybe Rectangle -> IO ())) => Op (DrawBoxWithBoxtype ()) Widget orig impl where\n runOp _ _ widget bx c Nothing =\n withRef widget $ \\widgetPtr -> widgetDrawBoxWithTC' widgetPtr bx c\n runOp _ _ widget bx c (Just r) =\n withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n widgetDrawBoxWithTXywhC' widgetPtr bx x_pos y_pos w_pos h_pos c\n{# fun Fl_Widget_draw_backdrop as widgetDrawBackdrop' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (DrawBackdrop ()) Widget orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> widgetDrawBackdrop' widgetPtr\n\n{# fun Fl_Widget_draw_focus as widgetDrawFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Widget_draw_focus_with_txywh as widgetDrawFocusWithTXywh' { id `Ptr ()', cFromEnum `Boxtype', `Int', `Int', `Int', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Maybe (Boxtype, Rectangle) -> IO ())) => Op (DrawFocus ()) Widget orig impl where\n runOp _ _ widget Nothing =\n withRef widget $ \\ widgetPtr -> widgetDrawFocus' widgetPtr\n runOp _ _ widget (Just (bx, r)) =\n withRef widget $ \\widgetPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n widgetDrawFocusWithTXywh' widgetPtr bx x_pos y_pos w_pos h_pos\n\n-- $widgetfunctions\n-- @\n--\n-- activate :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- active :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- activeR :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- changed :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- clearActive :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearChanged :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearDamage :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearDamageWithBitmask :: 'Ref' 'Widget' -> 'Word8' -> 'IO' ()\n--\n-- clearOutput :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearVisible :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- clearVisibleFocus :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- contains:: ('Parent' a 'Widget') => 'Ref' 'Widget' -> 'Ref' a -> 'IO' 'Int'\n--\n-- copyLabel :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- copyTooltip :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- deactivate :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- doCallback :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- drawBackdrop :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- drawBox :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- drawBoxWithBoxtype :: 'Ref' 'Widget' -> 'Boxtype' -> 'Color' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- drawFocus :: 'Ref' 'Widget' -> 'Maybe' ('Boxtype', 'Rectangle') -> 'IO' ()\n--\n-- drawLabel :: 'Ref' 'Widget' -> 'Maybe' ('Rectangle,Alignments') -> 'IO' ()\n--\n-- getAlign :: 'Ref' 'Widget' -> 'IO' 'Alignments'\n--\n-- getBox :: 'Ref' 'Widget' -> 'IO' ('Boxtype')\n--\n-- getColor :: 'Ref' 'Widget' -> 'IO' ('Color')\n--\n-- getDamage :: 'Ref' 'Widget' -> 'IO' ('Word8')\n--\n-- getDamageInsideWidget :: 'Ref' 'Widget' -> 'Word8' -> 'Rectangle' -> 'IO' ()\n--\n-- getDamageWithText :: 'Ref' 'Widget' -> 'Word8' -> 'IO' ()\n--\n-- getDeimage :: 'Ref' 'Widget' -> 'IO' ('Ref' 'Image')\n--\n-- getH :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getImage :: 'Ref' 'Widget' -> 'IO' ('Ref' 'Image')\n--\n-- getLabel :: 'Ref' 'Widget' -> 'IO' 'T.Text'\n--\n-- getLabelcolor :: 'Ref' 'Widget' -> 'IO' ('Color')\n--\n-- getLabelfont :: 'Ref' 'Widget' -> 'IO' ('Font')\n--\n-- getLabelsize :: 'Ref' 'Widget' -> 'IO' ('FontSize')\n--\n-- getLabeltype :: 'Ref' 'Widget' -> 'IO' ('Labeltype')\n--\n-- getOutput :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getParent :: 'Ref' 'Widget' -> 'IO' ('Maybe' ('Ref' 'Group'))\n--\n-- getRectangle:: ('Match' obj ~ 'FindOp' orig orig ('GetX' ()), 'Match' obj ~ 'FindOp' orig orig ('GetY' ()), 'Match' obj ~ 'FindOp' orig orig ('GetW' ()), 'Match' obj ~ 'FindOp' orig orig ('GetH' ()), 'Op' ('GetX' ()) obj orig ('IO' 'Int',) 'Op' ('GetY' ()) obj orig ('IO' 'Int',) 'Op' ('GetW' ()) obj orig ('IO' 'Int',) 'Op' ('GetH' ()) obj orig ('IO' 'Int',)) => 'Ref' 'Widget' -> 'IO' 'Rectangle'\n--\n-- getSelectionColor :: 'Ref' 'Widget' -> 'IO' ('Color')\n--\n-- getTooltip :: 'Ref' 'Widget' -> 'IO' 'T.Text'\n--\n-- getTopWindow :: 'Ref' 'Widget' -> 'IO' ('Maybe' ('Ref' 'Window'))\n--\n-- getTopWindowOffset :: 'Ref' 'Widget' -> 'IO' ('Position')\n--\n-- getType_ :: 'Ref' 'Widget' -> 'IO' ('Word8')\n--\n-- getVisible :: 'Ref' 'Widget' -> 'IO' 'Bool'\n--\n-- getVisibleFocus :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- getVisibleR :: 'Ref' 'Widget' -> 'IO' 'Bool'\n--\n-- getW :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getWhen :: 'Ref' 'Widget' -> 'IO' ['When']\n--\n-- getWindow :: 'Ref' 'Widget' -> 'IO' ('Maybe' ('Ref' 'Window'))\n--\n-- getX :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- getY :: 'Ref' 'Widget' -> 'IO' ('Int')\n--\n-- handle :: 'Ref' 'Widget' -> ('Event' -> 'IO' ('Either' 'UnknownEvent' ()))\n--\n-- hasCallback :: 'Ref' 'Widget' -> 'IO' ('Bool')\n--\n-- hide :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- hideSuper :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- inside:: ('Parent' a 'Widget') => 'Ref' 'Widget' -> 'Ref' a -> 'IO' ('Int')\n--\n-- measureLabel :: 'Ref' 'Widget' -> 'IO' ('Size')\n--\n-- modifyVisibleFocus :: 'Ref' 'Widget' -> 'Int' -> 'IO' ()\n--\n-- redraw :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- redrawLabel :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- resize :: 'Ref' 'Widget' -> 'Rectangle' -> 'IO' ()\n--\n-- resizeSuper :: 'Ref' 'Widget' -> 'Rectangle' -> 'IO' ()\n--\n-- setActive :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setAlign :: 'Ref' 'Widget' -> 'Alignments' -> 'IO' ()\n--\n-- setBox :: 'Ref' 'Widget' -> 'Boxtype' -> 'IO' ()\n--\n-- setCallback :: 'Ref' 'Widget' -> ('Ref' orig -> 'IO' ()) -> 'IO' ()\n--\n-- setChanged :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setColor :: 'Ref' 'Widget' -> 'Color' -> 'IO' ()\n--\n-- setColorWithBgSel :: 'Ref' 'Widget' -> 'Color' -> 'Color' -> 'IO' ()\n--\n-- setDeimage:: ('Parent' a 'Image') => 'Ref' 'Widget' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setImage:: ('Parent' a 'Image') => 'Ref' 'Widget' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setLabel :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- setLabelcolor :: 'Ref' 'Widget' -> 'Color' -> 'IO' ()\n--\n-- setLabelfont :: 'Ref' 'Widget' -> 'Font' -> 'IO' ()\n--\n-- setLabelsize :: 'Ref' 'Widget' -> 'FontSize' -> 'IO' ()\n--\n-- setLabeltype :: 'Ref' 'Widget' -> 'Labeltype' -> 'IO' ()\n--\n-- setOutput :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setParent:: ('Parent' a 'Group') => 'Ref' 'Widget' -> 'Maybe' ('Ref' a) -> 'IO' ()\n--\n-- setSelectionColor :: 'Ref' 'Widget' -> 'Color' -> 'IO' ()\n--\n-- setTooltip :: 'Ref' 'Widget' -> 'T.Text' -> 'IO' ()\n--\n-- setType :: 'Ref' 'Widget' -> 'Word8' -> 'IO' ()\n--\n-- setVisible :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setVisibleFocus :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- setWhen :: 'Ref' 'Widget' -> ['When'] -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- showWidgetSuper :: 'Ref' 'Widget' -> 'IO' ()\n--\n-- takeFocus :: 'Ref' 'Widget' -> 'IO' ('Either' 'NoChange' ())\n--\n-- takesevents :: 'Ref' 'Widget' -> 'IO' ('Bool')\n-- @\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"c7d96a3fc252f2084e167456a8c2b0686bacabc4","subject":"getMaskBand and bandNodataPredicate","message":"getMaskBand and bandNodataPredicate\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , SomeDataset (..)\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , openAnyReadOnly\n , openAnyReadWrite\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 , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , bandNodataPredicate\n , setBandNodataValue\n , getBand\n , getMaskBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Data.Coerce (coerce)\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 (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown 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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: GDALType a => FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p >>= checkType\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\nopenAnyWithMode :: forall s t. Access -> String -> GDAL s (SomeDataset s t)\nopenAnyWithMode m p = do\n ds <- openWithMode m p\n dt <- getBand ds 1 >>= bandDatatype\n case dt of\n GDT_Byte -> return $ SomeDataset ((coerce ds) :: Dataset s t Word8)\n GDT_UInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word16)\n GDT_UInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word32)\n GDT_Int16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int16)\n GDT_Int32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int32)\n GDT_Float32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Float)\n GDT_Float64 -> return $ SomeDataset ((coerce ds) :: Dataset s t Double)\n GDT_CInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int16))\n GDT_CInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int32))\n GDT_CFloat32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Float))\n GDT_CFloat64 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Double))\n _ -> liftIO (throw InvalidType)\n\ncheckType\n :: forall s t a. GDALType a\n => Dataset s t a -> GDAL s (Dataset s t a)\ncheckType ds = do\n c <- datasetBandCount ds\n if c > 0\n then do\n b <- getBand ds 1\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ds\n else liftIO (throw InvalidType)\n else return ds\n\ndata SomeDataset s (t :: DatasetMode)\n = forall a. GDALType a => SomeDataset (Dataset s t a)\n\nopenAnyReadOnly :: forall s. FilePath -> GDAL s (SomeDataset s ReadOnly)\nopenAnyReadOnly = openAnyWithMode GA_ReadOnly\n\nopenAnyReadWrite :: forall s. FilePath -> GDAL s (SomeDataset s ReadWrite)\nopenAnyReadWrite = openAnyWithMode GA_Update\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nbandNodataPredicate :: GDALType a => (Band s t a) -> GDAL s (a -> Bool)\nbandNodataPredicate b = liftIO $ alloca $ \\p -> do\n nd <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then (==nd) . toNodata else const False)\n{-# INLINE bandNodataPredicate #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector a)\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s a. GDALType a\n => (ROBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector a)\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBandIO band xoff yoff sx sy bx by = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy 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 0\n 0\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by vec = liftIO $ do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector a)\nreadBandBlock b x y = do\n len <- bandBlockLen b\n liftIO $ do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f len\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector a -> GDAL s ()\nwriteBandBlock b x y vec = do\n nElems <- bandBlockLen b\n liftIO $ do\n let (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\ngetMaskBand :: Band s t a -> GDAL s (Band s t Word8)\ngetMaskBand = liftIO . c_getMaskBand\n\n\nclass Storable a => GDALType a where\n datatype :: Proxy a -> Datatype\n toNodata :: a -> CDouble\n fromNodata :: CDouble -> a\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE datatype #-}\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , SomeDataset (..)\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , openAnyReadOnly\n , openAnyReadWrite\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 , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..))\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Data.Coerce (coerce)\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 (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown 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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: GDALType a => FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p >>= checkType\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\nopenAnyWithMode :: forall s t. Access -> String -> GDAL s (SomeDataset s t)\nopenAnyWithMode m p = do\n ds <- openWithMode m p\n dt <- getBand ds 1 >>= bandDatatype\n case dt of\n GDT_Byte -> return $ SomeDataset ((coerce ds) :: Dataset s t Word8)\n GDT_UInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word16)\n GDT_UInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word32)\n GDT_Int16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int16)\n GDT_Int32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int32)\n GDT_Float32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Float)\n GDT_Float64 -> return $ SomeDataset ((coerce ds) :: Dataset s t Double)\n GDT_CInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int16))\n GDT_CInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int32))\n GDT_CFloat32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Float))\n GDT_CFloat64 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Double))\n _ -> liftIO (throw InvalidType)\n\ncheckType\n :: forall s t a. GDALType a\n => Dataset s t a -> GDAL s (Dataset s t a)\ncheckType ds = do\n c <- datasetBandCount ds\n if c > 0\n then do\n b <- getBand ds 1\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ds\n else liftIO (throw InvalidType)\n else return ds\n\ndata SomeDataset s (t :: DatasetMode)\n = forall a. GDALType a => SomeDataset (Dataset s t a)\n\nopenAnyReadOnly :: forall s. FilePath -> GDAL s (SomeDataset s ReadOnly)\nopenAnyReadOnly = openAnyWithMode GA_ReadOnly\n\nopenAnyReadWrite :: forall s. FilePath -> GDAL s (SomeDataset s ReadWrite)\nopenAnyReadWrite = openAnyWithMode GA_Update\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: (Band s t a) -> GDAL s (Maybe Double)\nbandNodataValue b = liftIO $ 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 s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s a) -> Double -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector a)\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s a. GDALType a\n => (ROBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector a)\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBandIO band xoff yoff sx sy bx by = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy 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 0\n 0\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by vec = liftIO $ do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector a)\nreadBandBlock b x y = do\n len <- bandBlockLen b\n liftIO $ do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f len\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector a -> GDAL s ()\nwriteBandBlock b x y vec = do\n nElems <- bandBlockLen b\n liftIO $ do\n let (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\nclass Storable a => GDALType a where\n datatype :: Proxy a -> Datatype\n\ninstance GDALType Word8 where datatype _ = GDT_Byte\ninstance GDALType Word16 where datatype _ = GDT_UInt16\ninstance GDALType Word32 where datatype _ = GDT_UInt32\ninstance GDALType Int16 where datatype _ = GDT_Int16\ninstance GDALType Int32 where datatype _ = GDT_Int32\ninstance GDALType Float where datatype _ = GDT_Float32\ninstance GDALType Double where datatype _ = GDT_Float64\ninstance GDALType (Complex Int16) where datatype _ = GDT_CInt16\ninstance GDALType (Complex Int32) where datatype _ = GDT_CInt32\ninstance GDALType (Complex Float) where datatype _ = GDT_CFloat32\ninstance GDALType (Complex Double) where datatype _ = GDT_CFloat64\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5fd2f97771f9ddc69159223b670f31c8c4a85ee9","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\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/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":"09e3af8a10ebc4c6f9e7854906e530a84546e02a","subject":"gstreamer: document & implement missing API for M.S.G.Core.ElementFactory","message":"gstreamer: document & implement missing API for M.S.G.Core.ElementFactory\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\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","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.ElementFactory (\n \n ElementFactory,\n ElementFactoryClass,\n castToElementFactory,\n toElementFactory,\n \n elementFactoryFind,\n elementFactoryGetElementType,\n elementFactoryGetLongname,\n elementFactoryGetKlass,\n elementFactoryGetDescription,\n elementFactoryGetAuthor,\n elementFactoryGetNumPadTemplates,\n elementFactoryGetURIType,\n elementFactoryGetURIProtocols,\n elementFactoryCreate,\n elementFactoryMake\n \n ) where\n\nimport Control.Monad ( liftM )\nimport System.Glib.FFI\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString\n , peekUTFStringArray0 )\nimport System.Glib.GType ( GType )\n{# import Media.Streaming.GStreamer.Core.Types #}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementFactoryFind :: String\n -> IO ElementFactory\nelementFactoryFind name =\n withUTFString name {# call element_factory_find #} >>= takeObject\n\nelementFactoryGetElementType :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO (Maybe GType)\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\nelementFactoryGetLongname :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetLongname factory =\n {# call element_factory_get_longname #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetKlass :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetKlass factory =\n {# call element_factory_get_klass #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetDescription :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetDescription factory =\n {# call element_factory_get_description #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetAuthor :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetAuthor factory =\n {# call element_factory_get_author #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetNumPadTemplates :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO Word\nelementFactoryGetNumPadTemplates factory =\n liftM fromIntegral $\n {# call element_factory_get_num_pad_templates #} $ toElementFactory factory\n\nelementFactoryGetURIType :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO Word\nelementFactoryGetURIType factory =\n liftM fromIntegral $\n {# call element_factory_get_uri_type #} $ toElementFactory factory\n\nelementFactoryGetURIProtocols :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO (Maybe [String])\nelementFactoryGetURIProtocols factory =\n {# call element_factory_get_uri_protocols #} (toElementFactory factory) >>=\n maybePeek peekUTFStringArray0\n\nelementFactoryCreate :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> String\n -> IO (Maybe Element)\nelementFactoryCreate factory name =\n withUTFString name $ \\cName ->\n {# call element_factory_create #} (toElementFactory factory) cName >>=\n maybePeek takeObject\n\nelementFactoryMake :: String\n -> String\n -> IO (Maybe Element)\nelementFactoryMake factoryName name =\n withUTFString factoryName $ \\cFactoryName ->\n withUTFString name $ \\cName ->\n {# call element_factory_make #} cFactoryName cName >>=\n maybePeek takeObject\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d5a89c01752e90786a83ab0234fc7507c6d2bee3","subject":"Added bindings for cvCountNonZero to ImageMath","message":"Added bindings for cvCountNonZero to ImageMath\n","repos":"aleator\/CV,aleator\/CV,TomMD\/CV,BeautifulDestinations\/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, countNonZero\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--\u00a0| Calculate number of nonzero pixels\ncountNonZero :: Image GrayScale a -> Int\ncountNonZero img = unsafePerformIO $\u00a0withGenImage img $ \\cImg -> fromIntegral <$> {#call cvCountNonZero#} cImg \n\n\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 -- * 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5429245bf7530749461a6da77e861ae073f1b76c","subject":"Change for poppler-glib-0.16","message":"Change for poppler-glib-0.16\n","repos":"wavewave\/poppler,gtk2hs\/poppler","old_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page = \n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\npageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point \n -> Int -- ^ @rotation@ rotate the document by the specified degree \n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into \n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page \n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr -> \n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n \n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page \npageGetIndex page =\n liftM fromIntegral $ \n {#call poppler_page_get_index #} (toPage page)\n \n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page = \n alloca $ \\ widthPtr -> \n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success \n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n \n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile = \n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded) \n -> IO [PopplerRectangle]\npageFindText page text = \n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n \n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page = \n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n \n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1. \npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'. \npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'. \npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'. \npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'. \npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection = \n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #} \n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n-- \n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> PopplerRectangle -- ^ @oldSelection@ previous selection \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs \n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background \n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $ \n with selection $ \\ selectionPtr -> \n with oldSelection $ \\ oldSelectionPtr -> \n with glyphColor $ \\ glyphColorPtr -> \n with backgroundColor $ \\ backgroundColorPtr -> \n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n \n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n-- \n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelectionToPixbuf :: PageClass page => page \n -> Double -- ^ @scale@ scale specified as pixels per point \n -> Int -- ^ @rotation@ rotate the document by the specified degree \n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> PopplerRectangle -- ^ @oldSelection@ previous selection \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> Color -- ^ @glyphColor@ color to use for drawing glyphs \n -> Color -- ^ @backgroundColor@ color to use for the selection background \n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor = \n with selection $ \\ selectionPtr -> \n with oldSelection $ \\ oldSelectionPtr -> \n with glyphColor $ \\ glyphColorPtr -> \n with backgroundColor $ \\ backgroundColorPtr -> \n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page = \n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\npageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point \n -> Int -- ^ @rotation@ rotate the document by the specified degree \n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into \n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page \n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr -> \n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n \n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page \npageGetIndex page =\n liftM fromIntegral $ \n {#call poppler_page_get_index #} (toPage page)\n \n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page = \n alloca $ \\ widthPtr -> \n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success \n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n \n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile = \n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded) \n -> IO [PopplerRectangle]\npageFindText page text = \n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n \n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> SelectionStyle -> PopplerRectangle\n -> IO String -- ^ returns selection string\npageGetText page style rect = \n with rect $ \\ rectPtr ->\n {#call poppler_page_get_text #} (toPage page) ((fromIntegral . fromEnum) style) (castPtr rectPtr)\n >>= peekUTFString\n \n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1. \npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'. \npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'. \npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'. \npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'. \npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection = \n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #} \n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n-- \n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> PopplerRectangle -- ^ @oldSelection@ previous selection \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs \n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background \n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $ \n with selection $ \\ selectionPtr -> \n with oldSelection $ \\ oldSelectionPtr -> \n with glyphColor $ \\ glyphColorPtr -> \n with backgroundColor $ \\ backgroundColorPtr -> \n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n \n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n-- \n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelectionToPixbuf :: PageClass page => page \n -> Double -- ^ @scale@ scale specified as pixels per point \n -> Int -- ^ @rotation@ rotate the document by the specified degree \n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> PopplerRectangle -- ^ @oldSelection@ previous selection \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> Color -- ^ @glyphColor@ color to use for drawing glyphs \n -> Color -- ^ @backgroundColor@ color to use for the selection background \n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor = \n with selection $ \\ selectionPtr -> \n with oldSelection $ \\ oldSelectionPtr -> \n with glyphColor $ \\ glyphColorPtr -> \n with backgroundColor $ \\ backgroundColorPtr -> \n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d49e76764100665c2e0690277ea61b5161e4da68","subject":"Fix the get side of all container child attributes. It was accidentally calling 'set' rather than 'get'. doh! :-)","message":"Fix the get side of all container child attributes.\nIt was accidentally calling 'set' rather than 'get'. doh! :-)\n\n","repos":"gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","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":"cdd4a0a74791e68550cb3697c3ff8a80aa9a26a5","subject":"Compile on platforms where int64_t == long long. (#6)","message":"Compile on platforms where int64_t == long long. (#6)\n\nIn particular, this helps fix the build on Mac OS X.","repos":"judah\/tensorflow-haskell,cem3394\/haskell,jcberentsen\/haskell,tensorflow\/haskell","old_file":"tensorflow\/src\/TensorFlow\/Internal\/Raw.chs","new_file":"tensorflow\/src\/TensorFlow\/Internal\/Raw.chs","new_contents":"-- Copyright 2016 TensorFlow authors.\n--\n-- Licensed under the Apache License, Version 2.0 (the \"License\");\n-- you may not use this file except in compliance with the License.\n-- You may obtain a copy of the License at\n--\n-- http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n--\n-- Unless required by applicable law or agreed to in writing, software\n-- distributed under the License is distributed on an \"AS IS\" BASIS,\n-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-- See the License for the specific language governing permissions and\n-- limitations under the License.\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule TensorFlow.Internal.Raw where\n\n#include \"third_party\/tensorflow\/c\/c_api.h\"\n\nimport Foreign\nimport Foreign.C\n\n{#enum TF_DataType as DataType {} deriving (Show, Eq) #}\n{#enum TF_Code as Code {} deriving (Show, Eq) #}\n\n\n-- Status.\n{#pointer *TF_Status as Status newtype #}\n\nnewStatus :: IO Status\nnewStatus = {# call TF_NewStatus as ^ #}\n\ndeleteStatus :: Status -> IO ()\ndeleteStatus = {# call TF_DeleteStatus as ^ #}\n\nsetStatus :: Status -> Code -> CString -> IO ()\nsetStatus s c = {# call TF_SetStatus as ^ #} s (fromIntegral $ fromEnum c)\n\ngetCode :: Status -> IO Code\ngetCode s = toEnum . fromIntegral <$> {# call TF_GetCode as ^ #} s\n\nmessage :: Status -> IO CString\nmessage = {# call TF_Message as ^ #}\n\n\n-- Buffer.\ndata Buffer\n{#pointer *TF_Buffer as BufferPtr -> Buffer #}\n\ngetBufferData :: BufferPtr -> IO (Ptr ())\ngetBufferData = {#get TF_Buffer->data #}\n\ngetBufferLength :: BufferPtr -> IO CULong\ngetBufferLength ={#get TF_Buffer->length #}\n\n-- Tensor.\n{#pointer *TF_Tensor as Tensor newtype #}\n\ninstance Storable Tensor where\n sizeOf (Tensor t) = sizeOf t\n alignment (Tensor t) = alignment t\n peek p = fmap Tensor (peek (castPtr p))\n poke p (Tensor t) = poke (castPtr p) t\n\n-- A synonym for the int64_t type, which is used in the TensorFlow API.\n-- On some platforms it's `long`; on others (e.g., Mac OS X) it's `long long`;\n-- and as far as Haskell is concerned, those are distinct types (`CLong` vs\n-- `CLLong`).\ntype CInt64 = {#type int64_t #}\n\nnewTensor :: DataType\n -> Ptr CInt64 -- dimensions array\n -> CInt -- num dimensions\n -> Ptr () -- data\n -> CULong -- data len\n -> FunPtr (Ptr () -> CULong -> Ptr () -> IO ()) -- deallocator\n -> Ptr () -- deallocator arg\n -> IO Tensor\nnewTensor dt = {# call TF_NewTensor as ^ #} (fromIntegral $ fromEnum dt)\n\ndeleteTensor :: Tensor -> IO ()\ndeleteTensor = {# call TF_DeleteTensor as ^ #}\n\ntensorType :: Tensor -> IO DataType\ntensorType t = toEnum . fromIntegral <$> {# call TF_TensorType as ^ #} t\n\nnumDims :: Tensor -> IO CInt\nnumDims = {# call TF_NumDims as ^ #}\n\ndim :: Tensor -> CInt -> IO CInt64\ndim = {# call TF_Dim as ^ #}\n\ntensorByteSize :: Tensor -> IO CULong\ntensorByteSize = {# call TF_TensorByteSize as ^ #}\n\ntensorData :: Tensor -> IO (Ptr ())\ntensorData = {# call TF_TensorData as ^ #}\n\n\n-- Session Options.\n{# pointer *TF_SessionOptions as SessionOptions newtype #}\n\nnewSessionOptions :: IO SessionOptions\nnewSessionOptions = {# call TF_NewSessionOptions as ^ #}\n\nsetTarget :: SessionOptions -> CString -> IO ()\nsetTarget = {# call TF_SetTarget as ^ #}\n\nsetConfig :: SessionOptions -> Ptr () -> CULong -> Status -> IO ()\nsetConfig = {# call TF_SetConfig as ^ #}\n\ndeleteSessionOptions :: SessionOptions -> IO ()\ndeleteSessionOptions = {# call TF_DeleteSessionOptions as ^ #}\n\n\n-- Session.\n{# pointer *TF_Session as Session newtype #}\n\nnewSession :: SessionOptions -> Status -> IO Session\nnewSession = {# call TF_NewSession as ^ #}\n\ncloseSession :: Session -> Status -> IO ()\ncloseSession = {# call TF_CloseSession as ^ #}\n\ndeleteSession :: Session -> Status -> IO ()\ndeleteSession = {# call TF_DeleteSession as ^ #}\n\nextendGraph :: Session -> Ptr () -> CULong -> Status -> IO ()\nextendGraph = {# call TF_ExtendGraph as ^ #}\n\nrun :: Session\n -> BufferPtr -- RunOptions proto.\n -> Ptr CString -> Ptr Tensor -> CInt -- Input (names, tensors, count).\n -> Ptr CString -> Ptr Tensor -> CInt -- Output (names, tensors, count).\n -> Ptr CString -> CInt -- Target nodes (names, count).\n -> BufferPtr -- RunMetadata proto.\n -> Status\n -> IO ()\nrun = {# call TF_Run as ^ #}\n\n-- FFI helpers.\ntype TensorDeallocFn = Ptr () -> CULong -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n wrapTensorDealloc :: TensorDeallocFn -> IO (FunPtr TensorDeallocFn)\n\n\n-- | Get the OpList of all OpDefs defined in this address space.\n-- Returns a BufferPtr, ownership of which is transferred to the caller\n-- (and can be freed using deleteBuffer).\n--\n-- The data in the buffer will be the serialized OpList proto for ops registered\n-- in this address space.\ngetAllOpList :: IO BufferPtr\ngetAllOpList = {# call TF_GetAllOpList as ^ #}\n\nforeign import ccall \"&TF_DeleteBuffer\"\n deleteBuffer :: FunPtr (BufferPtr -> IO ())\n","old_contents":"-- Copyright 2016 TensorFlow authors.\n--\n-- Licensed under the Apache License, Version 2.0 (the \"License\");\n-- you may not use this file except in compliance with the License.\n-- You may obtain a copy of the License at\n--\n-- http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n--\n-- Unless required by applicable law or agreed to in writing, software\n-- distributed under the License is distributed on an \"AS IS\" BASIS,\n-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-- See the License for the specific language governing permissions and\n-- limitations under the License.\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule TensorFlow.Internal.Raw where\n\n#include \"third_party\/tensorflow\/c\/c_api.h\"\n\nimport Foreign\nimport Foreign.C\n\n{#enum TF_DataType as DataType {} deriving (Show, Eq) #}\n{#enum TF_Code as Code {} deriving (Show, Eq) #}\n\n\n-- Status.\n{#pointer *TF_Status as Status newtype #}\n\nnewStatus :: IO Status\nnewStatus = {# call TF_NewStatus as ^ #}\n\ndeleteStatus :: Status -> IO ()\ndeleteStatus = {# call TF_DeleteStatus as ^ #}\n\nsetStatus :: Status -> Code -> CString -> IO ()\nsetStatus s c = {# call TF_SetStatus as ^ #} s (fromIntegral $ fromEnum c)\n\ngetCode :: Status -> IO Code\ngetCode s = toEnum . fromIntegral <$> {# call TF_GetCode as ^ #} s\n\nmessage :: Status -> IO CString\nmessage = {# call TF_Message as ^ #}\n\n\n-- Buffer.\ndata Buffer\n{#pointer *TF_Buffer as BufferPtr -> Buffer #}\n\ngetBufferData :: BufferPtr -> IO (Ptr ())\ngetBufferData = {#get TF_Buffer->data #}\n\ngetBufferLength :: BufferPtr -> IO CULong\ngetBufferLength ={#get TF_Buffer->length #}\n\n-- Tensor.\n{#pointer *TF_Tensor as Tensor newtype #}\n\ninstance Storable Tensor where\n sizeOf (Tensor t) = sizeOf t\n alignment (Tensor t) = alignment t\n peek p = fmap Tensor (peek (castPtr p))\n poke p (Tensor t) = poke (castPtr p) t\n\nnewTensor :: DataType\n -> Ptr CLong -- dimensions array\n -> CInt -- num dimensions\n -> Ptr () -- data\n -> CULong -- data len\n -> FunPtr (Ptr () -> CULong -> Ptr () -> IO ()) -- deallocator\n -> Ptr () -- deallocator arg\n -> IO Tensor\nnewTensor dt = {# call TF_NewTensor as ^ #} (fromIntegral $ fromEnum dt)\n\ndeleteTensor :: Tensor -> IO ()\ndeleteTensor = {# call TF_DeleteTensor as ^ #}\n\ntensorType :: Tensor -> IO DataType\ntensorType t = toEnum . fromIntegral <$> {# call TF_TensorType as ^ #} t\n\nnumDims :: Tensor -> IO CInt\nnumDims = {# call TF_NumDims as ^ #}\n\ndim :: Tensor -> CInt -> IO CLong\ndim = {# call TF_Dim as ^ #}\n\ntensorByteSize :: Tensor -> IO CULong\ntensorByteSize = {# call TF_TensorByteSize as ^ #}\n\ntensorData :: Tensor -> IO (Ptr ())\ntensorData = {# call TF_TensorData as ^ #}\n\n\n-- Session Options.\n{# pointer *TF_SessionOptions as SessionOptions newtype #}\n\nnewSessionOptions :: IO SessionOptions\nnewSessionOptions = {# call TF_NewSessionOptions as ^ #}\n\nsetTarget :: SessionOptions -> CString -> IO ()\nsetTarget = {# call TF_SetTarget as ^ #}\n\nsetConfig :: SessionOptions -> Ptr () -> CULong -> Status -> IO ()\nsetConfig = {# call TF_SetConfig as ^ #}\n\ndeleteSessionOptions :: SessionOptions -> IO ()\ndeleteSessionOptions = {# call TF_DeleteSessionOptions as ^ #}\n\n\n-- Session.\n{# pointer *TF_Session as Session newtype #}\n\nnewSession :: SessionOptions -> Status -> IO Session\nnewSession = {# call TF_NewSession as ^ #}\n\ncloseSession :: Session -> Status -> IO ()\ncloseSession = {# call TF_CloseSession as ^ #}\n\ndeleteSession :: Session -> Status -> IO ()\ndeleteSession = {# call TF_DeleteSession as ^ #}\n\nextendGraph :: Session -> Ptr () -> CULong -> Status -> IO ()\nextendGraph = {# call TF_ExtendGraph as ^ #}\n\nrun :: Session\n -> BufferPtr -- RunOptions proto.\n -> Ptr CString -> Ptr Tensor -> CInt -- Input (names, tensors, count).\n -> Ptr CString -> Ptr Tensor -> CInt -- Output (names, tensors, count).\n -> Ptr CString -> CInt -- Target nodes (names, count).\n -> BufferPtr -- RunMetadata proto.\n -> Status\n -> IO ()\nrun = {# call TF_Run as ^ #}\n\n-- FFI helpers.\ntype TensorDeallocFn = Ptr () -> CULong -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n wrapTensorDealloc :: TensorDeallocFn -> IO (FunPtr TensorDeallocFn)\n\n\n-- | Get the OpList of all OpDefs defined in this address space.\n-- Returns a BufferPtr, ownership of which is transferred to the caller\n-- (and can be freed using deleteBuffer).\n--\n-- The data in the buffer will be the serialized OpList proto for ops registered\n-- in this address space.\ngetAllOpList :: IO BufferPtr\ngetAllOpList = {# call TF_GetAllOpList as ^ #}\n\nforeign import ccall \"&TF_DeleteBuffer\"\n deleteBuffer :: FunPtr (BufferPtr -> IO ())\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"56051a444c9877c1dfcbad6be1e037c9b55159a9","subject":"Add the forgotten Nothing case to readFile.","message":"Add the forgotten Nothing case to readFile.\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer","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\nfileRead file Nothing = constructNewGObject mkFileInputStream $\n propagateGError $ {# call file_read #} (toFile file) (Cancellable nullForeignPtr)\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\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"17cdc7305d9dfe8353aeb1867bf261077b019fd4","subject":"Make names more palatable.","message":"Make names more palatable.\n","repos":"joelburget\/assimp,haraldsteinlechner\/assimp,haraldsteinlechner\/assimp,joelburget\/assimp","old_file":"Graphics\/Formats\/Assimp\/Types.chs","new_file":"Graphics\/Formats\/Assimp\/Types.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls #-}\nmodule Graphics.Formats.Assimp.Types (\n SceneFlags(..)\n , PostProcessSteps(..)\n , Return(..)\n , Origin(..)\n , DefaultLogStream(..)\n , PrimitiveType(..)\n , LightSourceType(..)\n , TextureOp(..)\n , TextureMapMode(..)\n , TextureMapping(..)\n , TextureType(..)\n , ShadingMode(..)\n , TextureFlags(..)\n , BlendMode(..)\n , PropertyTypeInfo(..)\n , Plane(..)\n , Ray(..)\n , Color3D(..)\n , Color4D(..)\n , MemoryInfo(..)\n , Quaternion(..)\n , Vector2D(..)\n , Vector3D(..)\n , AiString(..)\n , Matrix3x3(..)\n , Matrix4x4(..)\n , Node(..)\n , Face(..)\n , VertexWeight(..)\n , Bone(..)\n , Mesh(..)\n , MaterialProperty(..)\n , Material(..)\n , NodeAnim(..)\n , MeshAnim(..)\n , Animation(..)\n , Light(..)\n , Camera(..)\n , Scene(..)\n , Texture(..)\n , Texel(..)\n , (.|.)\n ) where\n\nimport C2HS\nimport Data.Vector hiding ((++))\nimport Data.Bits ((.|.))\n\n#include \"..\/..\/assimp\/include\/assimp.h\" \/\/ Plain-C interface\n#include \"..\/..\/assimp\/include\/aiScene.h\" \/\/ Output data structure\n#include \"..\/..\/assimp\/include\/aiPostProcess.h\" \/\/ Post processing flags\n#include \"typedefs.h\"\n\n{#context lib=\"assimp\"#}\n{#context prefix=\"ai\"#}\n\n{#enum define SceneFlags {AI_SCENE_FLAGS_INCOMPLETE as FlagsIncomplete\n , AI_SCENE_FLAGS_VALIDATED as FlagsValidated\n , AI_SCENE_FLAGS_VALIDATION_WARNING as FlagsValidationWarning\n , AI_SCENE_FLAGS_NON_VERBOSE_FORMAT as FlagsNonVerboseFormat\n , AI_SCENE_FLAGS_TERRAIN as FlagsTerrain\n }#}\ninstance Show SceneFlags where\n show FlagsIncomplete = \"FlagsIncomplete\"\n show FlagsValidated = \"FlagsValidated\"\n show FlagsValidationWarning = \"FlagsValidationWarning\"\n show FlagsNonVerboseFormat = \"FlagsNonVerboseFormat\"\n show FlagsTerrain = \"FlagsTerrain\"\n\n{#enum aiPostProcessSteps as PostProcessSteps {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiReturn as Return {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiOrigin as Origin {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiDefaultLogStream as DefaultLogStream {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiPrimitiveType as PrimitiveType {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiLightSourceType as LightSourceType {underscoreToCase} deriving (Show, Eq)#}\n\n-- Texture enums\n{#enum aiTextureOp as TextureOp {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureMapMode as TextureMapMode {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureMapping as TextureMapping {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureType as TextureType {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiShadingMode as ShadingMode {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureFlags as TextureFlags {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiBlendMode as BlendMode {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiPropertyTypeInfo as PropertyTypeInfo {underscoreToCase} deriving (Show, Eq)#}\n\ndata Plane = Plane {\n planeA :: Float\n , planeB :: Float\n , planeC :: Float\n , planeD :: Float\n } deriving (Show)\n{#pointer *aiPlane as PlanePtr -> Plane#}\n\ndata Ray = Ray {\n rayPos :: Vector3D\n , rayDir :: Vector3D\n } deriving (Show)\n{#pointer *aiRay as RayPtr -> Ray#}\n\ndata Color3D = Color3D {\n color3dR :: Float\n , color3dG :: Float\n , color3dB :: Float\n } deriving (Show)\n{#pointer *aiColor3D as Color3DPtr -> Color3D#}\n\ndata Color4D = Color4D {\n color4dR :: Float\n , color4dG :: Float\n , color4dB :: Float\n , color4dA :: Float\n } deriving (Show)\n{#pointer *aiColor4D as Color4DPtr -> Color4D#}\n\ndata MemoryInfo = MemoryInfo {\n textures :: CUInt\n , materials :: CUInt\n , meshes :: CUInt\n , nodes :: CUInt\n , animations :: CUInt\n , cameras :: CUInt\n , lights :: CUInt\n , total :: CUInt\n } deriving (Show)\n{#pointer *aiMemoryInfo as MemoryInfoPtr -> MemoryInfo#}\n\ndata LogStream\n{#pointer *aiLogStream as LogStreamPtr -> LogStream#}\n\ndata Quaternion = Quaternion {\n quaternionW :: Float\n , quaternionX :: Float\n , quaternionY :: Float\n , quaternionZ :: Float\n } deriving (Show)\n{#pointer *aiQuaternion as QuaternionPtr -> Quaternion#}\n\ndata Vector2D = Vector2D {\n vector2dX :: Float\n , vector2dY :: Float\n } deriving (Show)\n{#pointer *aiVector2D as Vector2DPtr -> Vector2D#}\n\ndata Vector3D = Vector3D {\n vector3dX :: Float\n , vector3dY :: Float\n , vector3dZ :: Float\n } deriving (Show)\n{#pointer *aiVector3D as Vector3DPtr -> Vector3D#}\n\nnewtype AiString = AiString String deriving (Show)\n{#pointer *aiString as StringPtr -> AiString#}\n\ndata Matrix3x3 = Matrix3x3 {\n matrix3x3 :: Vector (Vector Float)\n } deriving (Show)\n{#pointer *aiMatrix3x3 as Matrix3x3Ptr -> Matrix3x3#}\n\ndata Matrix4x4 = Matrix4x4 {\n matrix4x4 :: Vector (Vector Float)\n } deriving (Show)\n{#pointer *aiMatrix4x4 as Matrix4x4Ptr -> Matrix4x4#}\n\n{- From the Assimp source:\n -\n - Nodes are little named entities in the scene that have a place and\n - orientation relative to their parents. Starting from the scene's root node\n - all nodes can have 0 to x child nodes, thus forming a hierarchy. They form\n - the base on which the scene is built on: a node can refer to 0..x meshes,\n - can be referred to by a bone of a mesh or can be animated by a key sequence\n - of an animation. DirectX calls them \"frames\", others call them \"objects\", we\n - call them aiNode.\n -\n - A node can potentially refer to single or multiple meshes. The meshes are\n - not stored inside the node, but instead in an array of aiMesh inside the\n - aiScene. A node only refers to them by their array index. This also means\n - that multiple nodes can refer to the same mesh, which provides a simple form\n - of instancing. A mesh referred to by this way lives in the node's local\n - coordinate system. If you want the mesh's orientation in global space, you'd\n - have to concatenate the transformations from the referring node and all of\n - its parents.\n-}\ndata Node = Node\n { nodeMName :: String\n , mTransformation :: Matrix4x4\n , mParent :: Maybe Node\n , mChildren :: [Node]\n , nodeMMeshes :: [CUInt] -- Holds indices defining the node\n } deriving (Show)\n{#pointer *aiNode as NodePtr -> Node#}\n\ndata Face = Face\n {\n mIndices :: [CUInt] -- Holds indices defining the face\n } deriving (Show)\n{#pointer *aiFace as FacePtr -> Face#}\n\ndata VertexWeight = VertexWeight\n { mVertexId :: CUInt\n , mWeight :: CFloat\n } deriving (Show)\n{#pointer *aiVertexWeight as VertexWeightPtr -> VertexWeight#}\n\ndata Bone = Bone\n { boneMName :: String\n , mWeights :: [VertexWeight]\n , mOffpokeMatrix :: Matrix4x4\n } deriving (Show)\n{#pointer *aiBone as BonePtr -> Bone#}\n\ndata Mesh = Mesh\n { mPrimitiveTypes :: [PrimitiveType]\n , mVertices :: [Vector3D]\n , mNormals :: [Vector3D]\n , mTangents :: [Vector3D]\n , mBitangents :: [Vector3D]\n , mColors :: [Color4D]\n , mTextureCoords :: [Vector3D]\n , mNumUVComponents :: CUInt\n , mFaces :: [Face]\n , mBones :: [Bone]\n , mMaterialIndex :: CUInt\n , meshMName :: String\n } deriving (Show)\n{#pointer *aiMesh as MeshPtr -> Mesh#}\n\ndata MaterialProperty = MaterialProperty {\n mKey :: String\n , mSemantic :: TextureType\n , mIndex :: CUInt\n , mData :: String\n } deriving (Show)\n{#pointer *aiMaterialProperty as MaterialPropertyPtr -> MaterialProperty#}\n\ndata Material = Material {\n mProperties :: [MaterialProperty]\n } deriving (Show)\n{#pointer *aiMaterial as MaterialPtr -> Material#}\n\ndata NodeAnim = NodeAnim {\n dummy'NodeAnim :: Int\n } deriving (Show)\n\ndata MeshAnim = MeshAnim {\n dummy'MeshAnim :: Int\n } deriving (Show)\n\ndata Animation = Animation {\n animationMName :: String\n , mDuration :: Double\n , mTicksPerSecond :: Double\n , mChannels :: [NodeAnim]\n , mMeshChannels :: [MeshAnim]\n } deriving (Show)\n{#pointer *aiAnimation as AnimationPtr -> Animation#}\n\ndata Texel = Texel {\n dummy'Texel :: Int\n } deriving (Show)\n\ndata Texture = Texture {\n mWidth :: CUInt\n , mHeight :: CUInt\n , achFormatHint :: String\n , pcData :: [Texel]\n } deriving (Show)\n{#pointer *aiTexture as TexturePtr -> Texture#}\n\ndata UVTransform = UVTransform {\n mTranslation :: Vector2D\n , mScaling :: Vector2D\n , mRotation :: Float\n } deriving (Show)\n\ndata Light = Light {\n lightMName :: String\n , mType :: LightSourceType\n , lightMPosition :: Vector3D\n , mDirection :: Vector3D\n , mAttenuationConstant :: Float\n , mAttenuationLinear :: Float\n , mAttenuationQuadratic :: Float\n , mColorDiffuse :: Color3D\n , mColorSpecular :: Color3D\n , mColorAmbient :: Color3D\n , mAngleInnerCone :: Float\n , mAngleOuterCone :: Float\n } deriving (Show)\n{#pointer *aiLight as LightPtr -> Light#}\n\ndata Camera = Camera {\n cameraMName :: String\n , mPosition :: Vector3D\n , mUp :: Vector3D\n , mLookAt :: Vector3D\n , mHorizontalFOV :: Float\n , mClipPlaneNear :: Float\n , mClipPlaneFar :: Float\n , mAspect :: Float\n } deriving (Show)\n{#pointer *aiCamera as CameraPtr -> Camera#}\n\ndata Scene = Scene\n { mFlags :: [SceneFlags]\n , mRootNode :: Node\n , mMeshes :: [Mesh]\n , mMaterials :: [Material]\n , mAnimations :: [Animation]\n , mTextures :: [Texture]\n , mLights :: [Light]\n , mCameras :: [Camera]\n } deriving (Show)\n{#pointer *aiScene as ScenePtr -> Scene#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls #-}\nmodule Graphics.Formats.Assimp.Types (\n SceneFlags(..)\n , PostProcessSteps(..)\n , Return(..)\n , Origin(..)\n , DefaultLogStream(..)\n , PrimitiveType(..)\n , LightSourceType(..)\n , TextureOp(..)\n , TextureMapMode(..)\n , TextureMapping(..)\n , TextureType(..)\n , ShadingMode(..)\n , TextureFlags(..)\n , BlendMode(..)\n , PropertyTypeInfo(..)\n , Plane(..)\n , Ray(..)\n , Color3D(..)\n , Color4D(..)\n , MemoryInfo(..)\n , Quaternion(..)\n , Vector2D(..)\n , Vector3D(..)\n , AiString(..)\n , Matrix3x3(..)\n , Matrix4x4(..)\n , Node(..)\n , Face(..)\n , VertexWeight(..)\n , Bone(..)\n , Mesh(..)\n , MaterialProperty(..)\n , Material(..)\n , NodeAnim(..)\n , MeshAnim(..)\n , Animation(..)\n , Light(..)\n , Camera(..)\n , Scene(..)\n , Texture(..)\n , Texel(..)\n , (.|.)\n ) where\n\nimport C2HS\nimport Data.Vector hiding ((++))\nimport Data.Bits ((.|.))\n\n#include \"..\/..\/assimp\/include\/assimp.h\" \/\/ Plain-C interface\n#include \"..\/..\/assimp\/include\/aiScene.h\" \/\/ Output data structure\n#include \"..\/..\/assimp\/include\/aiPostProcess.h\" \/\/ Post processing flags\n#include \"typedefs.h\"\n\n{#context lib=\"assimp\"#}\n{#context prefix=\"ai\"#}\n\n{#enum define SceneFlags {AI_SCENE_FLAGS_INCOMPLETE as FlagsIncomplete\n , AI_SCENE_FLAGS_VALIDATED as FlagsValidated\n , AI_SCENE_FLAGS_VALIDATION_WARNING as FlagsValidationWarning\n , AI_SCENE_FLAGS_NON_VERBOSE_FORMAT as FlagsNonVerboseFormat\n , AI_SCENE_FLAGS_TERRAIN as FlagsTerrain\n }#}\ninstance Show SceneFlags where\n show FlagsIncomplete = \"FlagsIncomplete\"\n show FlagsValidated = \"FlagsValidated\"\n show FlagsValidationWarning = \"FlagsValidationWarning\"\n show FlagsNonVerboseFormat = \"FlagsNonVerboseFormat\"\n show FlagsTerrain = \"FlagsTerrain\"\n\n{#enum aiPostProcessSteps as PostProcessSteps {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiReturn as Return {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiOrigin as Origin {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiDefaultLogStream as DefaultLogStream {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiPrimitiveType as PrimitiveType {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiLightSourceType as LightSourceType {underscoreToCase} deriving (Show, Eq)#}\n\n-- Texture enums\n{#enum aiTextureOp as TextureOp {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureMapMode as TextureMapMode {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureMapping as TextureMapping {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureType as TextureType {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiShadingMode as ShadingMode {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiTextureFlags as TextureFlags {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiBlendMode as BlendMode {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiPropertyTypeInfo as PropertyTypeInfo {underscoreToCase} deriving (Show, Eq)#}\n\ndata Plane = Plane {\n a'Plane :: Float\n , b'Plane :: Float\n , c'Plane :: Float\n , d'Plane :: Float\n } deriving (Show)\n{#pointer *aiPlane as PlanePtr -> Plane#}\n\ndata Ray = Ray {\n pos'Ray :: Vector3D\n , dir'Ray :: Vector3D\n } deriving (Show)\n{#pointer *aiRay as RayPtr -> Ray#}\n\ndata Color3D = Color3D {\n r'Color3D :: Float\n , g'Color3D :: Float\n , b'Color3D :: Float\n } deriving (Show)\n{#pointer *aiColor3D as Color3DPtr -> Color3D#}\n\ndata Color4D = Color4D {\n r'Color4D :: Float\n , g'Color4D :: Float\n , b'Color4D :: Float\n , a'Color4D :: Float\n } deriving (Show)\n{#pointer *aiColor4D as Color4DPtr -> Color4D#}\n\ndata MemoryInfo = MemoryInfo {\n textures'MemoryInfo :: CUInt\n , materials'MemoryInfo :: CUInt\n , meshes'MemoryInfo :: CUInt\n , nodes'MemoryInfo :: CUInt\n , animations'MemoryInfo :: CUInt\n , cameras'MemoryInfo :: CUInt\n , lights'MemoryInfo :: CUInt\n , total'MemoryInfo :: CUInt\n } deriving (Show)\n{#pointer *aiMemoryInfo as MemoryInfoPtr -> MemoryInfo#}\n\ndata LogStream\n{#pointer *aiLogStream as LogStreamPtr -> LogStream#}\n\ndata Quaternion = Quaternion {\n w'Quaternion :: Float\n , x'Quaternion :: Float\n , y'Quaternion :: Float\n , z'Quaternion :: Float\n } deriving (Show)\n{#pointer *aiQuaternion as QuaternionPtr -> Quaternion#}\n\ndata Vector2D = Vector2D {\n x'Vector2D :: Float\n , y'Vector2D :: Float\n } deriving (Show)\n{#pointer *aiVector2D as Vector2DPtr -> Vector2D#}\n\ndata Vector3D = Vector3D {\n x'Vector3D :: Float\n , y'Vector3D :: Float\n , z'Vector3D :: Float\n } deriving (Show)\n{#pointer *aiVector3D as Vector3DPtr -> Vector3D#}\n\nnewtype AiString = AiString String deriving (Show)\n{#pointer *aiString as StringPtr -> AiString#}\n\ndata Matrix3x3 = Matrix3x3 {\n matrix'Matrix3x3 :: Vector (Vector Float)\n } deriving (Show)\n{#pointer *aiMatrix3x3 as Matrix3x3Ptr -> Matrix3x3#}\n\ndata Matrix4x4 = Matrix4x4 {\n matrix'Matrix4x4 :: Vector (Vector Float)\n } deriving (Show)\n{#pointer *aiMatrix4x4 as Matrix4x4Ptr -> Matrix4x4#}\n\n{- From the Assimp source:\n -\n - Nodes are little named entities in the scene that have a place and\n - orientation relative to their parents. Starting from the scene's root node\n - all nodes can have 0 to x child nodes, thus forming a hierarchy. They form\n - the base on which the scene is built on: a node can refer to 0..x meshes,\n - can be referred to by a bone of a mesh or can be animated by a key sequence\n - of an animation. DirectX calls them \"frames\", others call them \"objects\", we\n - call them aiNode.\n -\n - A node can potentially refer to single or multiple meshes. The meshes are\n - not stored inside the node, but instead in an array of aiMesh inside the\n - aiScene. A node only refers to them by their array index. This also means\n - that multiple nodes can refer to the same mesh, which provides a simple form\n - of instancing. A mesh referred to by this way lives in the node's local\n - coordinate system. If you want the mesh's orientation in global space, you'd\n - have to concatenate the transformations from the referring node and all of\n - its parents.\n-}\ndata Node = Node\n { mName'Node :: String\n , mTransformation'Node :: Matrix4x4\n , mParent'Node :: Maybe Node\n , mChildren'Node :: [Node]\n , mMeshes'Node :: [CUInt] -- Holds indices defining the node\n } deriving (Show)\n{#pointer *aiNode as NodePtr -> Node#}\n\ndata Face = Face\n {\n mIndices'Face :: [CUInt] -- Holds indices defining the face\n } deriving (Show)\n{#pointer *aiFace as FacePtr -> Face#}\n\ndata VertexWeight = VertexWeight\n { mVertexId'VertexWeight :: CUInt\n , mWeight'VertexWeight :: CFloat\n } deriving (Show)\n{#pointer *aiVertexWeight as VertexWeightPtr -> VertexWeight#}\n\ndata Bone = Bone\n { mName'Bone :: String\n , mWeights'Bone :: [VertexWeight]\n , mOffpokeMatrix'Bone :: Matrix4x4\n } deriving (Show)\n{#pointer *aiBone as BonePtr -> Bone#}\n\ndata Mesh = Mesh\n { mPrimitiveTypes'Mesh :: [PrimitiveType]\n , mVertices'Mesh :: [Vector3D]\n , mNormals'Mesh :: [Vector3D]\n , mTangents'Mesh :: [Vector3D]\n , mBitangents'Mesh :: [Vector3D]\n , mColors'Mesh :: [Color4D]\n , mTextureCoords'Mesh :: [Vector3D]\n , mNumUVComponents'Mesh :: CUInt\n , mFaces'Mesh :: [Face]\n , mBones'Mesh :: [Bone]\n , mMaterialIndex'Mesh :: CUInt\n , mName'Mesh :: String\n } deriving (Show)\n{#pointer *aiMesh as MeshPtr -> Mesh#}\n\ndata MaterialProperty = MaterialProperty {\n mKey :: String\n , mSemantic :: TextureType\n , mIndex :: CUInt\n , mData :: String\n } deriving (Show)\n{#pointer *aiMaterialProperty as MaterialPropertyPtr -> MaterialProperty#}\n\ndata Material = Material {\n mProperties'Material :: [MaterialProperty]\n } deriving (Show)\n{#pointer *aiMaterial as MaterialPtr -> Material#}\n\ndata NodeAnim = NodeAnim {\n dummy'NodeAnim :: Int\n } deriving (Show)\n\ndata MeshAnim = MeshAnim {\n dummy'MeshAnim :: Int\n } deriving (Show)\n\ndata Animation = Animation {\n mName'Animation :: String\n , mDuration'Animation :: Double\n , mTicksPerSecond'Animation :: Double\n , mChannels'Animation :: [NodeAnim]\n , mMeshChannels'Animation :: [MeshAnim]\n } deriving (Show)\n{#pointer *aiAnimation as AnimationPtr -> Animation#}\n\ndata Texel = Texel {\n dummy'Texel :: Int\n } deriving (Show)\n\ndata Texture = Texture {\n mWidth'Texture :: CUInt\n , mHeight'Texture :: CUInt\n , achFormatHint'Texture :: String\n , pcData'Texture :: [Texel]\n } deriving (Show)\n{#pointer *aiTexture as TexturePtr -> Texture#}\n\ndata UVTransform = UVTransform {\n mTranslation'UVTransform :: Vector2D\n , mScaling'UVTransform :: Vector2D\n , mRotation'UVTransform :: Float\n } deriving (Show)\n\ndata Light = Light {\n mName'Light :: String\n , mType'Light :: LightSourceType\n , mPosition'Light :: Vector3D\n , mDirection'Light :: Vector3D\n , mAttenuationConstant'Light :: Float\n , mAttenuationLinear'Light :: Float\n , mAttenuationQuadratic'Light :: Float\n , mColorDiffuse'Light :: Color3D\n , mColorSpecular'Light :: Color3D\n , mColorAmbient'Light :: Color3D\n , mAngleInnerCone'Light :: Float\n , mAngleOuterCone'Light :: Float\n } deriving (Show)\n{#pointer *aiLight as LightPtr -> Light#}\n\ndata Camera = Camera {\n mName'Camera :: String\n , mPosition'Camera :: Vector3D\n , mUp'Camera :: Vector3D\n , mLookAt'Camera :: Vector3D\n , mHorizontalFOV'Camera :: Float\n , mClipPlaneNear'Camera :: Float\n , mClipPlaneFar'Camera :: Float\n , mAspect'Camera :: Float\n } deriving (Show)\n{#pointer *aiCamera as CameraPtr -> Camera#}\n\ndata Scene = Scene\n { mFlags'Scene :: [SceneFlags]\n , mRootNode'Scene :: Node\n , mMeshes'Scene :: [Mesh]\n , mMaterials'Scene :: [Material]\n , mAnimations'Scene :: [Animation]\n , mTextures'Scene :: [Texture]\n , mLights'Scene :: [Light]\n , mCameras'Scene :: [Camera]\n } deriving (Show)\n{#pointer *aiScene as ScenePtr -> Scene#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f8249b7372d959c595650dc5aa737f757736321b","subject":"missing import for 2.0.1","message":"missing import for 2.0.1\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , createFeature\n , getFeature\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Int (Int64)\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..), CLLong(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException MultipleGeomFieldsNotSupported\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncreateFeature :: RWLayer s a -> Feature -> GDAL s ()\ncreateFeature layer feature = liftIO $ throwIfError \"createFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n void $ featureToHandle pFd feature ({#call OGR_L_CreateFeature as ^#} pL)\n\n\ngetFeature :: Layer s t a -> Int64 -> GDAL s Feature\ngetFeature layer fid = liftIO $ throwIfError \"getFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n featureFromHandle pFd ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n <*> pure True\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , createFeature\n , getFeature\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Int (Int64)\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException MultipleGeomFieldsNotSupported\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncreateFeature :: RWLayer s a -> Feature -> GDAL s ()\ncreateFeature layer feature = liftIO $ throwIfError \"createFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n void $ featureToHandle pFd feature ({#call OGR_L_CreateFeature as ^#} pL)\n\n\ngetFeature :: Layer s t a -> Int64 -> GDAL s Feature\ngetFeature layer fid = liftIO $ throwIfError \"getFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n featureFromHandle pFd ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n <*> pure True\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"59c982871fa1edca358c6925bf8088a8926cb9f2","subject":"trivial formatting","message":"trivial formatting\n\nIgnore-this: 6a87cf42602c24f2e1bfd610f11265cb\n\ndarcs-hash:20100610032545-dcabc-2336607487133ab50556793986bb5aeb7e3d2dc8.gz\n","repos":"mwu-tow\/cuda,phaazon\/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 (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","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":"fcbbdc415d692e61846e9fb4eb524d9372094b93","subject":"Add optional default string for flInput.","message":"Add optional default string for flInput.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Data.Maybe (fromMaybe)\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input_with_deflt as flInput' { `CString',`CString' } -> `CString' #}\nflInput :: T.Text -> Maybe T.Text -> IO (Maybe T.Text)\nflInput msg maybeDefault = do\n msgC <- copyTextToCString msg\n let def = fromMaybe T.empty maybeDefault\n defaultC <- copyTextToCString def\n r <- flInput' msgC defaultC\n cStringToMaybeText r\n\n{# fun flc_password as flPassword' { `CString' } -> `CString' #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- copyTextToCString msg >>= flPassword'\n cStringToMaybeText r\n\n{# fun flc_message as flMessage' { `CString' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage t = copyTextToCString t >>= flMessage'\n\n{# fun flc_alert as flAlert' { `CString' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert t = copyTextToCString t >>= flAlert'\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input as flInput' { `CString' } -> `CString' #}\nflInput :: T.Text -> IO (Maybe T.Text)\nflInput msg = do\n r <- copyTextToCString msg >>= flInput'\n cStringToMaybeText r\n\n{# fun flc_password as flPassword' { `CString' } -> `CString' #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- copyTextToCString msg >>= flPassword'\n cStringToMaybeText r\n\n{# fun flc_message as flMessage' { `CString' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage t = copyTextToCString t >>= flMessage'\n\n{# fun flc_alert as flAlert' { `CString' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert t = copyTextToCString t >>= flAlert'\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"1511cf67603d3de35e4bb5bd279c18e78f41cf7e","subject":"Haddock fix","message":"Haddock fix\n","repos":"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{-# LANGUAGE TemplateHaskell #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : [2009..2014] 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(..), SharedMem(..),\n requires,\n setCacheConfigFun,\n setSharedMemConfigFun,\n launchKernel, launchKernel',\n\n -- Deprecated since CUDA-4.0\n setBlockShape, setSharedSize, setParams, launch,\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(..), SharedMem(..) )\nimport Foreign.CUDA.Driver.Stream ( Stream(..), defaultStream )\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 peek _ = error \"Can not peek Foreign.CUDA.Driver.FunParam\"\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel.\n--\n-- \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-- 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-- Requires CUDA-3.0.\n--\n-- \n--\n{-# INLINEABLE setCacheConfigFun #-}\nsetCacheConfigFun :: Fun -> Cache -> IO ()\n#if CUDA_VERSION < 3000\nsetCacheConfigFun _ _ = requireSDK 'setCacheConfigFun 3.0\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-- |\n-- Set the shared memory configuration of a device function.\n--\n-- On devices with configurable shared memory banks, this will force all\n-- subsequent launches of the given device function to use the specified\n-- shared memory bank size configuration. On launch of the function, the\n-- shared memory configuration of the device will be temporarily changed if\n-- needed to suit the function configuration. Changes in shared memory\n-- configuration may introduction a device side synchronisation between\n-- kernel launches.\n--\n-- Any per-function configuration specified by 'setSharedMemConfig' will\n-- override the context-wide configuration set with\n-- 'Foreign.CUDA.Driver.Context.Config.setSharedMem'.\n--\n-- Changing the shared memory bank size will not increase shared memory\n-- usage or affect occupancy of kernels, but may have major effects on\n-- performance. Larger bank sizes will allow for greater potential\n-- bandwidth to shared memory, but will change what kinds of accesses to\n-- shared memory will result in bank conflicts.\n--\n-- This function will do nothing on devices with fixed shared memory bank\n-- size.\n--\n-- Requires CUDA-5.0.\n--\n-- \n--\n{-# INLINEABLE setSharedMemConfigFun #-}\nsetSharedMemConfigFun :: Fun -> SharedMem -> IO ()\n#if CUDA_VERSION < 5000\nsetSharedMemConfigFun _ _ = requireSDK 'setSharedMemConfigFun 5.0\n#else\nsetSharedMemConfigFun !fun !pref = nothingIfOk =<< cuFuncSetSharedMemConfig fun pref\n\n{-# INLINE cuFuncSetSharedMemConfig #-}\n{# fun unsafe cuFuncSetSharedMemConfig\n { useFun `Fun'\n , cFromEnum `SharedMem'\n }\n -> `Status' cToEnum #}\n#endif\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-- \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 defaultStream 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 defaultStream 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-- Deprecated\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--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch !fn (!w,!h) mst =\n nothingIfOk =<< cuLaunchGridAsync fn w h (fromMaybe defaultStream mst)\n\n{-# INLINE cuLaunchGridAsync #-}\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `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-- 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\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TemplateHaskell #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : [2009..2014] 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(..), SharedMem(..),\n requires,\n setCacheConfigFun,\n setSharedMemConfigFun,\n launchKernel, launchKernel',\n\n -- Deprecated since CUDA-4.0\n setBlockShape, setSharedSize, setParams, launch,\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(..), SharedMem(..) )\nimport Foreign.CUDA.Driver.Stream ( Stream(..), defaultStream )\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 peek _ = error \"Can not peek Foreign.CUDA.Driver.FunParam\"\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel.\n--\n-- \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-- 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-- Requires CUDA-3.0.\n--\n-- \n--\n{-# INLINEABLE setCacheConfigFun #-}\nsetCacheConfigFun :: Fun -> Cache -> IO ()\n#if CUDA_VERSION < 3000\nsetCacheConfigFun _ _ = requireSDK 'setCacheConfigFun 3.0\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-- |\n-- Set the shared memory configuration of a device function.\n--\n-- On devices with configurable shared memory banks, this will force all\n-- subsequent launches of the given device function to use the specified\n-- shared memory bank size configuration. On launch of the function, the\n-- shared memory configuration of the device will be temporarily changed if\n-- needed to suit the function configuration. Changes in shared memory\n-- configuration may introduction a device side synchronisation between\n-- kernel launches.\n--\n-- Any per-function configuration specified by 'setSharedMemConfig' will\n-- override the context-wide configuration set with\n-- 'Foreign.CUDA.Driver.Context.Config.setSharedMem'.\n--\n-- Changing the shared memory bank size will not increase shared memory\n-- usage or affect occupancy of kernels, but may have major effects on\n-- performance. Larger bank sizes will allow for greater potential\n-- bandwidth to shared memory, but will change what kinds of accesses to\n-- shared memory will result in bank conflicts.\n--\n-- This function will do nothing on devices with fixed shared memory bank\n-- size.\n--\n-- Requires CUDA-5.0.\n--\n-- \n--\n{-# INLINEABLE setSharedMemConfigFun #-}\nsetSharedMemConfigFun :: Fun -> SharedMem -> IO ()\n#if CUDA_VERSION < 5000\nsetSharedMemConfigFun _ _ = requireSDK 'setSharedMemConfigFun 5.0\n#else\nsetSharedMemConfigFun !fun !pref = nothingIfOk =<< cuFuncSetSharedMemConfig fun pref\n\n{-# INLINE cuFuncSetSharedMemConfig #-}\n{# fun unsafe cuFuncSetSharedMemConfig\n { useFun `Fun'\n , cFromEnum `SharedMem'\n }\n -> `Status' cToEnum #}\n#endif\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-- \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 defaultStream 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 defaultStream 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-- Deprecated\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--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch !fn (!w,!h) mst =\n nothingIfOk =<< cuLaunchGridAsync fn w h (fromMaybe defaultStream mst)\n\n{-# INLINE cuLaunchGridAsync #-}\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `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-- 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\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"364e1e7a0611d2b2c2440405de7a8235eb434f77","subject":"add cache configuration binding (v3.0 and above)","message":"add cache configuration binding (v3.0 and above)\n\nIgnore-this: ecba1d6a091b13d8c9cb05ab12a77ac8\n\ndarcs-hash:20100609045338-dcabc-6407368ca9fa0958d869b4c07ffc1265a101bd59.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_contents":"{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) [2009..2010] 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(..), CacheConfig(..),\n requires, setBlockShape, setSharedSize, setCacheConfig, 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#if CUDA_VERSION >= 3000\n-- |\n-- Cache configuration preference\n--\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\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#if CUDA_VERSION >= 3000\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; and the driver is free to choose a\n-- different 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--\nsetCacheConfig :: Fun -> CacheConfig -> IO ()\nsetCacheConfig 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-- 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 (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 GADTs #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) [2009..2010] 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 FunParam where\n IArg :: Int -> FunParam\n FArg :: Float -> FunParam\n-- TArg :: Texture -> FunParam\n VArg :: Storable a => a -> FunParam\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 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 :: 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{# 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":"b1505f008cd7d0fdd44a750e77955eb02436b055","subject":"add return error string","message":"add return error string\n","repos":"mith\/hs-assimp","old_file":"src\/Assimp.chs","new_file":"src\/Assimp.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\nmodule Assimp \n ( loadSceneFile \n , PostProcessStep(..)\n ) where\n\nimport Filesystem.Path.CurrentOS as FP\nimport Foreign.C\nimport Foreign.Safe\nimport Data.Bits\nimport Control.Applicative\n\nimport Assimp.Scene\n\n#include \n#include \n#include \"typedefs.h\"\n\n{#enum aiPostProcessSteps as PostProcessStep {} with prefix = \"aiProcess_\" deriving (Show) #}\n\nloadSceneFile :: FP.FilePath -> [PostProcessStep] -> IO (Either String Scene)\nloadSceneFile fp pps = withCString (FP.encodeString fp) importFile\n where\n\tflagsToBits :: CUInt\n\tflagsToBits = foldr (.|.) 0 . map (fromIntegral . fromEnum) $ pps\n importFile :: CString -> IO (Either String Scene)\n importFile cs = do sp <- {# call aiImportFile #} cs flagsToBits\n\t\t \t if sp == nullPtr\n\t\t\t then Left <$> (peekCString =<< {# call aiGetErrorString #})\n\t\t\t else Right <$> do sc <- peek (castPtr sp)\n\t\t\t {# call aiReleaseImport #} sp\n\t\t\t\t\t return sc\n \n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\nmodule Assimp \n ( loadSceneFile \n , PostProcessStep(..)\n ) where\n\nimport Filesystem.Path.CurrentOS as FP\nimport Foreign.C\nimport Foreign.Safe\nimport Data.Bits\nimport Control.Applicative\n\nimport Assimp.Scene\n\n#include \n#include \n#include \"typedefs.h\"\n\n{#enum aiPostProcessSteps as PostProcessStep {} with prefix = \"aiProcess_\" deriving (Show) #}\n\nloadSceneFile :: FP.FilePath -> [PostProcessStep] -> IO (Either String Scene)\nloadSceneFile fp pps = withCString (FP.encodeString fp) importFile\n where\n\tflagsToBits :: CUInt\n\tflagsToBits = foldr (.|.) 0 . map (fromIntegral . fromEnum) $ pps\n importFile :: CString -> IO (Either String Scene)\n importFile cs = do sp <- {# call aiImportFile #} cs flagsToBits\n\t\t \t if sp == nullPtr\n\t\t\t then return $ Left \"fail\"\n\t\t\t else Right <$> do sc <- peek (castPtr sp)\n\t\t\t {# call aiReleaseImport #} sp\n\t\t\t\t\t return sc\n \n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"f65d8acdd794165cf760e9b23b1799593f60b621","subject":"add option flags to host allocation","message":"add option flags to host allocation\n\nIgnore-this: 89c53d2f0e3d8ec6c14de4a96492c805\n- correspondingly, get a device pointer from mapped, pinned host memory\n\ndarcs-hash:20091209234733-9241b-b4e2536923ec1d5fcb34b4aeb0d29e75446e516c.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/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, withStream)\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 deriving (Show)\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. Note that since the amount of pageable\n-- memory is thusly reduced, overall system performance may suffer. This is best\n-- used sparingly to allocate staging areas for data exchange.\n--\nmallocHost :: [AllocFlag] -> Int -> IO (Either String (HostPtr a))\nmallocHost flags bytes =\n newHostPtr >>= \\hp -> withHostPtr hp $ \\p ->\n cuMemHostAlloc p bytes flags >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right hp\n Just err -> Left err\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 (Maybe String)\nfreeHost hp = withHostPtr hp $ \\p -> (nothingIfOk `fmap` 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 suitably aligned for any type, and is not cleared.\n--\nmalloc :: Int -> IO (Either String (DevicePtr a))\nmalloc bytes = resultIfOk `fmap` cuMemAlloc bytes\n\n{# fun unsafe cuMemAlloc\n { alloca- `DevicePtr a' dptr*\n , `Int' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peekIntConv\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO (Maybe String)\nfree dp = nothingIfOk `fmap` 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 (Maybe String)\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ = nothingIfOk `fmap` 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 (Maybe String)\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyDtoHAsync\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPoke x _ = nothingIfOk `fmap` 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 (Maybe String)\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n dopoke x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk `fmap` cuMemsetD8 dptr val n\n 2 -> nothingIfOk `fmap` cuMemsetD16 dptr val n\n 4 -> nothingIfOk `fmap` cuMemsetD32 dptr val n\n _ -> return $ Just \"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 (Either String (DevicePtr a))\ngetDevicePtr flags hptr = withHostPtr hptr $ \\hp -> (resultIfOk `fmap` 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 . peekIntConv\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,\n malloc, free, mallocHost, freeHost,\n peekArray, peekArrayAsync, pokeArray, pokeArrayAsync, memset\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, withStream)\n\n-- System\nimport Foreign hiding (peekArray, pokeArray, malloc, free)\nimport Foreign.C\nimport Control.Monad (liftM)\nimport Unsafe.Coerce\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 deriving (Show)\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-- 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. Note that since the amount of pageable\n-- memory is thusly reduced, overall system performance may suffer. This is best\n-- used sparingly to allocate staging areas for data exchange.\n--\nmallocHost :: Int -> IO (Either String (HostPtr a))\nmallocHost bytes =\n newHostPtr >>= \\hp -> withHostPtr hp $ \\p ->\n cuMemAllocHost p bytes >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right hp\n Just err -> Left err\n\n{# fun unsafe cuMemAllocHost\n { with'* `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n where with' = with . castPtr\n\n\n-- |\n-- Free a section of page-locked host memory\n--\nfreeHost :: HostPtr a -> IO (Maybe String)\nfreeHost hp = withHostPtr hp $ \\p -> (nothingIfOk `fmap` 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 suitably aligned for any type, and is not cleared.\n--\nmalloc :: Int -> IO (Either String (DevicePtr a))\nmalloc bytes = resultIfOk `fmap` cuMemAlloc bytes\n\n{# fun unsafe cuMemAlloc\n { alloca- `DevicePtr a' dptr*\n , `Int' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peekIntConv\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO (Maybe String)\nfree dp = nothingIfOk `fmap` 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 (Maybe String)\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ = nothingIfOk `fmap` 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 (Maybe String)\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyDtoHAsync\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPoke x _ = nothingIfOk `fmap` 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 (Maybe String)\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n dopoke x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk `fmap` cuMemsetD8 dptr val n\n 2 -> nothingIfOk `fmap` cuMemsetD16 dptr val n\n 4 -> nothingIfOk `fmap` cuMemsetD32 dptr val n\n _ -> return $ Just \"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\n-- into the required integer type.\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"11d6f72fb46da03f24060a5743a7e2d6029ecc14","subject":"removed unused import","message":"removed unused import\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/CPLError.chs","new_file":"src\/GDAL\/Internal\/CPLError.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n , checkCPLError\n , checkGDALCall\n , checkGDALCall_\n , withQuietErrorHandler\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Concurrent (runInBoundThread, rtsSupportsBoundThreads)\nimport Control.Monad (void, liftM)\nimport Control.Monad.Catch (MonadThrow(throwM))\nimport Control.Exception (\n Exception (..)\n , SomeException\n , throw\n , finally\n )\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable, cast)\n\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr)\nimport Foreign.Storable (peekByteOff, peek)\nimport Foreign.Marshal.Utils (with)\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport GDAL.Internal.Util (toEnumC)\nimport GDAL.Internal.CPLString (peekEncodedCString)\n\n#include \"cpl_error.h\"\n#include \"errorhandler.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ndata GDALException\n = forall e. Exception e =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !Text}\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException :: Exception e=> e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException :: Exception e => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\nthrowBindingException :: (MonadThrow m, Exception e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\n\ncheckGDALCall\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO a\ncheckGDALCall isOk act = withErrorHandler $ \\ stack -> do\n a <- act\n err <- peekLastError stack\n case isOk err a of\n Nothing -> return a\n Just e -> throw e\n{-# INLINE checkGDALCall #-}\n\ncheckGDALCall_\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO ()\n{-# INLINE checkGDALCall_ #-}\ncheckGDALCall_ isOk = void . checkGDALCall isOk\n\ncheckCPLError :: Text -> IO CInt -> IO ()\ncheckCPLError msg = checkGDALCall_ $ \\mExc r ->\n case (mExc, toEnumC r) of\n (Nothing, CE_None) -> Nothing\n (Nothing, e) -> Just (GDALException e AssertionFailed msg)\n (e, _) -> e\n{-# INLINE checkCPLError #-}\n\n{#pointer ErrorCell #}\ntype ErrorStack = Ptr ErrorCell\n\npeekLastError :: ErrorStack -> IO (Maybe GDALException)\npeekLastError stack = do\n ec <- peek stack\n if ec == nullPtr\n then return Nothing\n else do\n msg <- peekEncodedCString =<< {#get ErrorCell->msg #} ec\n errClass <- liftM toEnumC ({#get ErrorCell->errClass#} ec)\n errNo <- liftM toEnumC ({#get ErrorCell->errNo#} ec)\n return (Just (GDALException errClass errNo msg))\n\nwithErrorHandler :: (ErrorStack -> IO a) -> IO a\nwithErrorHandler act = runBounded $ with nullPtr $ \\stack ->\n ({#call unsafe push_error_handler as ^#} stack >> act stack)\n `finally` ({#call unsafe pop_error_handler as ^#} stack)\n{-# INLINE withErrorHandler #-}\n\nrunBounded :: IO a -> IO a\nrunBounded\n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n{-# INLINE runBounded #-}\n\nwithQuietErrorHandler :: IO a -> IO a\nwithQuietErrorHandler a = runBounded ((pushIt >> a) `finally` popIt)\n where\n pushIt = {#call unsafe CPLPushErrorHandler as ^#} c_quietErrorHandler\n popIt = {#call unsafe CPLPopErrorHandler as ^#}\n\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr (CInt -> CInt -> Ptr CChar -> IO ())\n","old_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n , checkCPLError\n , checkGDALCall\n , checkGDALCall_\n , withQuietErrorHandler\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Concurrent (runInBoundThread, rtsSupportsBoundThreads)\nimport Control.Monad (void, liftM)\nimport Control.Monad.Catch (MonadThrow(throwM))\nimport Control.Exception (\n Exception (..)\n , SomeException\n , throw\n , bracket\n , finally\n )\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable, cast)\n\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr)\nimport Foreign.Storable (peekByteOff, peek)\nimport Foreign.Marshal.Utils (with)\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport GDAL.Internal.Util (toEnumC)\nimport GDAL.Internal.CPLString (peekEncodedCString)\n\n#include \"cpl_error.h\"\n#include \"errorhandler.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ndata GDALException\n = forall e. Exception e =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !Text}\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException :: Exception e=> e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException :: Exception e => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\nthrowBindingException :: (MonadThrow m, Exception e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\n\ncheckGDALCall\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO a\ncheckGDALCall isOk act = withErrorHandler $ \\ stack -> do\n a <- act\n err <- peekLastError stack\n case isOk err a of\n Nothing -> return a\n Just e -> throw e\n{-# INLINE checkGDALCall #-}\n\ncheckGDALCall_\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO ()\n{-# INLINE checkGDALCall_ #-}\ncheckGDALCall_ isOk = void . checkGDALCall isOk\n\ncheckCPLError :: Text -> IO CInt -> IO ()\ncheckCPLError msg = checkGDALCall_ $ \\mExc r ->\n case (mExc, toEnumC r) of\n (Nothing, CE_None) -> Nothing\n (Nothing, e) -> Just (GDALException e AssertionFailed msg)\n (e, _) -> e\n{-# INLINE checkCPLError #-}\n\n{#pointer ErrorCell #}\ntype ErrorStack = Ptr ErrorCell\n\npeekLastError :: ErrorStack -> IO (Maybe GDALException)\npeekLastError stack = do\n ec <- peek stack\n if ec == nullPtr\n then return Nothing\n else do\n msg <- peekEncodedCString =<< {#get ErrorCell->msg #} ec\n errClass <- liftM toEnumC ({#get ErrorCell->errClass#} ec)\n errNo <- liftM toEnumC ({#get ErrorCell->errNo#} ec)\n return (Just (GDALException errClass errNo msg))\n\nwithErrorHandler :: (ErrorStack -> IO a) -> IO a\nwithErrorHandler act = runBounded $ with nullPtr $ \\stack ->\n ({#call unsafe push_error_handler as ^#} stack >> act stack)\n `finally` ({#call unsafe pop_error_handler as ^#} stack)\n{-# INLINE withErrorHandler #-}\n\nrunBounded :: IO a -> IO a\nrunBounded\n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n{-# INLINE runBounded #-}\n\nwithQuietErrorHandler :: IO a -> IO a\nwithQuietErrorHandler a = runBounded ((pushIt >> a) `finally` popIt)\n where\n pushIt = {#call unsafe CPLPushErrorHandler as ^#} c_quietErrorHandler\n popIt = {#call unsafe CPLPopErrorHandler as ^#}\n\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr (CInt -> CInt -> Ptr CChar -> IO ())\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"27fbd3251b20b4e774460ee15364041d0188668b","subject":"Bindings for MPI_COMM_SELF (predefined handle)","message":"Bindings for MPI_COMM_SELF (predefined handle)\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Comm.chs","new_file":"src\/Control\/Parallel\/MPI\/Comm.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Comm (Comm, commWorld, commSelf) where\n\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_comm_self\" commSelf :: Comm\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Comm (Comm, commWorld) where\n\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"86776da52335f8479dcb67aa6f9219641758a6e7","subject":"Add missing Node functions","message":"Add missing Node functions\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/Node.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/Node.chs","new_contents":"module Graphics.UI.Gtk.WebKit.DOM.Node\n (nodeInsertBefore, nodeReplaceChild, nodeRemoveChild,\n nodeAppendChild, nodeHasChildNodes, nodeCloneNode, nodeNormalize,\n nodeIsSupported, nodeHasAttributes, nodeIsSameNode,\n nodeIsEqualNode, nodeLookupPrefix, nodeIsDefaultNamespace,\n nodeLookupNamespaceURI, nodeCompareDocumentPosition, nodeContains,\n nodeDispatchEvent, cELEMENT_NODE, cATTRIBUTE_NODE, cTEXT_NODE,\n cCDATA_SECTION_NODE, cENTITY_REFERENCE_NODE, cENTITY_NODE,\n cPROCESSING_INSTRUCTION_NODE, cCOMMENT_NODE, cDOCUMENT_NODE,\n cDOCUMENT_TYPE_NODE, cDOCUMENT_FRAGMENT_NODE, cNOTATION_NODE,\n cDOCUMENT_POSITION_DISCONNECTED, cDOCUMENT_POSITION_PRECEDING,\n cDOCUMENT_POSITION_FOLLOWING, cDOCUMENT_POSITION_CONTAINS,\n cDOCUMENT_POSITION_CONTAINED_BY,\n cDOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, nodeGetNodeName,\n nodeSetNodeValue, nodeGetNodeValue, nodeGetNodeType,\n nodeGetParentNode, nodeGetChildNodes, nodeGetFirstChild,\n nodeGetLastChild, nodeGetPreviousSibling, nodeGetNextSibling,\n nodeGetAttributes, nodeGetOwnerDocument, nodeGetNamespaceURI,\n nodeSetPrefix, nodeGetPrefix, nodeGetLocalName, nodeGetBaseURI,\n nodeSetTextContent, nodeGetTextContent, nodeGetParentElement)\n where\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Graphics.UI.Gtk.WebKit.DOM.EventM\n \nnodeInsertBefore ::\n (NodeClass self, NodeClass newChild, NodeClass refChild) =>\n self -> Maybe newChild -> Maybe refChild -> IO (Maybe Node)\nnodeInsertBefore self newChild refChild\n = maybeNull (makeNewGObject mkNode)\n (propagateGError $\n \\ errorPtr_ ->\n {# call webkit_dom_node_insert_before #} (toNode self)\n (maybe (Node nullForeignPtr) toNode newChild)\n (maybe (Node nullForeignPtr) toNode refChild)\n errorPtr_)\n \nnodeReplaceChild ::\n (NodeClass self, NodeClass newChild, NodeClass oldChild) =>\n self -> Maybe newChild -> Maybe oldChild -> IO (Maybe Node)\nnodeReplaceChild self newChild oldChild\n = maybeNull (makeNewGObject mkNode)\n (propagateGError $\n \\ errorPtr_ ->\n {# call webkit_dom_node_replace_child #} (toNode self)\n (maybe (Node nullForeignPtr) toNode newChild)\n (maybe (Node nullForeignPtr) toNode oldChild)\n errorPtr_)\n \nnodeRemoveChild ::\n (NodeClass self, NodeClass oldChild) =>\n self -> Maybe oldChild -> IO (Maybe Node)\nnodeRemoveChild self oldChild\n = maybeNull (makeNewGObject mkNode)\n (propagateGError $\n \\ errorPtr_ ->\n {# call webkit_dom_node_remove_child #} (toNode self)\n (maybe (Node nullForeignPtr) toNode oldChild)\n errorPtr_)\n \nnodeAppendChild ::\n (NodeClass self, NodeClass newChild) =>\n self -> Maybe newChild -> IO (Maybe Node)\nnodeAppendChild self newChild\n = maybeNull (makeNewGObject mkNode)\n (propagateGError $\n \\ errorPtr_ ->\n {# call webkit_dom_node_append_child #} (toNode self)\n (maybe (Node nullForeignPtr) toNode newChild)\n errorPtr_)\n \nnodeHasChildNodes :: (NodeClass self) => self -> IO Bool\nnodeHasChildNodes self\n = toBool <$>\n ({# call webkit_dom_node_has_child_nodes #} (toNode self))\n \nnodeCloneNode ::\n (NodeClass self) => self -> Bool -> IO (Maybe Node)\nnodeCloneNode self deep\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_clone_node #} (toNode self)\n (fromBool deep))\n \nnodeNormalize :: (NodeClass self) => self -> IO ()\nnodeNormalize self\n = {# call webkit_dom_node_normalize #} (toNode self)\n \nnodeIsSupported ::\n (NodeClass self) => self -> String -> String -> IO Bool\nnodeIsSupported self feature version\n = toBool <$>\n (withUTFString version $\n \\ versionPtr ->\n withUTFString feature $\n \\ featurePtr ->\n {# call webkit_dom_node_is_supported #} (toNode self) featurePtr\n versionPtr)\n \nnodeHasAttributes :: (NodeClass self) => self -> IO Bool\nnodeHasAttributes self\n = toBool <$>\n ({# call webkit_dom_node_has_attributes #} (toNode self))\n \nnodeIsSameNode ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Bool\nnodeIsSameNode self other\n = toBool <$>\n ({# call webkit_dom_node_is_same_node #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeIsEqualNode ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Bool\nnodeIsEqualNode self other\n = toBool <$>\n ({# call webkit_dom_node_is_equal_node #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeLookupPrefix :: (NodeClass self) => self -> String -> IO String\nnodeLookupPrefix self namespaceURI\n = (withUTFString namespaceURI $\n \\ namespaceURIPtr ->\n {# call webkit_dom_node_lookup_prefix #} (toNode self)\n namespaceURIPtr)\n >>=\n readUTFString\n \nnodeIsDefaultNamespace ::\n (NodeClass self) => self -> String -> IO Bool\nnodeIsDefaultNamespace self namespaceURI\n = toBool <$>\n (withUTFString namespaceURI $\n \\ namespaceURIPtr ->\n {# call webkit_dom_node_is_default_namespace #} (toNode self)\n namespaceURIPtr)\n \nnodeLookupNamespaceURI ::\n (NodeClass self) => self -> String -> IO String\nnodeLookupNamespaceURI self prefix\n = (withUTFString prefix $\n \\ prefixPtr ->\n {# call webkit_dom_node_lookup_namespace_uri #} (toNode self)\n prefixPtr)\n >>=\n readUTFString\n \nnodeCompareDocumentPosition ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Word\nnodeCompareDocumentPosition self other\n = fromIntegral <$>\n ({# call webkit_dom_node_compare_document_position #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeContains ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Bool\nnodeContains self other\n = toBool <$>\n ({# call webkit_dom_node_contains #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeDispatchEvent ::\n (NodeClass self, EventClass event) =>\n self -> Maybe event -> IO Bool\nnodeDispatchEvent self event\n = toBool <$>\n (propagateGError $\n \\ errorPtr_ ->\n {# call webkit_dom_node_dispatch_event #} (toNode self)\n (maybe (Event nullForeignPtr) toEvent event)\n errorPtr_)\ncELEMENT_NODE = 1\ncATTRIBUTE_NODE = 2\ncTEXT_NODE = 3\ncCDATA_SECTION_NODE = 4\ncENTITY_REFERENCE_NODE = 5\ncENTITY_NODE = 6\ncPROCESSING_INSTRUCTION_NODE = 7\ncCOMMENT_NODE = 8\ncDOCUMENT_NODE = 9\ncDOCUMENT_TYPE_NODE = 10\ncDOCUMENT_FRAGMENT_NODE = 11\ncNOTATION_NODE = 12\ncDOCUMENT_POSITION_DISCONNECTED = 1\ncDOCUMENT_POSITION_PRECEDING = 2\ncDOCUMENT_POSITION_FOLLOWING = 4\ncDOCUMENT_POSITION_CONTAINS = 8\ncDOCUMENT_POSITION_CONTAINED_BY = 16\ncDOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32\n \nnodeGetNodeName :: (NodeClass self) => self -> IO String\nnodeGetNodeName self\n = ({# call webkit_dom_node_get_node_name #} (toNode self)) >>=\n readUTFString\n \nnodeSetNodeValue :: (NodeClass self) => self -> String -> IO ()\nnodeSetNodeValue self val\n = propagateGError $\n \\ errorPtr_ ->\n withUTFString val $\n \\ valPtr ->\n {# call webkit_dom_node_set_node_value #} (toNode self) valPtr\n errorPtr_\n \nnodeGetNodeValue :: (NodeClass self) => self -> IO String\nnodeGetNodeValue self\n = ({# call webkit_dom_node_get_node_value #} (toNode self)) >>=\n readUTFString\n \nnodeGetNodeType :: (NodeClass self) => self -> IO Word\nnodeGetNodeType self\n = fromIntegral <$>\n ({# call webkit_dom_node_get_node_type #} (toNode self))\n \nnodeGetParentNode :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetParentNode self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_parent_node #} (toNode self))\n \nnodeGetChildNodes ::\n (NodeClass self) => self -> IO (Maybe NodeList)\nnodeGetChildNodes self\n = maybeNull (makeNewGObject mkNodeList)\n ({# call webkit_dom_node_get_child_nodes #} (toNode self))\n \nnodeGetFirstChild :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetFirstChild self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_first_child #} (toNode self))\n \nnodeGetLastChild :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetLastChild self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_last_child #} (toNode self))\n \nnodeGetPreviousSibling ::\n (NodeClass self) => self -> IO (Maybe Node)\nnodeGetPreviousSibling self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_previous_sibling #} (toNode self))\n \nnodeGetNextSibling :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetNextSibling self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_next_sibling #} (toNode self))\n \nnodeGetAttributes ::\n (NodeClass self) => self -> IO (Maybe NamedNodeMap)\nnodeGetAttributes self\n = maybeNull (makeNewGObject mkNamedNodeMap)\n ({# call webkit_dom_node_get_attributes #} (toNode self))\n \nnodeGetOwnerDocument ::\n (NodeClass self) => self -> IO (Maybe Document)\nnodeGetOwnerDocument self\n = maybeNull (makeNewGObject mkDocument)\n ({# call webkit_dom_node_get_owner_document #} (toNode self))\n \nnodeGetNamespaceURI :: (NodeClass self) => self -> IO String\nnodeGetNamespaceURI self\n = ({# call webkit_dom_node_get_namespace_uri #} (toNode self)) >>=\n readUTFString\n \nnodeSetPrefix :: (NodeClass self) => self -> String -> IO ()\nnodeSetPrefix self val\n = propagateGError $\n \\ errorPtr_ ->\n withUTFString val $\n \\ valPtr ->\n {# call webkit_dom_node_set_prefix #} (toNode self) valPtr\n errorPtr_\n \nnodeGetPrefix :: (NodeClass self) => self -> IO String\nnodeGetPrefix self\n = ({# call webkit_dom_node_get_prefix #} (toNode self)) >>=\n readUTFString\n \nnodeGetLocalName :: (NodeClass self) => self -> IO String\nnodeGetLocalName self\n = ({# call webkit_dom_node_get_local_name #} (toNode self)) >>=\n readUTFString\n \nnodeGetBaseURI :: (NodeClass self) => self -> IO String\nnodeGetBaseURI self\n = ({# call webkit_dom_node_get_base_uri #} (toNode self)) >>=\n readUTFString\n \nnodeSetTextContent :: (NodeClass self) => self -> String -> IO ()\nnodeSetTextContent self val\n = propagateGError $\n \\ errorPtr_ ->\n withUTFString val $\n \\ valPtr ->\n {# call webkit_dom_node_set_text_content #} (toNode self) valPtr\n errorPtr_\n \nnodeGetTextContent :: (NodeClass self) => self -> IO String\nnodeGetTextContent self\n = ({# call webkit_dom_node_get_text_content #} (toNode self)) >>=\n readUTFString\n \nnodeGetParentElement ::\n (NodeClass self) => self -> IO (Maybe Element)\nnodeGetParentElement self\n = maybeNull (makeNewGObject mkElement)\n ({# call webkit_dom_node_get_parent_element #} (toNode self))\n","old_contents":"module Graphics.UI.Gtk.WebKit.DOM.Node\n (nodeHasChildNodes, nodeCloneNode, nodeNormalize, nodeIsSupported,\n nodeHasAttributes, nodeIsSameNode, nodeIsEqualNode,\n nodeLookupPrefix, nodeIsDefaultNamespace, nodeLookupNamespaceURI,\n nodeCompareDocumentPosition, nodeContains, nodeDispatchEvent,\n cELEMENT_NODE, cATTRIBUTE_NODE, cTEXT_NODE, cCDATA_SECTION_NODE,\n cENTITY_REFERENCE_NODE, cENTITY_NODE, cPROCESSING_INSTRUCTION_NODE,\n cCOMMENT_NODE, cDOCUMENT_NODE, cDOCUMENT_TYPE_NODE,\n cDOCUMENT_FRAGMENT_NODE, cNOTATION_NODE,\n cDOCUMENT_POSITION_DISCONNECTED, cDOCUMENT_POSITION_PRECEDING,\n cDOCUMENT_POSITION_FOLLOWING, cDOCUMENT_POSITION_CONTAINS,\n cDOCUMENT_POSITION_CONTAINED_BY,\n cDOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, nodeGetNodeName,\n nodeSetNodeValue, nodeGetNodeValue, nodeGetNodeType,\n nodeGetParentNode, nodeGetChildNodes, nodeGetFirstChild,\n nodeGetLastChild, nodeGetPreviousSibling, nodeGetNextSibling,\n nodeGetAttributes, nodeGetOwnerDocument, nodeGetNamespaceURI,\n nodeSetPrefix, nodeGetPrefix, nodeGetLocalName, nodeGetBaseURI,\n nodeSetTextContent, nodeGetTextContent, nodeGetParentElement)\n where\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Graphics.UI.Gtk.WebKit.DOM.EventM\n \nnodeHasChildNodes :: (NodeClass self) => self -> IO Bool\nnodeHasChildNodes self\n = toBool <$>\n ({# call webkit_dom_node_has_child_nodes #} (toNode self))\n \nnodeCloneNode ::\n (NodeClass self) => self -> Bool -> IO (Maybe Node)\nnodeCloneNode self deep\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_clone_node #} (toNode self)\n (fromBool deep))\n \nnodeNormalize :: (NodeClass self) => self -> IO ()\nnodeNormalize self\n = {# call webkit_dom_node_normalize #} (toNode self)\n \nnodeIsSupported ::\n (NodeClass self) => self -> String -> String -> IO Bool\nnodeIsSupported self feature version\n = toBool <$>\n (withUTFString version $\n \\ versionPtr ->\n withUTFString feature $\n \\ featurePtr ->\n {# call webkit_dom_node_is_supported #} (toNode self) featurePtr\n versionPtr)\n \nnodeHasAttributes :: (NodeClass self) => self -> IO Bool\nnodeHasAttributes self\n = toBool <$>\n ({# call webkit_dom_node_has_attributes #} (toNode self))\n \nnodeIsSameNode ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Bool\nnodeIsSameNode self other\n = toBool <$>\n ({# call webkit_dom_node_is_same_node #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeIsEqualNode ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Bool\nnodeIsEqualNode self other\n = toBool <$>\n ({# call webkit_dom_node_is_equal_node #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeLookupPrefix :: (NodeClass self) => self -> String -> IO String\nnodeLookupPrefix self namespaceURI\n = (withUTFString namespaceURI $\n \\ namespaceURIPtr ->\n {# call webkit_dom_node_lookup_prefix #} (toNode self)\n namespaceURIPtr)\n >>=\n readUTFString\n \nnodeIsDefaultNamespace ::\n (NodeClass self) => self -> String -> IO Bool\nnodeIsDefaultNamespace self namespaceURI\n = toBool <$>\n (withUTFString namespaceURI $\n \\ namespaceURIPtr ->\n {# call webkit_dom_node_is_default_namespace #} (toNode self)\n namespaceURIPtr)\n \nnodeLookupNamespaceURI ::\n (NodeClass self) => self -> String -> IO String\nnodeLookupNamespaceURI self prefix\n = (withUTFString prefix $\n \\ prefixPtr ->\n {# call webkit_dom_node_lookup_namespace_uri #} (toNode self)\n prefixPtr)\n >>=\n readUTFString\n \nnodeCompareDocumentPosition ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Word\nnodeCompareDocumentPosition self other\n = fromIntegral <$>\n ({# call webkit_dom_node_compare_document_position #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeContains ::\n (NodeClass self, NodeClass other) => self -> Maybe other -> IO Bool\nnodeContains self other\n = toBool <$>\n ({# call webkit_dom_node_contains #} (toNode self)\n (maybe (Node nullForeignPtr) toNode other))\n \nnodeDispatchEvent ::\n (NodeClass self, EventClass event) =>\n self -> Maybe event -> IO Bool\nnodeDispatchEvent self event\n = toBool <$>\n (propagateGError $\n \\ errorPtr_ ->\n {# call webkit_dom_node_dispatch_event #} (toNode self)\n (maybe (Event nullForeignPtr) toEvent event)\n errorPtr_)\ncELEMENT_NODE = 1\ncATTRIBUTE_NODE = 2\ncTEXT_NODE = 3\ncCDATA_SECTION_NODE = 4\ncENTITY_REFERENCE_NODE = 5\ncENTITY_NODE = 6\ncPROCESSING_INSTRUCTION_NODE = 7\ncCOMMENT_NODE = 8\ncDOCUMENT_NODE = 9\ncDOCUMENT_TYPE_NODE = 10\ncDOCUMENT_FRAGMENT_NODE = 11\ncNOTATION_NODE = 12\ncDOCUMENT_POSITION_DISCONNECTED = 1\ncDOCUMENT_POSITION_PRECEDING = 2\ncDOCUMENT_POSITION_FOLLOWING = 4\ncDOCUMENT_POSITION_CONTAINS = 8\ncDOCUMENT_POSITION_CONTAINED_BY = 16\ncDOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32\n \nnodeGetNodeName :: (NodeClass self) => self -> IO String\nnodeGetNodeName self\n = ({# call webkit_dom_node_get_node_name #} (toNode self)) >>=\n readUTFString\n \nnodeSetNodeValue :: (NodeClass self) => self -> String -> IO ()\nnodeSetNodeValue self val\n = propagateGError $\n \\ errorPtr_ ->\n withUTFString val $\n \\ valPtr ->\n {# call webkit_dom_node_set_node_value #} (toNode self) valPtr\n errorPtr_\n \nnodeGetNodeValue :: (NodeClass self) => self -> IO String\nnodeGetNodeValue self\n = ({# call webkit_dom_node_get_node_value #} (toNode self)) >>=\n readUTFString\n \nnodeGetNodeType :: (NodeClass self) => self -> IO Word\nnodeGetNodeType self\n = fromIntegral <$>\n ({# call webkit_dom_node_get_node_type #} (toNode self))\n \nnodeGetParentNode :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetParentNode self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_parent_node #} (toNode self))\n \nnodeGetChildNodes ::\n (NodeClass self) => self -> IO (Maybe NodeList)\nnodeGetChildNodes self\n = maybeNull (makeNewGObject mkNodeList)\n ({# call webkit_dom_node_get_child_nodes #} (toNode self))\n \nnodeGetFirstChild :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetFirstChild self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_first_child #} (toNode self))\n \nnodeGetLastChild :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetLastChild self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_last_child #} (toNode self))\n \nnodeGetPreviousSibling ::\n (NodeClass self) => self -> IO (Maybe Node)\nnodeGetPreviousSibling self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_previous_sibling #} (toNode self))\n \nnodeGetNextSibling :: (NodeClass self) => self -> IO (Maybe Node)\nnodeGetNextSibling self\n = maybeNull (makeNewGObject mkNode)\n ({# call webkit_dom_node_get_next_sibling #} (toNode self))\n \nnodeGetAttributes ::\n (NodeClass self) => self -> IO (Maybe NamedNodeMap)\nnodeGetAttributes self\n = maybeNull (makeNewGObject mkNamedNodeMap)\n ({# call webkit_dom_node_get_attributes #} (toNode self))\n \nnodeGetOwnerDocument ::\n (NodeClass self) => self -> IO (Maybe Document)\nnodeGetOwnerDocument self\n = maybeNull (makeNewGObject mkDocument)\n ({# call webkit_dom_node_get_owner_document #} (toNode self))\n \nnodeGetNamespaceURI :: (NodeClass self) => self -> IO String\nnodeGetNamespaceURI self\n = ({# call webkit_dom_node_get_namespace_uri #} (toNode self)) >>=\n readUTFString\n \nnodeSetPrefix :: (NodeClass self) => self -> String -> IO ()\nnodeSetPrefix self val\n = propagateGError $\n \\ errorPtr_ ->\n withUTFString val $\n \\ valPtr ->\n {# call webkit_dom_node_set_prefix #} (toNode self) valPtr\n errorPtr_\n \nnodeGetPrefix :: (NodeClass self) => self -> IO String\nnodeGetPrefix self\n = ({# call webkit_dom_node_get_prefix #} (toNode self)) >>=\n readUTFString\n \nnodeGetLocalName :: (NodeClass self) => self -> IO String\nnodeGetLocalName self\n = ({# call webkit_dom_node_get_local_name #} (toNode self)) >>=\n readUTFString\n \nnodeGetBaseURI :: (NodeClass self) => self -> IO String\nnodeGetBaseURI self\n = ({# call webkit_dom_node_get_base_uri #} (toNode self)) >>=\n readUTFString\n \nnodeSetTextContent :: (NodeClass self) => self -> String -> IO ()\nnodeSetTextContent self val\n = propagateGError $\n \\ errorPtr_ ->\n withUTFString val $\n \\ valPtr ->\n {# call webkit_dom_node_set_text_content #} (toNode self) valPtr\n errorPtr_\n \nnodeGetTextContent :: (NodeClass self) => self -> IO String\nnodeGetTextContent self\n = ({# call webkit_dom_node_get_text_content #} (toNode self)) >>=\n readUTFString\n \nnodeGetParentElement ::\n (NodeClass self) => self -> IO (Maybe Element)\nnodeGetParentElement self\n = maybeNull (makeNewGObject mkElement)\n ({# call webkit_dom_node_get_parent_element #} (toNode self))\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"67854d075f6f177f37c0402ae5caf1ebfc01e645","subject":"Fix egregious memory unsafety.","message":"Fix egregious memory unsafety.\n","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 ,\tdynamicReOrdering\n ,\tvarIndices\n ,\tbddSize\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\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 )\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\ncFromEnum :: (Integral i, Enum e) => e -> i\ncFromEnum = fromIntegral . fromEnum\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\nwithBDD :: BDD -> (Ptr BDD -> IO a) -> IO a\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 groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_DEFAULT) >> 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 = bddConstant {#call unsafe Cudd_ReadOne as _cudd_ReadOne#}\n false = bddConstant {#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\nbddConstant :: (DDManager -> IO (Ptr BDD)) -> BDD\nbddConstant f = unsafePerformIO $ f ddmanager >>= addBDDnullFinalizer\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\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 data Subst BDD = MkSubst [(BDD, BDD)]\n\n mkSubst = MkSubst\n rename = cudd_rename\n substitute = error \"CUDD substitute\" -- cudd_substitute\n\ninstance BDDOps BDD where\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\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\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\n-- | FIXME: This function is a bit touchier than you'd hope.\n-- The reaons is we use cudd_bddSwapVariables, which in fact swaps variables.\n-- This is not exactly a \"rename\" behaviour.\ncudd_rename :: Subst BDD -> BDD -> BDD\ncudd_rename (MkSubst subst) f = unsafePerformIO $\n withBDD f $ \\fp ->\n allocaArray len $ \\arrayx -> allocaArray len $ \\arrayx' ->\n do zipWithM_ (pokeSubst arrayx arrayx') subst [0..]\n bddp <- {#call unsafe cudd_bddSwapVariables#} ddmanager fp arrayx arrayx' (fromIntegral len)\n mapM_ (\\ (BDD v, BDD v') -> do touchForeignPtr v\n touchForeignPtr v') subst\n addBDDfinalizer bddp\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\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-- FIXME add an off switch\n----------------------------------------\n\n{#enum Cudd_ReorderingType as CUDDReorderingMethod {} deriving (Eq, Ord, Show)#}\n\nroMap :: [(ReorderingMethod, CUDDReorderingMethod)]\nroMap = [(ReorderSift, CUDD_REORDER_SIFT),\n (ReorderStableWindow3, CUDD_REORDER_WINDOW3)]\n\n-- | Set the dynamic variable ordering heuristic.\ndynamicReOrdering :: ReorderingMethod -> IO ()\ndynamicReOrdering rom =\n case lookup rom roMap of\n Nothing -> error $ \"CUDD.dynamicReOrdering: method not supported: \" ++ show rom\n Just brom ->\n {#call unsafe Cudd_AutodynEnable as _cudd_AutodynEnable#} ddmanager (cFromEnum brom) >> 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","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 ,\tdynamicReOrdering\n ,\tvarIndices\n ,\tbddSize\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\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 )\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\ncFromEnum :: (Integral i, Enum e) => e -> i\ncFromEnum = fromIntegral . fromEnum\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\nwithBDD :: BDD -> (Ptr BDD -> IO a) -> IO a\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 groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_DEFAULT) >> 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 = bddConstant {#call unsafe Cudd_ReadOne as _cudd_ReadOne#}\n false = bddConstant {#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\nbddConstant :: (DDManager -> IO (Ptr BDD)) -> BDD\nbddConstant f = unsafePerformIO $ f ddmanager >>= addBDDnullFinalizer\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\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 data Subst BDD = MkSubst [(BDD, BDD)]\n\n mkSubst = MkSubst\n rename = cudd_rename\n substitute = error \"CUDD substitute\" -- cudd_substitute\n\ninstance BDDOps BDD where\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\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\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\n-- | FIXME: This function is a bit touchier than you'd hope.\n-- The reaons is we use cudd_bddSwapVariables, which in fact swaps variables.\n-- This is not exactly a \"rename\" behaviour.\ncudd_rename :: Subst BDD -> BDD -> BDD\ncudd_rename (MkSubst subst) f = unsafePerformIO $\n withBDD f $ \\fp ->\n allocaArray len $ \\arrayx -> allocaArray len $ \\arrayx' ->\n do zipWithM_ (pokeSubst arrayx arrayx') subst [0..]\n bddp <- {#call unsafe cudd_bddSwapVariables#} ddmanager fp arrayx arrayx' (fromIntegral len)\n mapM_ (\\ (BDD v, BDD v') -> do touchForeignPtr v\n touchForeignPtr v') subst\n addBDDfinalizer bddp\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\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 as _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 -- 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-- FIXME add an off switch\n----------------------------------------\n\n{#enum Cudd_ReorderingType as CUDDReorderingMethod {} deriving (Eq, Ord, Show)#}\n\nroMap :: [(ReorderingMethod, CUDDReorderingMethod)]\nroMap = [(ReorderSift, CUDD_REORDER_SIFT),\n (ReorderStableWindow3, CUDD_REORDER_WINDOW3)]\n\n-- | Set the dynamic variable ordering heuristic.\ndynamicReOrdering :: ReorderingMethod -> IO ()\ndynamicReOrdering rom =\n case lookup rom roMap of\n Nothing -> error $ \"CUDD.dynamicReOrdering: method not supported: \" ++ show rom\n Just brom ->\n {#call unsafe Cudd_AutodynEnable as _cudd_AutodynEnable#} ddmanager (cFromEnum brom) >> 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1fd10289057ae9685d6c18cafbcc74265da5b178","subject":"Add function sourceCompletionProviderPopulate","message":"Add function sourceCompletionProviderPopulate\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"5a07f910278190257746b596311fa6adca78736f","subject":"rename enums","message":"rename enums\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..),\n -- * Functions\n clSuccess, wrapPError, wrapCheckSuccess, getCLValue, getDeviceLocalMemType, \n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \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\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CL_SUCCESS\n then return $ Right v\n else return $ Left errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . toEnum . fromIntegral\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . toEnum . fromIntegral\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . toEnum . fromIntegral\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . toEnum . fromIntegral\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CL_EXEC_ERROR\n | otherwise = Just . toEnum . fromIntegral $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes mask = filter (testMask mask . fromIntegral . fromEnum) $ [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..),\n -- * Functions\n clSuccess, wrapPError, wrapCheckSuccess, getCLValue, getDeviceLocalMemType, \n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \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\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n CLBUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n CLCOMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n CLDEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n CLDEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n CLIMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n CLIMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n CLINVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n CLINVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n CLINVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n CLINVALID_BINARY=CL_INVALID_BINARY,\n CLINVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n CLINVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n CLINVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n CLINVALID_CONTEXT=CL_INVALID_CONTEXT,\n CLINVALID_DEVICE=CL_INVALID_DEVICE,\n CLINVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n CLINVALID_EVENT=CL_INVALID_EVENT,\n CLINVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n CLINVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n CLINVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n CLINVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n CLINVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n CLINVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n CLINVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n CLINVALID_KERNEL=CL_INVALID_KERNEL,\n CLINVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n CLINVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n CLINVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n CLINVALID_OPERATION=CL_INVALID_OPERATION,\n CLINVALID_PLATFORM=CL_INVALID_PLATFORM,\n CLINVALID_PROGRAM=CL_INVALID_PROGRAM,\n CLINVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n CLINVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n CLINVALID_SAMPLER=CL_INVALID_SAMPLER,\n CLINVALID_VALUE=CL_INVALID_VALUE,\n CLINVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n CLINVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n CLINVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n CLMAP_FAILURE=CL_MAP_FAILURE,\n CLMEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n CLMEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n CLOUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n CLOUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n CLPROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n CLSUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n* 'CLBUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CLCOMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CLDEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CLDEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CLIMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CLIMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CLINVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CLINVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CLINVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CLINVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CLINVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CLINVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CLINVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CLINVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CLINVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CLINVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CLINVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CLINVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CLINVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CLINVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CLINVALID_HOST_PTR', Returned if host_ptr is NULL and 'CLMEM_USE_HOST_PTR'\nor 'CLMEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CLMEM_COPY_HOST_PTR' or 'CLMEM_USE_HOST_PTR' are not set in flags.\n\n * 'CLINVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CLINVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CLINVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CLINVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CLINVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CLINVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CLINVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CLINVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CLINVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CLINVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CLINVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CLINVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CLINVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CLINVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CLINVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CLINVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CLINVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CLMAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CLMEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CLMEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CLOUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CLPROFILING_INFO_NOT_AVAILABLE', Returned if the 'CLQUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CLSUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CLSUCCESS\n then return $ Right v\n else return $ Left errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CLSUCCESS) . toEnum . fromIntegral\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} deriving( Show ) #}\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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\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\n#c\nenum CLDeviceLocalMemType {\n CLLOCAL=CL_LOCAL, CLGLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {} deriving( Show ) #}\n\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\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\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\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n CLMEM_READ_WRITE=CL_MEM_READ_WRITE,\n CLMEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n CLMEM_READ_ONLY=CL_MEM_READ_ONLY,\n CLMEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n CLMEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n CLMEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n* 'CLMEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CLMEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CLMEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CLMEM_ALLOC_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CLMEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CLMEM_COPY_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually\nexclusive. 'CLMEM_COPY_HOST_PTR' can be used with 'CLMEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . toEnum . fromIntegral\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . toEnum . fromIntegral\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . toEnum . fromIntegral\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CLEXEC_ERROR\n | otherwise = Just . toEnum . fromIntegral $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\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\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\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":"b4a717e153472b413d8b8f02432d1a0a4a46a605","subject":"gstreamer: remove commented function messageParseAsyncStart in Message.chs","message":"gstreamer: remove commented function messageParseAsyncStart in Message.chs\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n \n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n --messageParseAsyncStart\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\n{-\nmessageParseAsyncStart :: Message\n -> Bool\nmessageParseAsyncStart message =\n toBool $ unsafePerformIO $ alloca $ \\newBaseTimePtr ->\n do poke newBaseTimePtr $ fromBool False\n {# call message_parse_async_start #} message newBaseTimePtr\n peek newBaseTimePtr\n-}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"8353c2ad8f33d57f4939902da7c2dcac854ca0ae","subject":"adjust montage to find max image size and to accept montage dimensions larger than image count","message":"adjust montage to find max image size and to accept montage dimensions larger than image count\n","repos":"aleator\/CV,TomMD\/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, 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\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\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 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 -> 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-- | 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 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\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) = 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 return r\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\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\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 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 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 -> 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-- | 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 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\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\ndata CvIOError = CvIOError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\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":"a685bf0cfd31c340d03820e99d234f880318c44a","subject":"Implement pageAddAnnot and pageRemoveAnnot","message":"Implement pageAddAnnot and pageRemoveAnnot\n","repos":"YoEight\/poppler_bak","old_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n--\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n -- pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageAddAnnot,\n pageRemoveAnnot\n -- pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page =\n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\n{- pageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into\n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n-}\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page\n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n\n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page\npageGetIndex page =\n liftM fromIntegral $\n {#call poppler_page_get_index #} (toPage page)\n\n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success\n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n\n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile =\n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded)\n -> IO [PopplerRectangle]\npageFindText page text =\n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n\n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page =\n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n\n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1.\npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'.\npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'.\npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'.\npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'.\npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection =\n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #}\n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs\n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background\n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n\npageAddAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageAddAnnot page annot =\n {# call poppler_page_add_annot #} (toPage page) (toAnnot annot)\n\npageRemoveAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageRemoveAnnot page annot =\n {# call poppler_page_remove_annot #} (toPage page) (toAnnot annot)\n\n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\n{-\npageRenderSelectionToPixbuf :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> Color -- ^ @glyphColor@ color to use for drawing glyphs\n -> Color -- ^ @backgroundColor@ color to use for the selection background\n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor =\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n-}\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n -- pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n -- pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page = \n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\n{- pageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point \n -> Int -- ^ @rotation@ rotate the document by the specified degree \n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into \n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n-}\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page \n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr -> \n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n \n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page \npageGetIndex page =\n liftM fromIntegral $ \n {#call poppler_page_get_index #} (toPage page)\n \n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page = \n alloca $ \\ widthPtr -> \n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success \n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n \n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile = \n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded) \n -> IO [PopplerRectangle]\npageFindText page text = \n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n \n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page = \n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n \n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1. \npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'. \npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'. \npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'. \npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'. \npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection = \n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #} \n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n-- \n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> PopplerRectangle -- ^ @oldSelection@ previous selection \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs \n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background \n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $ \n with selection $ \\ selectionPtr -> \n with oldSelection $ \\ oldSelectionPtr -> \n with glyphColor $ \\ glyphColorPtr -> \n with backgroundColor $ \\ backgroundColorPtr -> \n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n \n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n-- \n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\n{-\npageRenderSelectionToPixbuf :: PageClass page => page \n -> Double -- ^ @scale@ scale specified as pixels per point \n -> Int -- ^ @rotation@ rotate the document by the specified degree \n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to \n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle \n -> PopplerRectangle -- ^ @oldSelection@ previous selection \n -> SelectionStyle -- ^ @style@ a 'SelectionStyle' \n -> Color -- ^ @glyphColor@ color to use for drawing glyphs \n -> Color -- ^ @backgroundColor@ color to use for the selection background \n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor = \n with selection $ \\ selectionPtr -> \n with oldSelection $ \\ oldSelectionPtr -> \n with glyphColor $ \\ glyphColorPtr -> \n with backgroundColor $ \\ backgroundColorPtr -> \n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n-}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f30a3a9e55959a2179445540ac59802ac7cd5694","subject":"[project @ 2003-11-11 12:07:43 by juhp] (sourceTagSetStyle): Fix docu typo.","message":"[project @ 2003-11-11 12:07:43 by juhp]\n(sourceTagSetStyle): Fix docu typo.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","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":"64f028ba362ce20588ad83dcb675f461228ab2af","subject":"add cl_gl.h include","message":"add cl_gl.h include\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/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 __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","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#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":"403fcb72f38f567a1c32de42a807e49bb3c842ff","subject":"Add exception handling to IO action delimited by `begin` and `end`.","message":"Add exception handling to IO action delimited by `begin` and `end`.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Group.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Group.chs","new_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Group\n (\n -- * Constructor\n groupNew,\n groupCustom,\n groupSetCurrent,\n groupCurrent,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Group functions\n --\n -- $groupfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Widget\nimport Control.Exception (finally)\n\n{# fun Fl_Group_set_current as groupSetCurrent' { id `Ptr ()' } -> `()' #}\n{# fun Fl_Group_current as groupCurrent' {} -> `Ptr ()' id #}\n\ngroupSetCurrent :: (Parent a Group) => Maybe (Ref a) -> IO ()\ngroupSetCurrent group = withMaybeRef group $ \\groupPtr -> groupSetCurrent' groupPtr\n\ngroupCurrent :: IO (Maybe (Ref Group))\ngroupCurrent = groupCurrent' >>= toMaybeRef\n\n{# fun Fl_Group_New as groupNew' { `Int',`Int', `Int', `Int'} -> `Ptr ()' id #}\n{# fun Fl_Group_New_WithLabel as groupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text'} -> `Ptr ()' id #}\ngroupNew :: Rectangle -> Maybe T.Text -> IO (Ref Group)\ngroupNew rectangle label' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case label' of\n (Just l') -> groupNewWithLabel' x_pos y_pos width height l' >>= toRef\n Nothing -> groupNew' x_pos y_pos width height >>= toRef\n\n{# fun Fl_OverriddenGroup_New_WithLabel as overriddenGroupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGroup_New as overriddenGroupNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\ngroupCustom :: Rectangle -> Maybe T.Text -> Maybe (Ref Group -> IO ()) -> CustomWidgetFuncs Group -> IO (Ref Group)\ngroupCustom rectangle l' draw' funcs' =\n widgetMaker rectangle l' draw' (Just funcs') overriddenGroupNew' overriddenGroupNewWithLabel'\n\n{# fun Fl_Group_Destroy as groupDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Destroy ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> groupDestroy' groupPtr\n\n\n{# fun Fl_Group_draw_child as drawChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawChild' groupPtr widgetPtr\n\n{# fun Fl_Group_draw_children as drawChildren' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ (IO ())) => Op (DrawChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> drawChildren' groupPtr\n\n{# fun Fl_Group_draw_outside_label as drawOutsideLabel' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawOutsideLabel ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawOutsideLabel' groupPtr widgetPtr\n\n{# fun Fl_Group_update_child as updateChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (UpdateChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> updateChild' groupPtr widgetPtr\n\n{# fun Fl_Group_begin as begin' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Begin ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> begin' groupPtr\n\n{# fun Fl_Group_end as end' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (End ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> end' groupPtr\n\ninstance (\n Match obj ~ FindOp orig orig (Begin ()),\n Match obj ~ FindOp orig orig (End ()),\n Op (Begin ()) obj orig (IO ()),\n Op (End ()) obj orig (IO ()),\n impl ~ (IO () -> IO ())\n ) => Op (Within ()) Group orig impl where\n runOp _ _ group action = do\n () <- begin (castTo group :: Ref orig)\n finally action ((end (castTo group :: Ref orig)) :: IO ())\n\n{# fun Fl_Group_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Find ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> find' groupPtr wPtr\n\n{# fun Fl_Group_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> IO ())) => Op (Add ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> add' groupPtr wPtr\n\n{# fun Fl_Group_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> Int -> IO ())) => Op (Insert ()) Group orig impl where\n runOp _ _ group w i = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> insert' groupPtr wPtr i\n\n{# fun Fl_Group_remove_index as removeIndex' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (RemoveIndex ()) Group orig impl where\n runOp _ _ group index' = withRef group $ \\groupPtr -> removeIndex' groupPtr index'\n\n{# fun Fl_Group_remove_widget as removeWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (RemoveWidget ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> removeWidget' groupPtr wPtr\n\n{# fun Fl_Group_clear as clear' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Clear ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clear' groupPtr\n\n{# fun Fl_Group_set_resizable as setResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Maybe ( Ref a ) -> IO ())) => Op (SetResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withMaybeRef o $ \\oPtr -> setResizable' groupPtr oPtr\n\ninstance (impl ~ IO ()) => Op (SetNotResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> setResizable' groupPtr nullPtr\n\n{# fun Fl_Group_resizable as resizable' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Widget)))) => Op (GetResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> resizable' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_add_resizable as addResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (AddResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withRef o $ \\oPtr -> addResizable' groupPtr oPtr\n\n{# fun Fl_Group_init_sizes as initSizes' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (InitSizes ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> initSizes' groupPtr\n\n{# fun Fl_Group_children as children' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Children ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> children' groupPtr\n\n{# fun Fl_Group_set_clip_children as setClipChildren' { id `Ptr ()', cFromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetClipChildren ()) Group orig impl where\n runOp _ _ group c = withRef group $ \\groupPtr -> setClipChildren' groupPtr c\n\n{# fun Fl_Group_clip_children as clipChildren' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (ClipChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clipChildren' groupPtr\n\n{# fun Fl_Group_focus as focus' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (Focus ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> focus' groupPtr wPtr\n\n{# fun Fl_Group__ddfdesign_kludge as ddfdesignKludge' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Widget)))) => Op (DdfdesignKludge ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> ddfdesignKludge' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_insert_with_before as insertWithBefore' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> Ref b -> IO ())) => Op (InsertWithBefore ()) Group orig impl where\n runOp _ _ self w before = withRef self $ \\selfPtr -> withRef w $ \\wPtr -> withRef before $ \\beforePtr -> insertWithBefore' selfPtr wPtr beforePtr\n\n{# fun Fl_Group_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id#}\ninstance (impl ~ (IO [Ref Widget])) => Op (GetArray ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> do\n childArrayPtr <- array' groupPtr\n numChildren <- children group\n arrayToRefs childArrayPtr numChildren\n\n{# fun Fl_Group_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ninstance (impl ~ (Int -> IO (Maybe (Ref Widget)))) => Op (GetChild ()) Group orig impl where\n runOp _ _ self n = withRef self $ \\selfPtr -> child' selfPtr n >>= toMaybeRef\n\n-- $groupfunctions\n-- @\n-- add:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'IO' ()\n--\n-- addResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- begin :: 'Ref' 'Group' -> 'IO' ()\n--\n-- children :: 'Ref' 'Group' -> 'IO' ('Int')\n--\n-- clear :: 'Ref' 'Group' -> 'IO' ()\n--\n-- clipChildren :: 'Ref' 'Group' -> 'IO' ('Bool')\n--\n-- ddfdesignKludge :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- destroy :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- drawChildren :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawOutsideLabel:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- end :: 'Ref' 'Group' -> 'IO' ()\n--\n-- find:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ('Int')\n--\n-- focus:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- getArray :: 'Ref' 'Group' -> 'IO' ['Ref' 'Widget']\n--\n-- getChild :: 'Ref' 'Group' -> 'Int' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- getResizable :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- initSizes :: 'Ref' 'Group' -> 'IO' ()\n--\n-- insert:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'Int' -> 'IO' ()\n--\n-- insertWithBefore:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'Ref' b -> 'IO' ()\n--\n-- removeIndex :: 'Ref' 'Group' -> 'Int' -> 'IO' ()\n--\n-- removeWidget:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- setClipChildren :: 'Ref' 'Group' -> 'Bool' -> 'IO' ()\n--\n-- setNotResizable :: 'Ref' 'Group' -> 'IO' ()\n--\n-- setResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Maybe' ( 'Ref' a ) -> 'IO' ()\n--\n-- updateChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- @\n","old_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Group\n (\n -- * Constructor\n groupNew,\n groupCustom,\n groupSetCurrent,\n groupCurrent,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Group functions\n --\n -- $groupfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Widget\n\n{# fun Fl_Group_set_current as groupSetCurrent' { id `Ptr ()' } -> `()' #}\n{# fun Fl_Group_current as groupCurrent' {} -> `Ptr ()' id #}\n\ngroupSetCurrent :: (Parent a Group) => Maybe (Ref a) -> IO ()\ngroupSetCurrent group = withMaybeRef group $ \\groupPtr -> groupSetCurrent' groupPtr\n\ngroupCurrent :: IO (Maybe (Ref Group))\ngroupCurrent = groupCurrent' >>= toMaybeRef\n\n{# fun Fl_Group_New as groupNew' { `Int',`Int', `Int', `Int'} -> `Ptr ()' id #}\n{# fun Fl_Group_New_WithLabel as groupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text'} -> `Ptr ()' id #}\ngroupNew :: Rectangle -> Maybe T.Text -> IO (Ref Group)\ngroupNew rectangle label' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case label' of\n (Just l') -> groupNewWithLabel' x_pos y_pos width height l' >>= toRef\n Nothing -> groupNew' x_pos y_pos width height >>= toRef\n\n{# fun Fl_OverriddenGroup_New_WithLabel as overriddenGroupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGroup_New as overriddenGroupNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\ngroupCustom :: Rectangle -> Maybe T.Text -> Maybe (Ref Group -> IO ()) -> CustomWidgetFuncs Group -> IO (Ref Group)\ngroupCustom rectangle l' draw' funcs' =\n widgetMaker rectangle l' draw' (Just funcs') overriddenGroupNew' overriddenGroupNewWithLabel'\n\n{# fun Fl_Group_Destroy as groupDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Destroy ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> groupDestroy' groupPtr\n\n\n{# fun Fl_Group_draw_child as drawChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawChild' groupPtr widgetPtr\n\n{# fun Fl_Group_draw_children as drawChildren' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ (IO ())) => Op (DrawChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> drawChildren' groupPtr\n\n{# fun Fl_Group_draw_outside_label as drawOutsideLabel' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawOutsideLabel ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawOutsideLabel' groupPtr widgetPtr\n\n{# fun Fl_Group_update_child as updateChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (UpdateChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> updateChild' groupPtr widgetPtr\n\n{# fun Fl_Group_begin as begin' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Begin ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> begin' groupPtr\n\n{# fun Fl_Group_end as end' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (End ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> end' groupPtr\n\ninstance (\n Match obj ~ FindOp orig orig (Begin ()),\n Match obj ~ FindOp orig orig (End ()),\n Op (Begin ()) obj orig (IO ()),\n Op (End ()) obj orig (IO ()),\n impl ~ (IO () -> IO ())\n ) => Op (Within ()) Group orig impl where\n runOp _ _ group action = do\n () <- begin (castTo group :: Ref orig)\n action\n end (castTo group :: Ref orig)\n\n{# fun Fl_Group_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Find ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> find' groupPtr wPtr\n\n{# fun Fl_Group_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> IO ())) => Op (Add ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> add' groupPtr wPtr\n\n{# fun Fl_Group_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> Int -> IO ())) => Op (Insert ()) Group orig impl where\n runOp _ _ group w i = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> insert' groupPtr wPtr i\n\n{# fun Fl_Group_remove_index as removeIndex' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (RemoveIndex ()) Group orig impl where\n runOp _ _ group index' = withRef group $ \\groupPtr -> removeIndex' groupPtr index'\n\n{# fun Fl_Group_remove_widget as removeWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (RemoveWidget ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> removeWidget' groupPtr wPtr\n\n{# fun Fl_Group_clear as clear' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Clear ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clear' groupPtr\n\n{# fun Fl_Group_set_resizable as setResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Maybe ( Ref a ) -> IO ())) => Op (SetResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withMaybeRef o $ \\oPtr -> setResizable' groupPtr oPtr\n\ninstance (impl ~ IO ()) => Op (SetNotResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> setResizable' groupPtr nullPtr\n\n{# fun Fl_Group_resizable as resizable' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Widget)))) => Op (GetResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> resizable' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_add_resizable as addResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (AddResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withRef o $ \\oPtr -> addResizable' groupPtr oPtr\n\n{# fun Fl_Group_init_sizes as initSizes' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (InitSizes ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> initSizes' groupPtr\n\n{# fun Fl_Group_children as children' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Children ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> children' groupPtr\n\n{# fun Fl_Group_set_clip_children as setClipChildren' { id `Ptr ()', cFromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetClipChildren ()) Group orig impl where\n runOp _ _ group c = withRef group $ \\groupPtr -> setClipChildren' groupPtr c\n\n{# fun Fl_Group_clip_children as clipChildren' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (ClipChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clipChildren' groupPtr\n\n{# fun Fl_Group_focus as focus' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (Focus ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> focus' groupPtr wPtr\n\n{# fun Fl_Group__ddfdesign_kludge as ddfdesignKludge' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Widget)))) => Op (DdfdesignKludge ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> ddfdesignKludge' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_insert_with_before as insertWithBefore' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> Ref b -> IO ())) => Op (InsertWithBefore ()) Group orig impl where\n runOp _ _ self w before = withRef self $ \\selfPtr -> withRef w $ \\wPtr -> withRef before $ \\beforePtr -> insertWithBefore' selfPtr wPtr beforePtr\n\n{# fun Fl_Group_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id#}\ninstance (impl ~ (IO [Ref Widget])) => Op (GetArray ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> do\n childArrayPtr <- array' groupPtr\n numChildren <- children group\n arrayToRefs childArrayPtr numChildren\n\n{# fun Fl_Group_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ninstance (impl ~ (Int -> IO (Maybe (Ref Widget)))) => Op (GetChild ()) Group orig impl where\n runOp _ _ self n = withRef self $ \\selfPtr -> child' selfPtr n >>= toMaybeRef\n\n-- $groupfunctions\n-- @\n-- add:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'IO' ()\n--\n-- addResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- begin :: 'Ref' 'Group' -> 'IO' ()\n--\n-- children :: 'Ref' 'Group' -> 'IO' ('Int')\n--\n-- clear :: 'Ref' 'Group' -> 'IO' ()\n--\n-- clipChildren :: 'Ref' 'Group' -> 'IO' ('Bool')\n--\n-- ddfdesignKludge :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- destroy :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- drawChildren :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawOutsideLabel:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- end :: 'Ref' 'Group' -> 'IO' ()\n--\n-- find:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ('Int')\n--\n-- focus:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- getArray :: 'Ref' 'Group' -> 'IO' ['Ref' 'Widget']\n--\n-- getChild :: 'Ref' 'Group' -> 'Int' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- getResizable :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- initSizes :: 'Ref' 'Group' -> 'IO' ()\n--\n-- insert:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'Int' -> 'IO' ()\n--\n-- insertWithBefore:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'Ref' b -> 'IO' ()\n--\n-- removeIndex :: 'Ref' 'Group' -> 'Int' -> 'IO' ()\n--\n-- removeWidget:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- setClipChildren :: 'Ref' 'Group' -> 'Bool' -> 'IO' ()\n--\n-- setNotResizable :: 'Ref' 'Group' -> 'IO' ()\n--\n-- setResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Maybe' ( 'Ref' a ) -> 'IO' ()\n--\n-- updateChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"6f9eec7060303caedb0f342141ae5bcd7749d8fd","subject":"GStreamer.Core.Parse: initialize GError with NULL","message":"GStreamer.Core.Parse: initialize GError with NULL\n\nWhen passing a GError to a parse* function, it is important to set its\ncontents to NULL. GStreamer has assertions of the form\n\n g_return_val_if_fail (error == NULL || *error == NULL, NULL);\n \nViolating them may lead to a segfault when assertions are enabled.\n\n","repos":"gtk2hs\/gstreamer","old_file":"Media\/Streaming\/GStreamer\/Core\/Parse.chs","new_file":"Media\/Streaming\/GStreamer\/Core\/Parse.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"594d4bb1552edbf096ddfad9e8202c15c35e8ac7","subject":"Misspelling.","message":"Misspelling.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Multiline\/TextView.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Multiline\/TextView.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"c7d68c97551b3d8e2e1319d7402733e0fed412c1","subject":"import wibble","message":"import wibble\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error (\n\n Status(..), CUDAException(..),\n\n cudaError, describe, requireSDK,\n resultIfOk, nothingIfOk\n\n) where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Typeable\nimport Control.Exception\nimport System.IO.Unsafe\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n-- |\n-- Return codes from API functions\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- A specially formatted error message\n--\nrequireSDK :: Double -> String -> IO a\nrequireSDK v s = cudaError (\"'\" ++ s ++ \"' requires at least cuda-\" ++ show v)\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorStringWrapper as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\n{-# INLINE resultIfOk #-}\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status, !result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\n{-# INLINE nothingIfOk #-}\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error (\n\n Status(..), CUDAException(..),\n\n cudaError, describe, requireSDK,\n resultIfOk, nothingIfOk\n\n) where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign hiding ( unsafePerformIO )\nimport Foreign.C\nimport Data.Typeable\nimport Control.Exception\nimport System.IO.Unsafe\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n-- |\n-- Return codes from API functions\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- A specially formatted error message\n--\nrequireSDK :: Double -> String -> IO a\nrequireSDK v s = cudaError (\"'\" ++ s ++ \"' requires at least cuda-\" ++ show v)\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorStringWrapper as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\n{-# INLINE resultIfOk #-}\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status, !result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\n{-# INLINE nothingIfOk #-}\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":"6392e74a5a79a93d25725ffd9981fd7fea628b99","subject":"Fix Andy's compilation problem.","message":"Fix Andy's compilation problem.","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\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":"3390834ce8eeb75557c18c52d2018d8a84416ee5","subject":"Haddoc for Comm","message":"Haddoc for Comm\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Comm.chs","new_file":"src\/Control\/Parallel\/MPI\/Comm.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Comm\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module provides Haskell representation of the @MPI_Comm@ type\n(communicator handle).\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Comm (Comm, commWorld, commSelf) where\n\nimport C2HS\n\n{# context prefix = \"MPI\" #}\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 Comm = {# type MPI_Comm #}\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr Comm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr Comm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = unsafePerformIO $ peek commSelf_\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Comm (Comm, commWorld, commSelf) where\n\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr Comm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr Comm\n\ncommWorld, commSelf :: Comm\ncommWorld = unsafePerformIO $ peek commWorld_\ncommSelf = unsafePerformIO $ peek commSelf_\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"527d237cf1f009730afb05bf7c0aa680b9851f9a","subject":"removed unnecesary NOINLINES","message":"removed unnecesary NOINLINES\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\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\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 , 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ef94002755dd0be9336a3fa30cc5fe64e794d30e","subject":"GLDrawingArea: provide implementation for GObjectClass Without this patch, trying to use a GLDrawingArea results in program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject","message":"GLDrawingArea: provide implementation for GObjectClass\nWithout this patch, trying to use a GLDrawingArea results in\n program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject\n","repos":"vincenthz\/webkit","old_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea where\n toGObject (GLDrawingArea gd) = toGObject gd\n unsafeCastGObject = GLDrawingArea . unsafeCastGObject\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"977042b8fda7d6ed153c39aee9800be5b394ece2","subject":"Add type annotations to fix type errors","message":"Add type annotations to fix type errors\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(..),\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.\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\npeekEngine = liftM Engine . newForeignPtr_\n\npeekAudioPort = liftM AudioPort . newForeignPtr_\n\npeekVideoPort = liftM VideoPort . newForeignPtr_\n\npeekStream = liftM Stream . newForeignPtr_\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'} -> `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 ,fromIntegral `Int'\n ,withData- `Data'} -> `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'} -> `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\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\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.\ntype Mrl = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\nint2bool = (\/= 0)\n\ncint2enum = toEnum . fromIntegral\n\nenum2cint = fromIntegral . fromEnum\n\npeekInt = liftM fromIntegral . peek\n\npeekEngine = liftM Engine . newForeignPtr_\n\npeekAudioPort = liftM AudioPort . newForeignPtr_\n\npeekVideoPort = liftM VideoPort . newForeignPtr_\n\npeekStream = liftM Stream . newForeignPtr_\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'} -> `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 ,fromIntegral `Int'\n ,withData- `Data'} -> `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'} -> `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\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\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":"a7e6358967f1b4db25aae3c6046f252fb37326ee","subject":"Properly support SetColors 3rd arguments as an array of colors","message":"Properly support SetColors 3rd arguments as an array of colors\n","repos":"gtk2hs\/vte,gtk2hs\/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 resizeWindow,\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 -> Color -- ^ @foreground@ - the new foreground color, or @Nothing@ \n -> Color -- ^ @background@ - the new background color, or @Nothing@ \n -> [Color] -- ^ @palette@ - the color palette\n -> IO ()\nterminalSetColors terminal foreground background palette =\n allocaArray nbColors $ \\pPtr ->\n with foreground $ \\fPtr ->\n with background $ \\bPtr -> do\n pokeArray pPtr palette\n {#call terminal_set_colors#}\n (toTerminal terminal)\n (castPtr fPtr)\n (castPtr bPtr)\n (castPtr pPtr)\n (fromIntegral nbColors)\n where nbColors = length palette\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.\nresizeWindow :: TerminalClass self => Signal self (Int -> Int -> IO ())\nresizeWindow = 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 resizeWindow,\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 -> Color -- ^ @foreground@ - the new foreground color, or @Nothing@ \n -> Color -- ^ @background@ - the new background color, or @Nothing@ \n -> Color -- ^ @palette@ - the color palette \n -> Int -- ^ @size@ - the number of entries in palette \n -> IO ()\nterminalSetColors terminal foreground background palette size =\n with foreground $ \\fPtr ->\n with background $ \\bPtr ->\n with palette $ \\pPtr ->\n {#call terminal_set_colors#} \n (toTerminal terminal) \n (castPtr fPtr)\n (castPtr bPtr)\n (castPtr pPtr)\n (fromIntegral size)\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.\nresizeWindow :: TerminalClass self => Signal self (Int -> Int -> IO ())\nresizeWindow = 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":"be4960c6f5aae78dc50f2c9bcac76174d217bde1","subject":"Xine.Foreign: bind XINE_VERBOSITY_*","message":"Xine.Foreign: bind XINE_VERBOSITY_*\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{-# OPTIONS_GHC -Wwarn #-}\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(..), DemuxStrategy(..), Verbosity(..), MRL, EngineParam(..),\n 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-- | 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-- | Stream format detection strategies\n{#enum define DemuxStrategy\n {XINE_DEMUX_DEFAULT_STRATEGY as DemuxDefault,\n XINE_DEMUX_REVERT_STRATEGY as DemuxRevert,\n XINE_DEMUX_CONTENT_STRATEGY as DemuxContent,\n XINE_DEMUX_EXTENSION_STRATEGY as DemuxExtension}#}\n\n-- | Verbosity setting\n{#enum define Verbosity\n {XINE_VERBOSITY_NONE as VerbosityNone,\n XINE_VERBOSITY_LOG as VerbosityLog,\n XINE_VERBOSITY_DEBUG as VerbosityDebug}#}\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-- This is a trick to read the #define'd constant XINE_LANG_MAX\n{#enum define Wrapping\n {XINE_LANG_MAX as LangMax}#}\n\ncXINE_LANG_MAX :: Int\ncXINE_LANG_MAX = fromEnum LangMax\n\n-- Helper to allocate a language buffer\nallocLangBuf = allocaArray0 cXINE_LANG_MAX\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{-# OPTIONS_GHC -Wwarn #-}\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(..), DemuxStrategy(..), MRL, EngineParam(..), Affection(..),\n 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-- | 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-- | Stream format detection strategies\n{#enum define DemuxStrategy\n {XINE_DEMUX_DEFAULT_STRATEGY as DemuxDefault,\n XINE_DEMUX_REVERT_STRATEGY as DemuxRevert,\n XINE_DEMUX_CONTENT_STRATEGY as DemuxContent,\n XINE_DEMUX_EXTENSION_STRATEGY as DemuxExtension}#}\n\n-- XXX: here\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-- This is a trick to read the #define'd constant XINE_LANG_MAX\n{#enum define Wrapping\n {XINE_LANG_MAX as LangMax}#}\n\ncXINE_LANG_MAX :: Int\ncXINE_LANG_MAX = fromEnum LangMax\n\n-- Helper to allocate a language buffer\nallocLangBuf = allocaArray0 cXINE_LANG_MAX\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":"deee932901c07b4f92f64a7e07843cb45518c0f1","subject":"Fix the bug of `iconInfoGetEmbeddedRect`","message":"Fix the bug of `iconInfoGetEmbeddedRect`\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> Rectangle -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates; coordinates are only stored when this function \n -> IO Bool -- ^ returns 'True' if the icon has an embedded rectangle\niconInfoGetEmbeddedRect self rectangle =\n liftM toBool $\n with rectangle $ \\ rectanglePtr -> \n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectanglePtr)\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"288903827008dc12310a1acb872e723334328364","subject":"driver: add support for unified memory","message":"driver: add support for unified memory\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) [2009..2012] 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\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArrayAsync,\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(..))\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#if CUDA_VERSION >= 6000\n#c\ntypedef enum CUmemAttachFlags_option_enum {\n CU_MEM_ATTACH_OPTION_GLOBAL = CU_MEM_ATTACH_GLOBAL,\n CU_MEM_ATTACH_OPTION_HOST = CU_MEM_ATTACH_HOST,\n CU_MEM_ATTACH_OPTION_SINGLE = CU_MEM_ATTACH_SINGLE\n} CUmemAttachFlags_option;\n#endc\n#endif\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\n{# enum CUmemAttachFlags_option as AttachFlag\n { underscoreToCase }\n with prefix=\"CU_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 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-- |\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 unsafe 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 (Stream nullPtr) mst)\n\n{-# INLINE cuMemcpyDtoHAsync #-}\n{# fun unsafe 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 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 = 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 unsafe 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 (Stream nullPtr) mst)\n\n{-# INLINE cuMemcpyHtoDAsync #-}\n{# fun unsafe 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-- 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-- |\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--\n{-# INLINEABLE copyArrayAsync #-}\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{-# INLINE cuMemcpyDtoD #-}\n{# fun unsafe cuMemcpyDtoD\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\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 (Stream nullPtr) 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 (Stream nullPtr) 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 ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) [2009..2012] 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 -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArrayAsync,\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(..))\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-- 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 = 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 unsafe 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 (Stream nullPtr) mst)\n\n{-# INLINE cuMemcpyDtoHAsync #-}\n{# fun unsafe 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 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 = 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 unsafe 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 (Stream nullPtr) mst)\n\n{-# INLINE cuMemcpyHtoDAsync #-}\n{# fun unsafe 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-- 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-- |\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--\n{-# INLINEABLE copyArrayAsync #-}\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{-# INLINE cuMemcpyDtoD #-}\n{# fun unsafe cuMemcpyDtoD\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\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 (Stream nullPtr) 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 (Stream nullPtr) 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":"2c64d6312b6479ac6cb4a942b72047f8c540ba17","subject":"Add Show instances to Enums.","message":"Add Show instances to Enums.\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Enums.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Enums.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Enumerations\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon\n--\n-- Created: 13 Januar 1999\n--\n-- Copyright (C) 1999-2005 Manuel M. T. Chakravarty, 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-- General enumeration types.\n--\nmodule Graphics.UI.Gtk.Gdk.Enums (\n CapStyle(..),\n CrossingMode(..),\n Dither(..),\n DragProtocol(..),\n DragAction(..),\n EventMask(..),\n ExtensionMode(..),\n Fill(..),\n Function(..),\n InputCondition(..),\n JoinStyle(..),\n LineStyle(..),\n NotifyType(..),\n ScrollDirection(..),\n SubwindowMode(..),\n VisibilityState(..),\n WindowState(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n GrabStatus(..),\n ) where\n\nimport System.Glib.Flags\t(Flags)\n\n{#context lib=\"gdk\" prefix =\"gdk\"#}\n\n-- | Specify the how the ends of a line is drawn.\n--\n{#enum CapStyle {underscoreToCase}#}\n\n-- | How focus is crossing the widget.\n--\n{#enum CrossingMode {underscoreToCase} deriving(Show) #}\n\n-- | Used in 'Graphics.UI.Gtk.Gdk.Drag.DragContext' to indicate the protocol according to which DND is done.\n--\n{#enum DragProtocol {underscoreToCase} deriving (Bounded,Show)#}\n\n-- | Specify the kind of action performed on a drag event.\n{#enum DragAction {underscoreToCase} deriving (Bounded,Show)#}\n\ninstance Flags DragAction\n\n-- | Specify how to dither colors onto the screen.\n--\n{#enum RgbDither as Dither {underscoreToCase} deriving(Show) #}\n\n-- | specify which events a widget will emit signals on\n--\n{#enum EventMask {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags EventMask\n\n-- | specify which input extension a widget desires\n--\n{#enum ExtensionMode {underscoreToCase} deriving(Bounded,Show)#}\n\ninstance Flags ExtensionMode\n\n-- | How objects are filled.\n--\n{#enum Fill {underscoreToCase} deriving(Show) #}\n\n-- | Determine how bitmap operations are carried out.\n--\n{#enum Function {underscoreToCase} deriving(Show) #}\n\n-- | Specify on what file condition a callback should be\n-- done.\n--\n{#enum InputCondition {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags InputCondition\n\n-- | Determines how adjacent line ends are drawn.\n--\n{#enum JoinStyle {underscoreToCase}#}\n\n-- | Determines if a line is solid or dashed.\n--\n{#enum LineStyle {underscoreToCase}#}\n\n-- | Information on from what level of the widget hierarchy the mouse\n-- cursor came.\n--\n-- ['NotifyAncestor'] The window is entered from an ancestor or left towards\n-- an ancestor.\n--\n-- ['NotifyVirtual'] The pointer moves between an ancestor and an inferior\n-- of the window.\n--\n-- ['NotifyInferior'] The window is entered from an inferior or left\n-- towards an inferior.\n--\n-- ['NotifyNonlinear'] The window is entered from or left towards a\n-- window which is neither an ancestor nor an inferior.\n--\n-- ['NotifyNonlinearVirtual'] The pointer moves between two windows which\n-- are not ancestors of each other and the window is part of the ancestor\n-- chain between one of these windows and their least common ancestor.\n--\n-- ['NotifyUnknown'] The level change does not fit into any of the other\n-- categories or could not be determined.\n--\n{#enum NotifyType {underscoreToCase} deriving(Show) #}\n\n-- | in which direction was scrolled?\n--\n{#enum ScrollDirection {underscoreToCase} deriving(Show) #}\n\n-- | Determine if child widget may be overdrawn.\n--\n{#enum SubwindowMode {underscoreToCase} deriving(Show) #}\n\n-- | visibility of a window\n--\n{#enum VisibilityState {underscoreToCase,\n\t\t\tVISIBILITY_PARTIAL as VisibilityPartialObscured}\n\t\t\t deriving(Show) #}\n\n-- | The state a @DrawWindow@ is in.\n--\n{#enum WindowState {underscoreToCase} deriving (Bounded,Show)#}\n\ninstance Flags WindowState\n\n-- | Determines a window edge or corner.\n--\n{#enum WindowEdge {underscoreToCase} deriving(Show) #}\n\n-- | These are hints for the window manager that indicate what type of function\n-- the window has. The window manager can use this when determining decoration\n-- and behaviour of the window. The hint must be set before mapping the window.\n--\n-- See the extended window manager hints specification for more details about\n-- window types.\n--\n{#enum WindowTypeHint {underscoreToCase} #}\n\n-- | Defines the reference point of a window and the meaning of coordinates\n-- passed to 'Graphics.UI.Gtk.Windows.Window.windowMove'. See\n-- 'Graphics.UI.Gtk.Windows.Window.windowMove' and the \"implementation notes\"\n-- section of the extended window manager hints specification for more details.\n--\n{#enum Gravity {underscoreToCase} deriving(Show) #}\n\n-- | Returned by 'pointerGrab' and 'keyboardGrab' to indicate success or the\n-- reason for the failure of the grab attempt.\n--\n-- [@GrabSuccess@] the resource was successfully grabbed.\n--\n-- [@GrabAlreadyGrabbed@] the resource is actively grabbed by another client.\n--\n-- [@GrabInvalidTime@] the resource was grabbed more recently than the\n-- specified time.\n--\n-- [@GrabNotViewable@] the grab window or the confine_to window are not\n-- viewable.\n--\n-- [@GrabFrozen@] the resource is frozen by an active grab of another client.\n--\n{#enum GrabStatus {underscoreToCase} deriving(Show) #}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Enumerations\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon\n--\n-- Created: 13 Januar 1999\n--\n-- Copyright (C) 1999-2005 Manuel M. T. Chakravarty, 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-- General enumeration types.\n--\nmodule Graphics.UI.Gtk.Gdk.Enums (\n CapStyle(..),\n CrossingMode(..),\n Dither(..),\n DragProtocol(..),\n DragAction(..),\n EventMask(..),\n ExtensionMode(..),\n Fill(..),\n Function(..),\n InputCondition(..),\n JoinStyle(..),\n LineStyle(..),\n NotifyType(..),\n ScrollDirection(..),\n SubwindowMode(..),\n VisibilityState(..),\n WindowState(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n GrabStatus(..),\n ) where\n\nimport System.Glib.Flags\t(Flags)\n\n{#context lib=\"gdk\" prefix =\"gdk\"#}\n\n-- | Specify the how the ends of a line is drawn.\n--\n{#enum CapStyle {underscoreToCase}#}\n\n-- | How focus is crossing the widget.\n--\n{#enum CrossingMode {underscoreToCase}#}\n\n-- | Used in 'Graphics.UI.Gtk.Gdk.Drag.DragContext' to indicate the protocol according to which DND is done.\n--\n{#enum DragProtocol {underscoreToCase} deriving (Bounded)#}\n\n-- | Specify the kind of action performed on a drag event.\n{#enum DragAction {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags DragAction\n\n-- | Specify how to dither colors onto the screen.\n--\n{#enum RgbDither as Dither {underscoreToCase}#}\n\n-- | specify which events a widget will emit signals on\n--\n{#enum EventMask {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags EventMask\n\n-- | specify which input extension a widget desires\n--\n{#enum ExtensionMode {underscoreToCase} deriving(Bounded)#}\n\ninstance Flags ExtensionMode\n\n-- | How objects are filled.\n--\n{#enum Fill {underscoreToCase}#}\n\n-- | Determine how bitmap operations are carried out.\n--\n{#enum Function {underscoreToCase}#}\n\n-- | Specify on what file condition a callback should be\n-- done.\n--\n{#enum InputCondition {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags InputCondition\n\n-- | Determines how adjacent line ends are drawn.\n--\n{#enum JoinStyle {underscoreToCase}#}\n\n-- | Determines if a line is solid or dashed.\n--\n{#enum LineStyle {underscoreToCase}#}\n\n-- | Information on from what level of the widget hierarchy the mouse\n-- cursor came.\n--\n-- ['NotifyAncestor'] The window is entered from an ancestor or left towards\n-- an ancestor.\n--\n-- ['NotifyVirtual'] The pointer moves between an ancestor and an inferior\n-- of the window.\n--\n-- ['NotifyInferior'] The window is entered from an inferior or left\n-- towards an inferior.\n--\n-- ['NotifyNonlinear'] The window is entered from or left towards a\n-- window which is neither an ancestor nor an inferior.\n--\n-- ['NotifyNonlinearVirtual'] The pointer moves between two windows which\n-- are not ancestors of each other and the window is part of the ancestor\n-- chain between one of these windows and their least common ancestor.\n--\n-- ['NotifyUnknown'] The level change does not fit into any of the other\n-- categories or could not be determined.\n--\n{#enum NotifyType {underscoreToCase}#}\n\n-- | in which direction was scrolled?\n--\n{#enum ScrollDirection {underscoreToCase}#}\n\n-- | Determine if child widget may be overdrawn.\n--\n{#enum SubwindowMode {underscoreToCase}#}\n\n-- | visibility of a window\n--\n{#enum VisibilityState {underscoreToCase,\n\t\t\tVISIBILITY_PARTIAL as VisibilityPartialObscured}#}\n\n-- | The state a @DrawWindow@ is in.\n--\n{#enum WindowState {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags WindowState\n\n-- | Determines a window edge or corner.\n--\n{#enum WindowEdge {underscoreToCase} #}\n\n-- | These are hints for the window manager that indicate what type of function\n-- the window has. The window manager can use this when determining decoration\n-- and behaviour of the window. The hint must be set before mapping the window.\n--\n-- See the extended window manager hints specification for more details about\n-- window types.\n--\n{#enum WindowTypeHint {underscoreToCase} #}\n\n-- | Defines the reference point of a window and the meaning of coordinates\n-- passed to 'Graphics.UI.Gtk.Windows.Window.windowMove'. See\n-- 'Graphics.UI.Gtk.Windows.Window.windowMove' and the \"implementation notes\"\n-- section of the extended window manager hints specification for more details.\n--\n{#enum Gravity {underscoreToCase} #}\n\n-- | Returned by 'pointerGrab' and 'keyboardGrab' to indicate success or the\n-- reason for the failure of the grab attempt.\n--\n-- [@GrabSuccess@] the resource was successfully grabbed.\n--\n-- [@GrabAlreadyGrabbed@] the resource is actively grabbed by another client.\n--\n-- [@GrabInvalidTime@] the resource was grabbed more recently than the\n-- specified time.\n--\n-- [@GrabNotViewable@] the grab window or the confine_to window are not\n-- viewable.\n--\n-- [@GrabFrozen@] the resource is frozen by an active grab of another client.\n--\n{#enum GrabStatus {underscoreToCase} #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f761a1b937f1a3fc2eebd723861aa22abc2ece80","subject":"tagVal is superfluous, fromTag should be enough for everyone","message":"tagVal is superfluous, fromTag should be enough for everyone\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@ 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 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*- #}\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 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, tagVal, 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 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*- #}\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":"d44ebdf0bcc1503d5fcae94538ee645d69dde78e","subject":"Add WidgetBase to box hierarchy diagram","message":"Add WidgetBase to box hierarchy diagram\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Box.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Box.chs","new_contents":"{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Box\n (\n -- * Constructor\n boxNew,\n boxNewWithBoxtype,\n boxCustom,\n boxCustomWithBoxtype\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_BoxC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\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\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Base.Widget\n\n{# fun Fl_Box_New as boxNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Box_New_WithLabel as boxNewWithLabel' { `Int',`Int',`Int',`Int',`CString'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenBox_New_WithLabel as overriddenBoxNewWithLabel' { `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenBox_New as overriddenBoxNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_Box_New_WithBoxtype as boxNewWithBoxtype' {cFromEnum `Boxtype', `Int',`Int',`Int',`Int',`CString'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenBox_New_WithBoxtype as overriddenBoxNewWithBoxtype' {cFromEnum `Boxtype', `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n\nboxCustom :: Rectangle -- ^ The bounds of this box\n -> Maybe T.Text -- ^ Optional label\n -> Maybe (Ref Box -> IO ()) -- ^ Optional custom box drawing function\n -> Maybe (CustomWidgetFuncs Box) -- ^ Optional widget overrides\n -> IO (Ref Box)\nboxCustom rectangle l' draw' funcs' =\n widgetMaker\n rectangle\n l'\n draw'\n funcs'\n overriddenBoxNew'\n overriddenBoxNewWithLabel'\n\nboxCustomWithBoxtype :: Boxtype -> Rectangle -> T.Text -> Maybe (Ref Box -> IO ()) -> Maybe (CustomWidgetFuncs Box) -> IO (Ref Box)\nboxCustomWithBoxtype boxtype' rectangle' l' draw' funcs' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle'\n in case funcs' of\n Just fs -> do\n ptr <- customWidgetFunctionStruct draw' fs\n ref <- copyTextToCString l' >>= \\l'' -> overriddenBoxNewWithBoxtype' boxtype' x_pos y_pos width height l'' (castPtr ptr) >>= toRef\n setFlag ref WidgetFlagCopiedLabel\n setFlag ref WidgetFlagCopiedTooltip\n return ref\n Nothing ->\n copyTextToCString l' >>= \\l'' -> boxNewWithBoxtype' boxtype' x_pos y_pos width height l'' >>= toRef\n\n\nboxNew :: Rectangle -> Maybe T.Text -> IO (Ref Box)\nboxNew rectangle l' =\n widgetMaker\n rectangle\n l'\n Nothing\n Nothing\n overriddenBoxNew'\n overriddenBoxNewWithLabel'\n\nboxNewWithBoxtype :: Boxtype -> Rectangle -> T.Text -> IO (Ref Box)\nboxNewWithBoxtype boxtype' rectangle' l' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle'\n in do\n ref <- copyTextToCString l' >>= \\l'' -> boxNewWithBoxtype' boxtype' x_pos y_pos width height l'' >>= toRef\n setFlag ref WidgetFlagCopiedLabel\n setFlag ref WidgetFlagCopiedTooltip\n return ref\n\n{#fun Fl_Box_handle as boxHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) Box orig impl where\n runOp _ _ box event = withRef box (\\p -> boxHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n\n-- $functions\n-- @\n-- handle :: 'Ref' 'Box' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Base.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Box\"\n-- @\n","old_contents":"{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Box\n (\n -- * Constructor\n boxNew,\n boxNewWithBoxtype,\n boxCustom,\n boxCustomWithBoxtype\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_BoxC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\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\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Base.Widget\n\n{# fun Fl_Box_New as boxNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Box_New_WithLabel as boxNewWithLabel' { `Int',`Int',`Int',`Int',`CString'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenBox_New_WithLabel as overriddenBoxNewWithLabel' { `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenBox_New as overriddenBoxNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_Box_New_WithBoxtype as boxNewWithBoxtype' {cFromEnum `Boxtype', `Int',`Int',`Int',`Int',`CString'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenBox_New_WithBoxtype as overriddenBoxNewWithBoxtype' {cFromEnum `Boxtype', `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n\nboxCustom :: Rectangle -- ^ The bounds of this box\n -> Maybe T.Text -- ^ Optional label\n -> Maybe (Ref Box -> IO ()) -- ^ Optional custom box drawing function\n -> Maybe (CustomWidgetFuncs Box) -- ^ Optional widget overrides\n -> IO (Ref Box)\nboxCustom rectangle l' draw' funcs' =\n widgetMaker\n rectangle\n l'\n draw'\n funcs'\n overriddenBoxNew'\n overriddenBoxNewWithLabel'\n\nboxCustomWithBoxtype :: Boxtype -> Rectangle -> T.Text -> Maybe (Ref Box -> IO ()) -> Maybe (CustomWidgetFuncs Box) -> IO (Ref Box)\nboxCustomWithBoxtype boxtype' rectangle' l' draw' funcs' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle'\n in case funcs' of\n Just fs -> do\n ptr <- customWidgetFunctionStruct draw' fs\n ref <- copyTextToCString l' >>= \\l'' -> overriddenBoxNewWithBoxtype' boxtype' x_pos y_pos width height l'' (castPtr ptr) >>= toRef\n setFlag ref WidgetFlagCopiedLabel\n setFlag ref WidgetFlagCopiedTooltip\n return ref\n Nothing ->\n copyTextToCString l' >>= \\l'' -> boxNewWithBoxtype' boxtype' x_pos y_pos width height l'' >>= toRef\n\n\nboxNew :: Rectangle -> Maybe T.Text -> IO (Ref Box)\nboxNew rectangle l' =\n widgetMaker\n rectangle\n l'\n Nothing\n Nothing\n overriddenBoxNew'\n overriddenBoxNewWithLabel'\n\nboxNewWithBoxtype :: Boxtype -> Rectangle -> T.Text -> IO (Ref Box)\nboxNewWithBoxtype boxtype' rectangle' l' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle'\n in do\n ref <- copyTextToCString l' >>= \\l'' -> boxNewWithBoxtype' boxtype' x_pos y_pos width height l'' >>= toRef\n setFlag ref WidgetFlagCopiedLabel\n setFlag ref WidgetFlagCopiedTooltip\n return ref\n\n{#fun Fl_Box_handle as boxHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) Box orig impl where\n runOp _ _ box event = withRef box (\\p -> boxHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n\n-- $functions\n-- @\n-- handle :: 'Ref' 'Box' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Box\"\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"8346db48f0695e2259d5f8563c3f655eb4c2966e","subject":"Misspelling.","message":"Misspelling.\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit","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,\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","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 hand 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,\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":"c55aa9198088198e83060276114fcb8087872734","subject":"Return the open callback function pointer so it can be freed on the Haskell side.","message":"Return the open callback function pointer so it can be freed on the Haskell side.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/X.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/X.chs","new_contents":"{-# LANGUAGE CPP, FlexibleContexts #-}\n\nmodule Graphics.UI.FLTK.LowLevel.X (flcOpenDisplay, flcXid, openCallback) where\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Foreign.Ptr\n#include \"Fl_C.h\"\n#include \"xC.h\"\n\n{# fun flc_open_display as flcOpenDisplay {} -> `()' #}\n\n{# fun flc_xid as flcXid' {`Ptr ()'} -> `Ptr ()' #}\nflcXid :: (Parent a WindowBase) => Ref a -> IO (Maybe WindowHandle)\nflcXid win =\n withRef\n win\n (\n \\winPtr -> do\n res <- flcXid' winPtr\n if (res == nullPtr)\n then return Nothing\n else return (Just (WindowHandle res))\n )\n\n{# fun flc_open_callback as openCallback' { id `FunPtr OpenCallbackPrim' } -> `()' #}\n\nopenCallback :: Maybe OpenCallback -> IO (Maybe (FunPtr OpenCallbackPrim))\nopenCallback Nothing = openCallback' nullFunPtr >> return Nothing\nopenCallback (Just cb) = do\n ptr <- mkOpenCallbackPtr $ \\cstr -> do\n txt <- cStringToText cstr\n cb txt\n openCallback' ptr\n return (Just ptr)\n","old_contents":"{-# LANGUAGE CPP, FlexibleContexts #-}\n\nmodule Graphics.UI.FLTK.LowLevel.X (flcOpenDisplay, flcXid, openCallback) where\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Foreign.Ptr\nimport qualified Data.Text as T\n#include \"Fl_C.h\"\n#include \"xC.h\"\n\n{# fun flc_open_display as flcOpenDisplay {} -> `()' #}\n\n{# fun flc_xid as flcXid' {`Ptr ()'} -> `Ptr ()' #}\nflcXid :: (Parent a WindowBase) => Ref a -> IO (Maybe WindowHandle)\nflcXid win =\n withRef\n win\n (\n \\winPtr -> do\n res <- flcXid' winPtr\n if (res == nullPtr)\n then return Nothing\n else return (Just (WindowHandle res))\n )\n\n{# fun flc_open_callback as openCallback' { id `FunPtr OpenCallbackPrim' } -> `()' #}\n\nopenCallback :: Maybe OpenCallback -> IO ()\nopenCallback Nothing = openCallback' nullFunPtr\nopenCallback (Just cb) = do\n ptr <- mkOpenCallbackPtr $ \\cstr -> do\n txt <- cStringToText cstr\n cb txt\n openCallback' ptr\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"7f8e7215071cfd1de2d463e946a0ef125a43824c","subject":"Fix conflict in Screen, adding the screenGetRGBAColormap function.","message":"Fix conflict in Screen, adding the screenGetRGBAColormap function.\n","repos":"gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Screen.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Screen.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Screen\n--\n-- Author : Duncan Coutts\n--\n-- Created: 29 October 2007\n--\n-- Copyright (C) 2007 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-- Object representing a physical screen\n--\n-- * Module available since Gdk version 2.2\n--\nmodule Graphics.UI.Gtk.Gdk.Screen (\n\n-- * Detail\n--\n-- | 'Screen' objects are the GDK representation of a physical screen. It is\n-- used throughout GDK and Gtk+ to specify which screen the top level windows\n-- are to be displayed on. It is also used to query the screen specification\n-- and default settings such as the default colormap\n-- ('screenGetDefaultColormap'), the screen width ('screenGetWidth'), etc.\n--\n-- Note that a screen may consist of multiple monitors which are merged to\n-- form a large screen area.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----Screen\n-- @\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- * Types\n Screen,\n ScreenClass,\n castToScreen,\n toScreen,\n\n-- * Methods\n screenGetDefault,\n screenGetSystemColormap,\n#if GTK_CHECK_VERSION(2,8,0)\n screenGetRGBAColormap,\n#endif\n#ifndef DISABLE_DEPRECATED\n screenGetDefaultColormap,\n screenSetDefaultColormap,\n#endif\n\n-- screenGetSystemVisual,\n#if GTK_CHECK_VERSION(2,10,0)\n screenIsComposited,\n#endif\n screenGetRootWindow,\n screenGetDisplay,\n screenGetNumber,\n screenGetWidth,\n screenGetHeight,\n screenGetWidthMm,\n screenGetHeightMm,\n screenGetWidthMM,\n screenGetHeightMM,\n screenListVisuals,\n screenGetToplevelWindows,\n screenMakeDisplayName,\n screenGetNMonitors,\n screenGetMonitorGeometry,\n screenGetMonitorAtPoint,\n screenGetMonitorAtWindow,\n#if GTK_CHECK_VERSION(2,14,0)\n screenGetMonitorHeightMm,\n screenGetMonitorWidthMm,\n screenGetMonitorPlugName,\n#endif\n-- screenGetSetting,\n#if GTK_CHECK_VERSION(2,10,0)\n screenGetActiveWindow,\n screenGetWindowStack,\n#endif\n\n-- * Attributes\n screenFontOptions,\n screenResolution,\n screenDefaultColormap,\n\n-- * Signals\n screenSizeChanged,\n#if GTK_CHECK_VERSION(2,10,0)\n screenCompositedChanged,\n#if GTK_CHECK_VERSION(2,14,0)\n screenMonitorsChanged,\n#endif\n#endif\n\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Signals\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.Signals\nimport Graphics.Rendering.Cairo.Types ( FontOptions(..), mkFontOptions, \n withFontOptions)\nimport Graphics.UI.Gtk.General.Structs ( Rectangle(..) )\n\n{# context lib=\"gdk\" prefix=\"gdk\" #}\n\n#if GTK_CHECK_VERSION(2,2,0)\n--------------------\n-- Methods\n\n-- | Gets the default screen for the default display. (See\n-- 'displayGetDefault').\n--\nscreenGetDefault ::\n IO (Maybe Screen) -- ^ returns a 'Screen', or @Nothing@ if there is no\n -- default display.\nscreenGetDefault =\n maybeNull (makeNewGObject mkScreen) $\n {# call gdk_screen_get_default #}\n\nscreenGetDefaultColormap :: Screen\n -> IO Colormap -- ^ returns the default 'Colormap'.\nscreenGetDefaultColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_default_colormap #}\n self\n{-# DEPRECATED screenGetDefaultColormap \"instead of 'screenGetDefaultColormap obj' use 'get obj screenDefaultColormap'\" #-}\n\nscreenSetDefaultColormap :: Screen\n -> Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nscreenSetDefaultColormap self colormap =\n {# call gdk_screen_set_default_colormap #}\n self\n colormap\n{-# DEPRECATED screenSetDefaultColormap \"instead of 'screenSetDefaultColormap obj value' use 'set obj [ screenDefaultColormap := value ]'\" #-}\n\n-- | Gets the system default colormap for @screen@\n--\nscreenGetSystemColormap :: Screen\n -> IO Colormap -- ^ returns the default colormap for @screen@.\nscreenGetSystemColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_system_colormap #}\n self\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Gets a colormap to use for creating windows or pixmaps with an alpha\n-- channel. The windowing system on which Gtk+ is running may not support this\n-- capability, in which case @Nothing@ will be returned. Even if a\n-- non-@Nothing@ value is returned, its possible that the window's alpha\n-- channel won't be honored when displaying the window on the screen: in\n-- particular, for X an appropriate windowing manager and compositing manager\n-- must be running to provide appropriate display.\n--\n-- * Available since Gdk version 2.8\n--\nscreenGetRGBAColormap :: Screen\n -> IO (Maybe Colormap) -- ^ returns a colormap to use for windows with an\n -- alpha channel or @Nothing@ if the capability is not\n -- available.\nscreenGetRGBAColormap self =\n maybeNull (makeNewGObject mkColormap) $\n {# call gdk_screen_get_rgba_colormap #}\n self\n#endif\n\n-- | Get the system's default visual for @screen@. This is the visual for the\n-- root window of the display.\n--\nscreenGetSystemVisual :: Screen\n -> IO Visual -- ^ returns the system visual\nscreenGetSystemVisual self =\n makeNewGObject mkVisual $\n {# call gdk_screen_get_system_visual #}\n self\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns whether windows with an RGBA visual can reasonably be expected to\n-- have their alpha channel drawn correctly on the screen.\n--\n-- On X11 this function returns whether a compositing manager is compositing\n-- @screen@.\n--\n-- * Available since Gdk version 2.10\n--\nscreenIsComposited :: Screen\n -> IO Bool -- ^ returns Whether windows with RGBA visuals can reasonably be\n -- expected to have their alpha channels drawn correctly on the\n -- screen.\nscreenIsComposited self =\n liftM toBool $\n {# call gdk_screen_is_composited #}\n self\n#endif\n\n-- | Gets the root window of @screen@.\n--\nscreenGetRootWindow :: Screen\n -> IO DrawWindow -- ^ returns the root window\nscreenGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gdk_screen_get_root_window #}\n self\n\n-- | Gets the display to which the @screen@ belongs.\n--\nscreenGetDisplay :: Screen\n -> IO Display -- ^ returns the display to which @screen@ belongs\nscreenGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gdk_screen_get_display #}\n self\n\n-- | Gets the index of @screen@ among the screens in the display to which it\n-- belongs. (See 'screenGetDisplay')\n--\nscreenGetNumber :: Screen\n -> IO Int -- ^ returns the index\nscreenGetNumber self =\n liftM fromIntegral $\n {# call gdk_screen_get_number #}\n self\n\n-- | Gets the width of @screen@ in pixels\n--\nscreenGetWidth :: Screen\n -> IO Int -- ^ returns the width of @screen@ in pixels.\nscreenGetWidth self =\n liftM fromIntegral $\n {# call gdk_screen_get_width #}\n self\n\n-- | Gets the height of @screen@ in pixels\n--\nscreenGetHeight :: Screen\n -> IO Int -- ^ returns the height of @screen@ in pixels.\nscreenGetHeight self =\n liftM fromIntegral $\n {# call gdk_screen_get_height #}\n self\n\n-- | Gets the width of @screen@ in millimeters. Note that on some X servers\n-- this value will not be correct.\n--\nscreenGetWidthMM :: Screen\n -> IO Int -- ^ returns the width of @screen@ in millimeters.\nscreenGetWidthMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_width_mm #}\n self\n\nscreenGetWidthMm = screenGetWidthMM\n\n-- | Returns the height of @screen@ in millimeters. Note that on some X\n-- servers this value will not be correct.\n--\nscreenGetHeightMM :: Screen\n -> IO Int -- ^ returns the heigth of @screen@ in millimeters.\nscreenGetHeightMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_height_mm #}\n self\n\nscreenGetHeightMm = screenGetHeightMM\n\n-- | Lists the available visuals for the specified @screen@. A visual\n-- describes a hardware image data format. For example, a visual might support\n-- 24-bit color, or 8-bit color, and might expect pixels to be in a certain\n-- format.\n--\nscreenListVisuals :: Screen\n -> IO [Visual] -- ^ returns a list of visuals\nscreenListVisuals self =\n {# call gdk_screen_list_visuals #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkVisual . return)\n\n\n-- | Obtains a list of all toplevel windows known to GDK on the screen\n-- @screen@. A toplevel window is a child of the root window (see\n-- 'getDefaultRootWindow').\n--\nscreenGetToplevelWindows :: Screen\n -> IO [DrawWindow] -- ^ returns list of toplevel windows\nscreenGetToplevelWindows self =\n {# call gdk_screen_get_toplevel_windows #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkDrawWindow . return)\n\n\n-- | Determines the name to pass to 'displayOpen' to get a 'Display' with this\n-- screen as the default screen.\n--\nscreenMakeDisplayName :: Screen\n -> IO String -- ^ returns a newly allocated string\nscreenMakeDisplayName self =\n {# call gdk_screen_make_display_name #}\n self\n >>= readUTFString\n\n-- | Returns the number of monitors which @screen@ consists of.\n--\nscreenGetNMonitors :: Screen\n -> IO Int -- ^ returns number of monitors which @screen@ consists of.\nscreenGetNMonitors self =\n liftM fromIntegral $\n {# call gdk_screen_get_n_monitors #}\n self\n\n-- | Retrieves the 'Rectangle' representing the size and\n-- position of the individual monitor within the entire screen area.\n--\n-- Note that the size of the entire screen area can be retrieved via\n-- 'screenGetWidth' and 'screenGetHeight'.\n--\nscreenGetMonitorGeometry :: Screen\n -> Int -- ^ @monitorNum@ - the monitor number.\n -> IO Rectangle\nscreenGetMonitorGeometry self monitorNum =\n alloca $ \\rPtr -> do\n {# call gdk_screen_get_monitor_geometry #}\n self\n (fromIntegral monitorNum)\n (castPtr rPtr)\n peek rPtr\n\n-- | Returns the monitor number in which the point (@x@,@y@) is located.\n--\nscreenGetMonitorAtPoint :: Screen\n -> Int -- ^ @x@ - the x coordinate in the virtual screen.\n -> Int -- ^ @y@ - the y coordinate in the virtual screen.\n -> IO Int -- ^ returns the monitor number in which the point (@x@,@y@) lies,\n -- or a monitor close to (@x@,@y@) if the point is not in any\n -- monitor.\nscreenGetMonitorAtPoint self x y =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_point #}\n self\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Returns the number of the monitor in which the largest area of the\n-- bounding rectangle of @window@ resides.\n--\nscreenGetMonitorAtWindow :: Screen\n -> DrawWindow -- ^ @window@ - a 'DrawWindow'\n -> IO Int -- ^ returns the monitor number in which most of @window@ is\n -- located, or if @window@ does not intersect any monitors, a\n -- monitor, close to @window@.\nscreenGetMonitorAtWindow self window =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_window #}\n self\n window\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Gets the height in millimeters of the specified monitor.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorHeightMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the height of the monitor, or -1 if not available\nscreenGetMonitorHeightMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_height_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Gets the width in millimeters of the specified monitor, if available.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorWidthMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the width of the monitor, or -1 if not available\nscreenGetMonitorWidthMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_width_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Returns the output name of the specified monitor. Usually something like\n-- VGA, DVI, or TV, not the actual product name of the display device.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorPlugName :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO (Maybe String) -- ^ returns a newly-allocated string containing the name of the\n -- monitor, or @Nothing@ if the name cannot be determined\nscreenGetMonitorPlugName self monitorNum = do\n sPtr <-\n {# call gdk_screen_get_monitor_plug_name #}\n self\n (fromIntegral monitorNum)\n if sPtr==nullPtr then return Nothing else liftM Just $ readUTFString sPtr\n#endif\n\n{-\n-- | Retrieves a desktop-wide setting such as double-click time for the\n-- 'Screen'@screen@.\n--\n-- FIXME needs a list of valid settings here, or a link to more information.\n--\nscreenGetSetting :: Screen\n -> String -- ^ @name@ - the name of the setting\n -> {-GValue*-} -- ^ @value@ - location to store the value of the setting\n -> IO Bool -- ^ returns @True@ if the setting existed and a value was\n -- stored in @value@, @False@ otherwise.\nscreenGetSetting self name value =\n liftM toBool $\n withUTFString name $ \\namePtr ->\n {# call gdk_screen_get_setting #}\n self\n namePtr\n {-value-}\n-}\n\n-- these are only used for the attributes\nscreenGetFontOptions :: Screen\n -> IO (Maybe FontOptions)\nscreenGetFontOptions self = do\n fPtr <- {# call gdk_screen_get_font_options #} self\n if fPtr==nullPtr then return Nothing else liftM Just $ mkFontOptions (castPtr fPtr)\n\nscreenSetFontOptions :: Screen\n -> Maybe FontOptions\n -> IO ()\nscreenSetFontOptions self Nothing =\n {# call gdk_screen_set_font_options #} self nullPtr\nscreenSetFontOptions self (Just options) =\n withFontOptions options $ \\fPtr ->\n {# call gdk_screen_set_font_options #} self (castPtr fPtr)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the currently active window of this screen.\n--\n-- On X11, this is done by inspecting the _NET_ACTIVE_WINDOW property on the\n-- root window, as described in the Extended Window Manager Hints. If there is\n-- no currently currently active window, or the window manager does not support\n-- the _NET_ACTIVE_WINDOW hint, this function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether\n-- it is implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetActiveWindow :: Screen\n -> IO (Maybe DrawWindow) -- ^ returns the currently active window, or\n -- @Nothing@.\nscreenGetActiveWindow self =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call gdk_screen_get_active_window #}\n self\n#endif\n\n-- | Returns a list of 'DrawWindow's representing the\n-- current window stack.\n--\n-- On X11, this is done by inspecting the _NET_CLIENT_LIST_STACKING property\n-- on the root window, as described in the Extended Window Manager Hints. If\n-- the window manager does not support the _NET_CLIENT_LIST_STACKING hint, this\n-- function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether it is\n-- implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetWindowStack :: Screen\n -> IO (Maybe [DrawWindow]) -- ^ returns a list of 'DrawWindow's for the\n -- current window stack, or @Nothing@.\nscreenGetWindowStack self = do\n lPtr <- {# call gdk_screen_get_window_stack #} self\n if lPtr==nullPtr then return Nothing else liftM Just $ do\n fromGList lPtr >>= mapM (constructNewGObject mkDrawWindow . return)\n#endif\n\n--------------------\n-- Attributes\n\n-- | The default font options for the screen.\n--\nscreenFontOptions :: Attr Screen (Maybe FontOptions)\nscreenFontOptions = newAttr\n screenGetFontOptions\n screenSetFontOptions\n\n-- | The resolution for fonts on the screen.\n--\n-- Default value: -1\n--\nscreenResolution :: Attr Screen Double\nscreenResolution = newAttrFromDoubleProperty \"resolution\"\n\n-- | Sets the default @colormap@ for @screen@.\n--\n-- Gets the default colormap for @screen@.\n--\nscreenDefaultColormap :: Attr Screen Colormap\nscreenDefaultColormap = newAttr\n screenGetDefaultColormap\n screenSetDefaultColormap\n\n--------------------\n-- Signals\n\n-- | The ::size_changed signal is emitted when the pixel width or height of a\n-- screen changes.\n--\nscreenSizeChanged :: ScreenClass self => Signal self (IO ())\nscreenSizeChanged = Signal (connect_NONE__NONE \"size_changed\")\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | The 'screenCompositedChanged' signal is emitted when the composited status of\n-- the screen changes\n--\n-- * Available since Gdk version 2.10\n--\nscreenCompositedChanged :: ScreenClass self => Signal self (IO ())\nscreenCompositedChanged = Signal (connect_NONE__NONE \"composited_changed\")\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | The 'screenMonitorsChanged' signal is emitted when the number, size or\n-- position of the monitors attached to the screen change.\n--\n-- Only for X for now. Future implementations for Win32 and OS X may be a\n-- possibility.\n--\n-- * Available since Gdk version 2.14\n--\nscreenMonitorsChanged :: ScreenClass self => Signal self (IO ())\nscreenMonitorsChanged = Signal (connect_NONE__NONE \"monitors-changed\")\n#endif\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Screen\n--\n-- Author : Duncan Coutts\n--\n-- Created: 29 October 2007\n--\n-- Copyright (C) 2007 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-- Object representing a physical screen\n--\n-- * Module available since Gdk version 2.2\n--\nmodule Graphics.UI.Gtk.Gdk.Screen (\n\n-- * Detail\n--\n-- | 'Screen' objects are the GDK representation of a physical screen. It is\n-- used throughout GDK and Gtk+ to specify which screen the top level windows\n-- are to be displayed on. It is also used to query the screen specification\n-- and default settings such as the default colormap\n-- ('screenGetDefaultColormap'), the screen width ('screenGetWidth'), etc.\n--\n-- Note that a screen may consist of multiple monitors which are merged to\n-- form a large screen area.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----Screen\n-- @\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- * Types\n Screen,\n ScreenClass,\n castToScreen,\n toScreen,\n\n-- * Methods\n screenGetDefault,\n screenGetSystemColormap,\n-- screenGetSystemVisual,\n#if GTK_CHECK_VERSION(2,10,0)\n screenIsComposited,\n#endif\n screenGetRootWindow,\n screenGetDisplay,\n screenGetNumber,\n screenGetWidth,\n screenGetHeight,\n screenGetWidthMm,\n screenGetHeightMm,\n screenGetWidthMM,\n screenGetHeightMM,\n screenListVisuals,\n screenGetToplevelWindows,\n screenMakeDisplayName,\n screenGetNMonitors,\n screenGetMonitorGeometry,\n screenGetMonitorAtPoint,\n screenGetMonitorAtWindow,\n#if GTK_CHECK_VERSION(2,14,0)\n screenGetMonitorHeightMm,\n screenGetMonitorWidthMm,\n screenGetMonitorPlugName,\n#endif\n-- screenGetSetting,\n#if GTK_CHECK_VERSION(2,10,0)\n screenGetActiveWindow,\n screenGetWindowStack,\n#endif\n\n-- * Attributes\n screenFontOptions,\n screenResolution,\n screenDefaultColormap,\n\n-- * Signals\n screenSizeChanged,\n#if GTK_CHECK_VERSION(2,10,0)\n screenCompositedChanged,\n#if GTK_CHECK_VERSION(2,14,0)\n screenMonitorsChanged,\n#endif\n#endif\n\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Signals\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.Signals\nimport Graphics.Rendering.Cairo.Types ( FontOptions(..), mkFontOptions, \n withFontOptions)\nimport Graphics.UI.Gtk.General.Structs ( Rectangle(..) )\n\n{# context lib=\"gdk\" prefix=\"gdk\" #}\n\n#if GTK_CHECK_VERSION(2,2,0)\n--------------------\n-- Methods\n\n-- | Gets the default screen for the default display. (See\n-- 'displayGetDefault').\n--\nscreenGetDefault ::\n IO (Maybe Screen) -- ^ returns a 'Screen', or @Nothing@ if there is no\n -- default display.\nscreenGetDefault =\n maybeNull (makeNewGObject mkScreen) $\n {# call gdk_screen_get_default #}\n\nscreenGetDefaultColormap :: Screen\n -> IO Colormap -- ^ returns the default 'Colormap'.\nscreenGetDefaultColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_default_colormap #}\n self\n{-# DEPRECATED screenGetDefaultColormap \"instead of 'screenGetDefaultColormap obj' use 'get obj screenDefaultColormap'\" #-}\n\nscreenSetDefaultColormap :: Screen\n -> Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nscreenSetDefaultColormap self colormap =\n {# call gdk_screen_set_default_colormap #}\n self\n colormap\n{-# DEPRECATED screenSetDefaultColormap \"instead of 'screenSetDefaultColormap obj value' use 'set obj [ screenDefaultColormap := value ]'\" #-}\n\n-- | Gets the system default colormap for @screen@\n--\nscreenGetSystemColormap :: Screen\n -> IO Colormap -- ^ returns the default colormap for @screen@.\nscreenGetSystemColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_system_colormap #}\n self\n\n-- | Get the system's default visual for @screen@. This is the visual for the\n-- root window of the display.\n--\nscreenGetSystemVisual :: Screen\n -> IO Visual -- ^ returns the system visual\nscreenGetSystemVisual self =\n makeNewGObject mkVisual $\n {# call gdk_screen_get_system_visual #}\n self\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns whether windows with an RGBA visual can reasonably be expected to\n-- have their alpha channel drawn correctly on the screen.\n--\n-- On X11 this function returns whether a compositing manager is compositing\n-- @screen@.\n--\n-- * Available since Gdk version 2.10\n--\nscreenIsComposited :: Screen\n -> IO Bool -- ^ returns Whether windows with RGBA visuals can reasonably be\n -- expected to have their alpha channels drawn correctly on the\n -- screen.\nscreenIsComposited self =\n liftM toBool $\n {# call gdk_screen_is_composited #}\n self\n#endif\n\n-- | Gets the root window of @screen@.\n--\nscreenGetRootWindow :: Screen\n -> IO DrawWindow -- ^ returns the root window\nscreenGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gdk_screen_get_root_window #}\n self\n\n-- | Gets the display to which the @screen@ belongs.\n--\nscreenGetDisplay :: Screen\n -> IO Display -- ^ returns the display to which @screen@ belongs\nscreenGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gdk_screen_get_display #}\n self\n\n-- | Gets the index of @screen@ among the screens in the display to which it\n-- belongs. (See 'screenGetDisplay')\n--\nscreenGetNumber :: Screen\n -> IO Int -- ^ returns the index\nscreenGetNumber self =\n liftM fromIntegral $\n {# call gdk_screen_get_number #}\n self\n\n-- | Gets the width of @screen@ in pixels\n--\nscreenGetWidth :: Screen\n -> IO Int -- ^ returns the width of @screen@ in pixels.\nscreenGetWidth self =\n liftM fromIntegral $\n {# call gdk_screen_get_width #}\n self\n\n-- | Gets the height of @screen@ in pixels\n--\nscreenGetHeight :: Screen\n -> IO Int -- ^ returns the height of @screen@ in pixels.\nscreenGetHeight self =\n liftM fromIntegral $\n {# call gdk_screen_get_height #}\n self\n\n-- | Gets the width of @screen@ in millimeters. Note that on some X servers\n-- this value will not be correct.\n--\nscreenGetWidthMM :: Screen\n -> IO Int -- ^ returns the width of @screen@ in millimeters.\nscreenGetWidthMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_width_mm #}\n self\n\nscreenGetWidthMm = screenGetWidthMM\n\n-- | Returns the height of @screen@ in millimeters. Note that on some X\n-- servers this value will not be correct.\n--\nscreenGetHeightMM :: Screen\n -> IO Int -- ^ returns the heigth of @screen@ in millimeters.\nscreenGetHeightMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_height_mm #}\n self\n\nscreenGetHeightMm = screenGetHeightMM\n\n-- | Lists the available visuals for the specified @screen@. A visual\n-- describes a hardware image data format. For example, a visual might support\n-- 24-bit color, or 8-bit color, and might expect pixels to be in a certain\n-- format.\n--\nscreenListVisuals :: Screen\n -> IO [Visual] -- ^ returns a list of visuals\nscreenListVisuals self =\n {# call gdk_screen_list_visuals #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkVisual . return)\n\n\n-- | Obtains a list of all toplevel windows known to GDK on the screen\n-- @screen@. A toplevel window is a child of the root window (see\n-- 'getDefaultRootWindow').\n--\nscreenGetToplevelWindows :: Screen\n -> IO [DrawWindow] -- ^ returns list of toplevel windows\nscreenGetToplevelWindows self =\n {# call gdk_screen_get_toplevel_windows #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkDrawWindow . return)\n\n\n-- | Determines the name to pass to 'displayOpen' to get a 'Display' with this\n-- screen as the default screen.\n--\nscreenMakeDisplayName :: Screen\n -> IO String -- ^ returns a newly allocated string\nscreenMakeDisplayName self =\n {# call gdk_screen_make_display_name #}\n self\n >>= readUTFString\n\n-- | Returns the number of monitors which @screen@ consists of.\n--\nscreenGetNMonitors :: Screen\n -> IO Int -- ^ returns number of monitors which @screen@ consists of.\nscreenGetNMonitors self =\n liftM fromIntegral $\n {# call gdk_screen_get_n_monitors #}\n self\n\n-- | Retrieves the 'Rectangle' representing the size and\n-- position of the individual monitor within the entire screen area.\n--\n-- Note that the size of the entire screen area can be retrieved via\n-- 'screenGetWidth' and 'screenGetHeight'.\n--\nscreenGetMonitorGeometry :: Screen\n -> Int -- ^ @monitorNum@ - the monitor number.\n -> IO Rectangle\nscreenGetMonitorGeometry self monitorNum =\n alloca $ \\rPtr -> do\n {# call gdk_screen_get_monitor_geometry #}\n self\n (fromIntegral monitorNum)\n (castPtr rPtr)\n peek rPtr\n\n-- | Returns the monitor number in which the point (@x@,@y@) is located.\n--\nscreenGetMonitorAtPoint :: Screen\n -> Int -- ^ @x@ - the x coordinate in the virtual screen.\n -> Int -- ^ @y@ - the y coordinate in the virtual screen.\n -> IO Int -- ^ returns the monitor number in which the point (@x@,@y@) lies,\n -- or a monitor close to (@x@,@y@) if the point is not in any\n -- monitor.\nscreenGetMonitorAtPoint self x y =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_point #}\n self\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Returns the number of the monitor in which the largest area of the\n-- bounding rectangle of @window@ resides.\n--\nscreenGetMonitorAtWindow :: Screen\n -> DrawWindow -- ^ @window@ - a 'DrawWindow'\n -> IO Int -- ^ returns the monitor number in which most of @window@ is\n -- located, or if @window@ does not intersect any monitors, a\n -- monitor, close to @window@.\nscreenGetMonitorAtWindow self window =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_window #}\n self\n window\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Gets the height in millimeters of the specified monitor.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorHeightMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the height of the monitor, or -1 if not available\nscreenGetMonitorHeightMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_height_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Gets the width in millimeters of the specified monitor, if available.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorWidthMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the width of the monitor, or -1 if not available\nscreenGetMonitorWidthMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_width_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Returns the output name of the specified monitor. Usually something like\n-- VGA, DVI, or TV, not the actual product name of the display device.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorPlugName :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO (Maybe String) -- ^ returns a newly-allocated string containing the name of the\n -- monitor, or @Nothing@ if the name cannot be determined\nscreenGetMonitorPlugName self monitorNum = do\n sPtr <-\n {# call gdk_screen_get_monitor_plug_name #}\n self\n (fromIntegral monitorNum)\n if sPtr==nullPtr then return Nothing else liftM Just $ readUTFString sPtr\n#endif\n\n{-\n-- | Retrieves a desktop-wide setting such as double-click time for the\n-- 'Screen'@screen@.\n--\n-- FIXME needs a list of valid settings here, or a link to more information.\n--\nscreenGetSetting :: Screen\n -> String -- ^ @name@ - the name of the setting\n -> {-GValue*-} -- ^ @value@ - location to store the value of the setting\n -> IO Bool -- ^ returns @True@ if the setting existed and a value was\n -- stored in @value@, @False@ otherwise.\nscreenGetSetting self name value =\n liftM toBool $\n withUTFString name $ \\namePtr ->\n {# call gdk_screen_get_setting #}\n self\n namePtr\n {-value-}\n-}\n\n-- these are only used for the attributes\nscreenGetFontOptions :: Screen\n -> IO (Maybe FontOptions)\nscreenGetFontOptions self = do\n fPtr <- {# call gdk_screen_get_font_options #} self\n if fPtr==nullPtr then return Nothing else liftM Just $ mkFontOptions (castPtr fPtr)\n\nscreenSetFontOptions :: Screen\n -> Maybe FontOptions\n -> IO ()\nscreenSetFontOptions self Nothing =\n {# call gdk_screen_set_font_options #} self nullPtr\nscreenSetFontOptions self (Just options) =\n withFontOptions options $ \\fPtr ->\n {# call gdk_screen_set_font_options #} self (castPtr fPtr)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the currently active window of this screen.\n--\n-- On X11, this is done by inspecting the _NET_ACTIVE_WINDOW property on the\n-- root window, as described in the Extended Window Manager Hints. If there is\n-- no currently currently active window, or the window manager does not support\n-- the _NET_ACTIVE_WINDOW hint, this function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether\n-- it is implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetActiveWindow :: Screen\n -> IO (Maybe DrawWindow) -- ^ returns the currently active window, or\n -- @Nothing@.\nscreenGetActiveWindow self =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call gdk_screen_get_active_window #}\n self\n#endif\n\n-- | Returns a list of 'DrawWindow's representing the\n-- current window stack.\n--\n-- On X11, this is done by inspecting the _NET_CLIENT_LIST_STACKING property\n-- on the root window, as described in the Extended Window Manager Hints. If\n-- the window manager does not support the _NET_CLIENT_LIST_STACKING hint, this\n-- function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether it is\n-- implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetWindowStack :: Screen\n -> IO (Maybe [DrawWindow]) -- ^ returns a list of 'DrawWindow's for the\n -- current window stack, or @Nothing@.\nscreenGetWindowStack self = do\n lPtr <- {# call gdk_screen_get_window_stack #} self\n if lPtr==nullPtr then return Nothing else liftM Just $ do\n fromGList lPtr >>= mapM (constructNewGObject mkDrawWindow . return)\n#endif\n\n--------------------\n-- Attributes\n\n-- | The default font options for the screen.\n--\nscreenFontOptions :: Attr Screen (Maybe FontOptions)\nscreenFontOptions = newAttr\n screenGetFontOptions\n screenSetFontOptions\n\n-- | The resolution for fonts on the screen.\n--\n-- Default value: -1\n--\nscreenResolution :: Attr Screen Double\nscreenResolution = newAttrFromDoubleProperty \"resolution\"\n\n-- | Sets the default @colormap@ for @screen@.\n--\n-- Gets the default colormap for @screen@.\n--\nscreenDefaultColormap :: Attr Screen Colormap\nscreenDefaultColormap = newAttr\n screenGetDefaultColormap\n screenSetDefaultColormap\n\n--------------------\n-- Signals\n\n-- | The ::size_changed signal is emitted when the pixel width or height of a\n-- screen changes.\n--\nscreenSizeChanged :: ScreenClass self => Signal self (IO ())\nscreenSizeChanged = Signal (connect_NONE__NONE \"size_changed\")\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | The 'screenCompositedChanged' signal is emitted when the composited status of\n-- the screen changes\n--\n-- * Available since Gdk version 2.10\n--\nscreenCompositedChanged :: ScreenClass self => Signal self (IO ())\nscreenCompositedChanged = Signal (connect_NONE__NONE \"composited_changed\")\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | The 'screenMonitorsChanged' signal is emitted when the number, size or\n-- position of the monitors attached to the screen change.\n--\n-- Only for X for now. Future implementations for Win32 and OS X may be a\n-- possibility.\n--\n-- * Available since Gdk version 2.14\n--\nscreenMonitorsChanged :: ScreenClass self => Signal self (IO ())\nscreenMonitorsChanged = Signal (connect_NONE__NONE \"monitors-changed\")\n#endif\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d8a6a4316104b759e08ebd26298a8ba3f18ee905","subject":"Missing link","message":"Missing link\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and mainGUI then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"8701d6dfa955f815e6b06c1f8ce6a3fa0ca3ab5c","subject":"Must not use _static version of pango_font_description_set_family Since the string buffer is only kept around temporarily, not forever like pango_font_description_set_family_static requires.","message":"Must not use _static version of pango_font_description_set_family\nSince the string buffer is only kept around temporarily, not forever like\npango_font_description_set_family_static requires.\n\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family_static#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"167a6f7db0a968ecd0b1b19904405860a23ef9ab","subject":"Must not use _static version of pango_font_description_set_family","message":"Must not use _static version of pango_font_description_set_family\n\nSince the string buffer is only kept around temporarily, not forever like\npango_font_description_set_family_static requires.\n\ndarcs-hash:20070723145641-adfee-9f8777e0fecb042cd1bc8b7925fe8c8223339d95.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family_static#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"cec7d821e21799b3a5c6e1f700f64bafc3a62a82","subject":"Add nullHostPtr constant for driver API","message":"Add nullHostPtr constant for driver API\n\nIgnore-this: 68c43d4d7b0f07335e29d71b9d0c0300\n\ndarcs-hash:20100218022439-dcabc-6a9f0cb1394ec31206f2009d193f112567c49dc3.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/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, nullHostPtr,\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-- The constant 'nullHostPtr' contains the distinguished memory location that is\n-- not associated with a valid memory location\n--\nnullHostPtr :: HostPtr a\nnullHostPtr = HostPtr nullPtr\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-- 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--------------------------------------------------------------------------------\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, 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c2d0bb92690c231620b0086c0d4410e3fdb8f1d2","subject":"first stab at 1.8 compatibility","message":"first stab at 1.8 compatibility\n","repos":"mwotton\/Hubris-Haskell,mwotton\/Hubris-Haskell,mwotton\/Hubris-Haskell","old_file":"lib\/RubyMap.chs","new_file":"lib\/RubyMap.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n-- {-# LANGUAGE TypeSynonymInstances #-}\n\nmodule RubyMap where\n#include \"rshim.h\"\n#include \n\n-- import Control.Applicative\n-- import Control.Monad\nimport Data.Word\n-- import Foreign.Ptr\nimport Foreign.C.Types\t\nimport Foreign.C.String\n-- import Foreign.Storable\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- import Foreign.Marshal.Array\n\n{# context lib=\"rshim\" #}\n\n{# enum RubyType {} deriving (Eq, Show) #} -- maybe Ord?\n\n#if RUBY_VERSION_CODE >= 187\n#c\nenum ruby_special_consts { \n RUBY_Qfalse = 0,\n RUBY_Qtrue = 2,\n RUBY_Qnil = 4,\n RUBY_Qundef = 6\n};\n#endc\n#endif\n{# enum ruby_special_consts as RubyConsts {} deriving (Eq,Show) #}\ntype Value = CULong -- FIXME, we'd prefer to import the type VALUE directly\nforeign import ccall unsafe \"ruby.h rb_str2cstr\" rb_str2cstr :: Value -> CInt -> CString\nforeign import ccall unsafe \"ruby.h rb_str_new2\" rb_str_new2 :: CString -> Value\nforeign import ccall unsafe \"ruby.h rb_ary_new2\" rb_ary_new2 :: CLong -> IO Value\nforeign import ccall unsafe \"ruby.h rb_ary_push\" rb_ary_push :: Value -> Value -> IO ()\nforeign import ccall unsafe \"ruby.h rb_float_new\" rb_float_new :: Double -> Value\nforeign import ccall unsafe \"ruby.h rb_big2str\" rb_big2str :: Value -> Int -> Value\nforeign import ccall unsafe \"ruby.h rb_str_to_inum\" rb_str_to_inum :: Value -> Int -> Int -> Value\n\n-- we're being a bit filthy here - the interface is all macros, so we're digging in to find what it actually is\nforeign import ccall unsafe \"rshim.h rb_ary_len\" rb_ary_len :: Value -> CUInt\nforeign import ccall unsafe \"rshim.h rtype\" rtype :: Value -> Int\nforeign import ccall unsafe \"rshim.h int2fix\" int2fix :: Int -> Value\nforeign import ccall unsafe \"rshim.h fix2int\" fix2int :: Value -> Int\nforeign import ccall unsafe \"rshim.h num2dbl\" num2dbl :: Value -> Double -- technically CDoubles, but jhc promises they're the same\n\n-- this line crashes jhc\nforeign import ccall unsafe \"intern.h rb_ary_entry\" rb_ary_entry :: Value -> CLong -> IO Value\n\nforeign import ccall safe \"ruby.h rb_raise\" rb_raise :: Value -> CString -> IO ()\nforeign import ccall unsafe \"ruby.h rb_eval_string\" rb_eval_string :: CString -> Value\n\n\n\n\ndata RValue = T_NIL \n | T_FLOAT Double\n | T_STRING String\n\n -- List is non-ideal. Switch to uvector? Array? There's always going\n -- to be an extraction step to pull the RValues out.\n | T_ARRAY [RValue]\n | T_FIXNUM Int \n | T_HASH Int -- definitely FIXME - native ruby hashes, or going to transliterate into Data.Map?\n | T_BIGNUM Integer \n\n -- technically, these are mapping over the types True and False,\n -- I'm going to treat them as values, though.\n | T_TRUE \n | T_FALSE \n\n | T_SYMBOL Word -- interned string\n\n-- These are the other basic Ruby structures that we're not handling yet.\n-- | T_REGEXP \n-- | T_FILE\n-- | T_STRUCT \n-- | T_DATA \n-- | T_OBJECT \n-- | T_CLASS \n-- | T_MODULE \n\ntoRuby :: RValue -> Value\ntoRuby r = case r of\n T_FLOAT d -> rb_float_new d\n -- need to take the address of the cstr, just cast it to a value\n -- sadly no bytestrings yet - unpack it to a list. yeah it's ugly.\n T_STRING str -> rb_str_new2 $ unsafePerformIO $ newCAString str\n T_FIXNUM i -> int2fix i\n\n -- so this is just bizarre - there's no boolean type. True and False have their own types\n -- as well as their own values.\n T_TRUE -> fromIntegral $ fromEnum RUBY_Qtrue\n T_FALSE -> fromIntegral $ fromEnum RUBY_Qfalse\n T_NIL -> fromIntegral $ fromEnum RUBY_Qnil\n T_ARRAY l -> unsafePerformIO $ do\n ary <- rb_ary_new2 $ fromIntegral $ length l\n mapM_ (rb_ary_push ary . toRuby) l\n return ary\n T_BIGNUM b -> rb_str_to_inum (rb_str_new2 $ unsafePerformIO $ newCAString $ show b) 10 1\n _ -> error \"sorry, haven't implemented that yet.\"\n\nfromRuby :: Value -> RValue\nfromRuby v = case target of\n RT_NIL -> T_NIL\n RT_FIXNUM -> T_FIXNUM $ fix2int v\n RT_STRING -> T_STRING $ unsafePerformIO $ peekCString $ rb_str2cstr v 0\n RT_FLOAT -> T_FLOAT $ num2dbl v\n RT_BIGNUM -> T_BIGNUM $ read $ unsafePerformIO $ peekCString $ rb_str2cstr (rb_big2str v 10) 0\n RT_TRUE -> T_TRUE\n RT_FALSE -> T_FALSE\n RT_ARRAY -> T_ARRAY $ map fromRuby $ unsafePerformIO $ mapM (rb_ary_entry v . fromIntegral) [0..(rb_ary_len v) - 1]\n\n _ -> error (show target)\n where target :: RubyType\n target = toEnum $ rtype v\n\n-- utility stuff\n\nthrowException :: String -> IO Value\nthrowException s = do he <- newCAString \"HaskellError\"\n err <- newCAString s\n rb_raise (rb_eval_string he) err\n error \"shouldn't ever get here\"","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n-- {-# LANGUAGE TypeSynonymInstances #-}\n\nmodule RubyMap where\n#include \"rshim.h\"\n#include \n\n-- import Control.Applicative\n-- import Control.Monad\nimport Data.Word\n-- import Foreign.Ptr\nimport Foreign.C.Types\t\nimport Foreign.C.String\n-- import Foreign.Storable\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- import Foreign.Marshal.Array\n\n{# context lib=\"rshim\" #}\n{# enum RubyType {} deriving (Eq, Show) #} -- maybe Ord?\n{# enum ruby_special_consts as RubyConsts {} deriving (Eq,Show) #}\n\ntype Value = CULong -- FIXME, we'd prefer to import the type VALUE directly\nforeign import ccall unsafe \"ruby.h rb_str2cstr\" rb_str2cstr :: Value -> CInt -> CString\nforeign import ccall unsafe \"ruby.h rb_str_new2\" rb_str_new2 :: CString -> Value\nforeign import ccall unsafe \"ruby.h rb_ary_new2\" rb_ary_new2 :: CLong -> IO Value\nforeign import ccall unsafe \"ruby.h rb_ary_push\" rb_ary_push :: Value -> Value -> IO ()\nforeign import ccall unsafe \"ruby.h rb_float_new\" rb_float_new :: Double -> Value\nforeign import ccall unsafe \"ruby.h rb_big2str\" rb_big2str :: Value -> Int -> Value\nforeign import ccall unsafe \"ruby.h rb_str_to_inum\" rb_str_to_inum :: Value -> Int -> Int -> Value\n\n-- we're being a bit filthy here - the interface is all macros, so we're digging in to find what it actually is\nforeign import ccall unsafe \"rshim.h rb_ary_len\" rb_ary_len :: Value -> CUInt\nforeign import ccall unsafe \"rshim.h rtype\" rtype :: Value -> Int\nforeign import ccall unsafe \"rshim.h int2fix\" int2fix :: Int -> Value\nforeign import ccall unsafe \"rshim.h fix2int\" fix2int :: Value -> Int\nforeign import ccall unsafe \"rshim.h num2dbl\" num2dbl :: Value -> Double -- technically CDoubles, but jhc promises they're the same\n\n-- this line crashes jhc\nforeign import ccall unsafe \"intern.h rb_ary_entry\" rb_ary_entry :: Value -> CLong -> IO Value\n\nforeign import ccall safe \"ruby.h rb_raise\" rb_raise :: Value -> CString -> IO ()\nforeign import ccall unsafe \"ruby.h rb_eval_string\" rb_eval_string :: CString -> Value\n\n\n\n\ndata RValue = T_NIL \n | T_FLOAT Double\n | T_STRING String\n\n -- List is non-ideal. Switch to uvector? Array? There's always going\n -- to be an extraction step to pull the RValues out.\n | T_ARRAY [RValue]\n | T_FIXNUM Int \n | T_HASH Int -- definitely FIXME - native ruby hashes, or going to transliterate into Data.Map?\n | T_BIGNUM Integer \n\n -- technically, these are mapping over the types True and False,\n -- I'm going to treat them as values, though.\n | T_TRUE \n | T_FALSE \n\n | T_SYMBOL Word -- interned string\n\n-- These are the other basic Ruby structures that we're not handling yet.\n-- | T_REGEXP \n-- | T_FILE\n-- | T_STRUCT \n-- | T_DATA \n-- | T_OBJECT \n-- | T_CLASS \n-- | T_MODULE \n\ntoRuby :: RValue -> Value\ntoRuby r = case r of\n T_FLOAT d -> rb_float_new d\n -- need to take the address of the cstr, just cast it to a value\n -- sadly no bytestrings yet - unpack it to a list. yeah it's ugly.\n T_STRING str -> rb_str_new2 $ unsafePerformIO $ newCAString str\n T_FIXNUM i -> int2fix i\n\n -- so this is just bizarre - there's no boolean type. True and False have their own types\n -- as well as their own values.\n T_TRUE -> fromIntegral $ fromEnum RUBY_Qtrue\n T_FALSE -> fromIntegral $ fromEnum RUBY_Qfalse\n T_NIL -> fromIntegral $ fromEnum RUBY_Qnil\n T_ARRAY l -> unsafePerformIO $ do\n ary <- rb_ary_new2 $ fromIntegral $ length l\n mapM_ (rb_ary_push ary . toRuby) l\n return ary\n T_BIGNUM b -> rb_str_to_inum (rb_str_new2 $ unsafePerformIO $ newCAString $ show b) 10 1\n _ -> error \"sorry, haven't implemented that yet.\"\n\nfromRuby :: Value -> RValue\nfromRuby v = case target of\n RT_NIL -> T_NIL\n RT_FIXNUM -> T_FIXNUM $ fix2int v\n RT_STRING -> T_STRING $ unsafePerformIO $ peekCString $ rb_str2cstr v 0\n RT_FLOAT -> T_FLOAT $ num2dbl v\n RT_BIGNUM -> T_BIGNUM $ read $ unsafePerformIO $ peekCString $ rb_str2cstr (rb_big2str v 10) 0\n RT_TRUE -> T_TRUE\n RT_FALSE -> T_FALSE\n RT_ARRAY -> T_ARRAY $ map fromRuby $ unsafePerformIO $ mapM (rb_ary_entry v . fromIntegral) [0..(rb_ary_len v) - 1]\n\n _ -> error (show target)\n where target :: RubyType\n target = toEnum $ rtype v\n\n-- utility stuff\n\nthrowException :: String -> IO Value\nthrowException s = do he <- newCAString \"HaskellError\"\n err <- newCAString s\n rb_raise (rb_eval_string he) err\n error \"shouldn't ever get here\"","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"06927682d6049c824a9942e40f71650ca18807b8","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\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit","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":"cd4b46f95bcdb179d1c1bdf022b772bbf6eff1aa","subject":"Added a Loadable class","message":"Added a Loadable class","repos":"aleator\/CV,TomMD\/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\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","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\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":"50423b14784482a4146890b21fa257ed607345b2","subject":"Getpixel for LAB images","message":"Getpixel for LAB images\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 #-}\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","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\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":"39e217c33bc82a5faa3b6536e15cece78b2650da","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","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit","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":"6e845a1263dee8b4c01e232488f22cb6ca6d7128","subject":"Doc fixes.","message":"Doc fixes.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte","old_file":"gtk\/Graphics\/UI\/Gtk\/Misc\/DrawingArea.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Misc\/DrawingArea.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget DrawingArea\n--\n-- Author : Axel Simon\n--\n-- Created: 22 September 2002\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-- A widget for custom user interface elements\n--\nmodule Graphics.UI.Gtk.Misc.DrawingArea (\n-- * Detail\n-- \n-- | The 'DrawingArea' widget is used for creating custom user interface\n-- elements. It's essentially a blank widget; you can draw on\n-- the 'Drawable' returned by 'drawingAreaGetDrawWindow'.\n--\n-- After creating a drawing area, the application may want to connect to:\n--\n-- * Mouse and button press signals to respond to input from the user.\n--\n-- * The 'realize' signal to take any necessary actions when the widget is\n-- instantiated on a particular display. (Create GDK resources in response to\n-- this signal.)\n--\n-- * The 'configureEvent' signal to take any necessary actions when the\n-- widget changes size.\n--\n-- * The 'exposeEvent' signal to handle redrawing the contents of the\n-- widget.\n--\n-- Expose events are normally delivered when a drawing area first comes\n-- onscreen, or when it's covered by another window and then uncovered\n-- (exposed). You can also force an expose event by adding to the \\\"damage\n-- region\\\" of the drawing area's window; 'widgetQueueDrawArea' and\n-- 'windowInvalidateRect' are equally good ways to do this. You\\'ll then get an\n-- expose event for the invalid region.\n--\n-- The available routines for drawing are documented on the GDK Drawing\n-- Primitives page.\n--\n-- To receive mouse events on a drawing area, you will need to enable them\n-- with 'widgetAddEvents'. To receive keyboard events, you will need to set the\n-- 'widgetCanFocus' attribute on the drawing area, and should probably draw some\n-- user-visible indication that the drawing area is focused.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----DrawingArea\n-- @\n\n-- * Types\n DrawingArea,\n DrawingAreaClass,\n castToDrawingArea,\n toDrawingArea,\n\n-- * Constructors\n drawingAreaNew,\n\n-- * Methods\n drawingAreaGetDrawWindow,\n drawingAreaGetSize\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.General.Structs\t(widgetGetDrawWindow, widgetGetSize)\n-- to make haddock happy:\nimport Graphics.UI.Gtk.Abstract.Widget\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new drawing area.\n--\ndrawingAreaNew :: IO DrawingArea\ndrawingAreaNew =\n makeNewObject mkDrawingArea $\n liftM (castPtr :: Ptr Widget -> Ptr DrawingArea) $\n {# call unsafe drawing_area_new #}\n\n-- | See 'widgetGetDrawWindow'\n--\ndrawingAreaGetDrawWindow :: DrawingArea -> IO DrawWindow\ndrawingAreaGetDrawWindow = widgetGetDrawWindow\n{-# DEPRECATED drawingAreaGetDrawWindow \"use widgetGetDrawWindow instead\" #-}\n\n-- | See 'widgetGetSize'\n--\ndrawingAreaGetSize :: DrawingArea -> IO (Int, Int)\ndrawingAreaGetSize = widgetGetSize\n{-# DEPRECATED drawingAreaGetSize \"use widgetGetSize instead\" #-}\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget DrawingArea\n--\n-- Author : Axel Simon\n--\n-- Created: 22 September 2002\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-- A widget for custom user interface elements\n--\nmodule Graphics.UI.Gtk.Misc.DrawingArea (\n-- * Detail\n-- \n-- | The 'DrawingArea' widget is used for creating custom user interface\n-- elements. It's essentially a blank widget; you can draw on\n-- the 'Drawable' returned by 'drawingAreaGetWindow'.\n--\n-- After creating a drawing area, the application may want to connect to:\n--\n-- * Mouse and button press signals to respond to input from the user. (Use\n-- 'widgetAddEvents' to enable events you wish to receive.)\n--\n-- * The \\\"realize\\\" signal to take any necessary actions when the widget is\n-- instantiated on a particular display. (Create GDK resources in response to\n-- this signal.)\n--\n-- * The \\\"configure_event\\\" signal to take any necessary actions when the\n-- widget changes size.\n--\n-- * The \\\"expose_event\\\" signal to handle redrawing the contents of the\n-- widget.\n--\n-- Expose events are normally delivered when a drawing area first comes\n-- onscreen, or when it's covered by another window and then uncovered\n-- (exposed). You can also force an expose event by adding to the \\\"damage\n-- region\\\" of the drawing area's window; 'widgetQueueDrawArea' and\n-- 'windowInvalidateRect' are equally good ways to do this. You\\'ll then get an\n-- expose event for the invalid region.\n--\n-- The available routines for drawing are documented on the GDK Drawing\n-- Primitives page. See also 'pixbufRenderToDrawable' for drawing a 'Pixbuf'.\n--\n-- To receive mouse events on a drawing area, you will need to enable them\n-- with 'widgetAddEvents'. To receive keyboard events, you will need to set the\n-- 'CanFocus' flag on the drawing area, and should probably draw some\n-- user-visible indication that the drawing area is focused.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----DrawingArea\n-- @\n\n-- * Types\n DrawingArea,\n DrawingAreaClass,\n castToDrawingArea,\n toDrawingArea,\n\n-- * Constructors\n drawingAreaNew,\n\n-- * Methods\n drawingAreaGetDrawWindow,\n drawingAreaGetSize\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.General.Structs\t(widgetGetDrawWindow, widgetGetSize)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new drawing area.\n--\ndrawingAreaNew :: IO DrawingArea\ndrawingAreaNew =\n makeNewObject mkDrawingArea $\n liftM (castPtr :: Ptr Widget -> Ptr DrawingArea) $\n {# call unsafe drawing_area_new #}\n\n-- | See 'widgetGetDrawWindow'\n--\ndrawingAreaGetDrawWindow :: DrawingArea -> IO DrawWindow\ndrawingAreaGetDrawWindow = widgetGetDrawWindow\n{-# DEPRECATED drawingAreaGetDrawWindow \"use widgetGetDrawWindow instead\" #-}\n\n-- | See 'widgetGetSize'\n--\ndrawingAreaGetSize :: DrawingArea -> IO (Int, Int)\ndrawingAreaGetSize = widgetGetSize\n{-# DEPRECATED drawingAreaGetSize \"use widgetGetSize instead\" #-}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"425357f0e2ae48700bc17d802e8cffd5b9efa09f","subject":"RawBlobSize and cleanup","message":"RawBlobSize and cleanup\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 * 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 -> IO Int\nrawBlobSize (Blob b) = return . fromIntegral =<< {#call git_blob_rawsize#} b\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"16147d963a3bf3d8ea33fa46b70f5c8929ec8384","subject":"Initial implementation of openRepo","message":"Initial implementation of openRepo\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = do\n pstr <- newCString path\n res <- {#call git_repository_open#} nullPtr pstr\n return $ case res of\n 0 -> Right repo\n n -> Left . toEnum . fromIntegral $ n\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\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.Primitive\nimport Foreign\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = undefined -- git_repository_open\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5e1fe9c23de362f1e300f1f75bb240a46d9c229a","subject":"[project @ 2005-02-13 16:59:11 by as49]","message":"[project @ 2005-02-13 16:59:11 by as49]\n\nRemove this file which was renamed to Image.chs.pp.\n\ndarcs-hash:20050213165911-d90cf-80df205d351dabee5ce8c1fad1c5566657c46ce2.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Image.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Image.chs","new_contents":"","old_contents":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Image\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2005\/02\/13 16:25:56 $\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-- This widget displays an image.\n--\n--\n-- * Because Haskell is not the best language to modify large images directly\n-- only functions are bound that allow loading images from disc or by stock\n-- names.\n--\n-- * Another function for extracting the 'Pixbuf' is added for \n-- 'CellRenderer'.\n--\n-- TODO\n--\n-- * Figure out what other functions are useful within Haskell. Maybe we should\n-- support loading Pixmaps without exposing them.\n--\nmodule Graphics.UI.Gtk.Display.Image (\n Image,\n ImageClass,\n castToImage,\n imageNewFromFile,\n IconSize,\n iconSizeMenu,\n iconSizeSmallToolbar,\n iconSizeLargeToolbar,\n iconSizeButton,\n iconSizeDialog,\n imageNewFromStock,\n imageGetPixbuf,\n imageSetFromPixbuf,\n imageNewFromPixbuf\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(IconSize, iconSizeInvalid, iconSizeMenu,\n\t\t\t\t\t iconSizeSmallToolbar, iconSizeLargeToolbar,\n\t\t\t\t\t iconSizeButton, iconSizeDialog)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create an image by loading a file.\n--\nimageNewFromFile :: FilePath -> IO Image\nimageNewFromFile path = makeNewObject mkImage $ liftM castPtr $ \n\n\n\n withUTFString path {#call unsafe image_new_from_file#}\n\n\n-- | Create a set of images by specifying a stock\n-- object.\n--\nimageNewFromStock :: String -> IconSize -> IO Image\nimageNewFromStock stock ic = withUTFString stock $ \\strPtr -> \n makeNewObject mkImage $ liftM castPtr $ {#call unsafe image_new_from_stock#}\n strPtr (fromIntegral ic)\n\n-- | Extract the Pixbuf from the 'Image'.\n--\nimageGetPixbuf :: Image -> IO Pixbuf\nimageGetPixbuf img = makeNewGObject mkPixbuf $ liftM castPtr $\n throwIfNull \"Image.imageGetPixbuf: The image contains no Pixbuf object.\" $\n {#call unsafe image_get_pixbuf#} img\n\n\n-- | Overwrite the current content of the 'Image' with a new 'Pixbuf'.\n--\nimageSetFromPixbuf :: Image -> Pixbuf -> IO ()\nimageSetFromPixbuf img pb = {#call unsafe gtk_image_set_from_pixbuf#} img pb\n\n-- | Create an 'Image' from a \n-- 'Pixbuf'.\n--\nimageNewFromPixbuf :: Pixbuf -> IO Image\nimageNewFromPixbuf pbuf = makeNewObject mkImage $ liftM castPtr $\n {#call unsafe image_new_from_pixbuf#} pbuf\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"88dabbed2156c8759d91494a9b14dd5125168f44","subject":"implemented gdalForkIO","message":"implemented gdalForkIO\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 TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , gdalForkIO\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , throwIfError\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Concurrent (ThreadId)\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, liftM2, foldM)\nimport Control.Monad.Trans.Resource (\n ResourceT, runResourceT, register, resourceForkIO)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\ngdalForkIO :: GDAL s () -> GDAL s ThreadId\ngdalForkIO (GDAL a) = GDAL (resourceForkIO a)\n\ndata GDALException = GDALException !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset (Mutex, Ptr (Dataset s t a))\n\nunDataset :: Dataset s t a -> Ptr (Dataset s t a)\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t a -> (Ptr (Dataset s t a) -> 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 GDALRasterBandH as Band newtype nocode#}\n\nnewtype (Band s (t::DatasetMode) a)\n = Band (Mutex, Ptr (Band s t a))\n\nunBand :: Band s t a -> Ptr (Band s t a)\nunBand (Band (_,p)) = p\n\nwithLockedBandPtr\n :: Band s t a -> (Ptr (Band s t a) -> 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 GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n withLockedDatasetPtr ds $ \\dsPtr ->\n c_createCopy d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n m <- liftIO newMutex\n return $ Dataset (m,p)\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = let d = unDataset ds\n in (fromIntegral (getDatasetXSize_ d), fromIntegral (getDatasetYSize_ d)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ (unDataset d) >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError \"setDatasetProjection: could not set projection\" $\n withLockedDatasetPtr d $ withCString p . setProjection' \n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform (unDataset d) 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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds (Geotransform g0 g1 g2 g3 g4 g5) = liftIO $\n withLockedDatasetPtr ds $ \\dsPtr ->\n allocaArray 6 $ \\a -> do\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 dsPtr a\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_ . unDataset\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band (Dataset (m,dp)) = liftIO $ do\n p <- c_getRasterBand dp (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return (Band (m,p))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" c_getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO (Ptr (Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_ . unBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: Ptr (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ (unBand band) xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: Ptr (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ (unBand band))\n , fromIntegral (getBandYSize_ (unBand band)))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: Ptr (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: Ptr (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue = fmap (fmap fromNodata) . liftIO . c_bandNodataValue . unBand\n\nc_bandNodataValue :: Ptr (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: Ptr (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ (unBand b) (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: Ptr (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ (unBand b) (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: Ptr (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\nreadBandPure band xoff yoff sx sy bx by = unsafePerformIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- c_getMaskFlags bPtr\n reader bPtr >>= fmap V_Value . 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 <- c_bandNodataValue bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- c_getMaskBand 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by (V_Value uvec) = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\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\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr ()\n -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: Ptr (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc band = liftIO $ do\n mNodata <- c_bandNodataValue (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n withLockedBandPtr band $ \\b ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount band\n (sx,sy) = bandBlockSize band\n (bx,by) = bandSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band x y (V_Value uvec) = do\n checkType band\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n nElems = bandBlockLen band\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: Ptr (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: Ptr (Band s t a) -> IO (Ptr (Band s t Word8))\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: Ptr (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n--\n-- Value\n--\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype instance U.Vector (Value a) = V_Value (St.Vector (Value a))\nnewtype instance U.MVector s (Value a) = MV_Value (St.MVector s (Value a))\ninstance Storable a => U.Unbox (Value a)\n\ninstance Storable a => M.MVector U.MVector (Value a) where\n basicLength (MV_Value v ) = M.basicLength v\n basicUnsafeSlice m n (MV_Value v) = MV_Value (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_Value v) (MV_Value u) = M.basicOverlaps v u\n basicUnsafeNew = liftM MV_Value . M.basicUnsafeNew\n basicUnsafeRead (MV_Value v) i = M.basicUnsafeRead v i\n basicUnsafeWrite (MV_Value v) i x = M.basicUnsafeWrite v i x\n basicInitialize (MV_Value v) = M.basicInitialize v\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n {-# INLINE basicInitialize #-}\n\ninstance Storable a => G.Vector U.Vector (Value a) where\n basicUnsafeFreeze (MV_Value v) = liftM V_Value (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Value v) = liftM MV_Value (G.basicUnsafeThaw v)\n basicLength ( V_Value v) = G.basicLength v\n basicUnsafeSlice m n (V_Value v) = V_Value (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_Value v) i = G.basicUnsafeIndexM v i\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , throwIfError\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, liftM2, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = GDALException !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset (Mutex, Ptr (Dataset s t a))\n\nunDataset :: Dataset s t a -> Ptr (Dataset s t a)\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t a -> (Ptr (Dataset s t a) -> 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 GDALRasterBandH as Band newtype nocode#}\n\nnewtype (Band s (t::DatasetMode) a)\n = Band (Mutex, Ptr (Band s t a))\n\nunBand :: Band s t a -> Ptr (Band s t a)\nunBand (Band (_,p)) = p\n\nwithLockedBandPtr\n :: Band s t a -> (Ptr (Band s t a) -> 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 GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n withLockedDatasetPtr ds $ \\dsPtr ->\n c_createCopy d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n m <- liftIO newMutex\n return $ Dataset (m,p)\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = let d = unDataset ds\n in (fromIntegral (getDatasetXSize_ d), fromIntegral (getDatasetYSize_ d)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ (unDataset d) >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError \"setDatasetProjection: could not set projection\" $\n withLockedDatasetPtr d $ withCString p . setProjection' \n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform (unDataset d) 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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds (Geotransform g0 g1 g2 g3 g4 g5) = liftIO $\n withLockedDatasetPtr ds $ \\dsPtr ->\n allocaArray 6 $ \\a -> do\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 dsPtr a\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_ . unDataset\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band (Dataset (m,dp)) = liftIO $ do\n p <- c_getRasterBand dp (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return (Band (m,p))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" c_getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO (Ptr (Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_ . unBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: Ptr (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ (unBand band) xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: Ptr (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ (unBand band))\n , fromIntegral (getBandYSize_ (unBand band)))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: Ptr (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: Ptr (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue = fmap (fmap fromNodata) . liftIO . c_bandNodataValue . unBand\n\nc_bandNodataValue :: Ptr (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: Ptr (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ (unBand b) (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: Ptr (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ (unBand b) (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: Ptr (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\nreadBandPure band xoff yoff sx sy bx by = unsafePerformIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- c_getMaskFlags bPtr\n reader bPtr >>= fmap V_Value . 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 <- c_bandNodataValue bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- c_getMaskBand 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by (V_Value uvec) = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\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\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr ()\n -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: Ptr (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc band = liftIO $ do\n mNodata <- c_bandNodataValue (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n withLockedBandPtr band $ \\b ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount band\n (sx,sy) = bandBlockSize band\n (bx,by) = bandSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band x y (V_Value uvec) = do\n checkType band\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n nElems = bandBlockLen band\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: Ptr (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: Ptr (Band s t a) -> IO (Ptr (Band s t Word8))\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: Ptr (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n--\n-- Value\n--\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype instance U.Vector (Value a) = V_Value (St.Vector (Value a))\nnewtype instance U.MVector s (Value a) = MV_Value (St.MVector s (Value a))\ninstance Storable a => U.Unbox (Value a)\n\ninstance Storable a => M.MVector U.MVector (Value a) where\n basicLength (MV_Value v ) = M.basicLength v\n basicUnsafeSlice m n (MV_Value v) = MV_Value (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_Value v) (MV_Value u) = M.basicOverlaps v u\n basicUnsafeNew = liftM MV_Value . M.basicUnsafeNew\n basicUnsafeRead (MV_Value v) i = M.basicUnsafeRead v i\n basicUnsafeWrite (MV_Value v) i x = M.basicUnsafeWrite v i x\n basicInitialize (MV_Value v) = M.basicInitialize v\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n {-# INLINE basicInitialize #-}\n\ninstance Storable a => G.Vector U.Vector (Value a) where\n basicUnsafeFreeze (MV_Value v) = liftM V_Value (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Value v) = liftM MV_Value (G.basicUnsafeThaw v)\n basicLength ( V_Value v) = G.basicLength v\n basicUnsafeSlice m n (V_Value v) = V_Value (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_Value v) i = G.basicUnsafeIndexM v i\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"206b2a06b092bef7c34b6dfb522aca94fc252aa6","subject":"Initial progress on c2hs description of hyperclient.h","message":"Initial progress on c2hs description of hyperclient.h\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 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\nhyperclientCreate :: String -> Int16 -> IO HyperclientPtr\nhyperclientCreate host port = do\n inHost <- newCString host\n {# call hyperclient_create #} inHost (fromIntegral port)\n\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-- result <- hyperclientGetRaw client space inKey (fromIntegral inKeySize) returnCodePtr attributePtr attributePtrSize\n","old_contents":"module Database.HyperDex.Internal.Hyperclient where\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Data.Int\n\n#import \"hyperclient.h\"\n\ndata Hyperclient\n{#pointer *hyperclient as HyperclientPtr -> Hyperclient #}\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 HcReturnCode {underscoreToCase} #}\n\n{#fun hyperclient_create as ^\n { `String', `Int16' } -> `HyperclientPtr' id #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"72422b638e5e3cee77af381dec5854b92ef15930","subject":"Pick the right function to load a Pixbuf on Windows.","message":"Pick the right function to load a Pixbuf on Windows.\n","repos":"gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/PixbufAnimation.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/PixbufAnimation.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf Animation\n--\n-- Author : Matthew Arsenault\n--\n-- Created: 14 November 2009\n--\n-- Copyright (C) 2009 Matthew Arsenault\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.Gdk.PixbufAnimation (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'PixbufAnimation'\n-- | +----'PixbufSimpleAnim'\n-- @\n\n-- * Types\n PixbufAnimation,\n PixbufAnimationClass,\n castToPixbufAnimation, gTypePixbufAnimation,\n toPixbufAnimation,\n\n PixbufAnimationIter,\n PixbufAnimationIterClass,\n castToPixbufAnimationIter, gTypePixbufAnimationIter,\n toPixbufAnimationIter,\n\n PixbufSimpleAnim,\n PixbufSimpleAnimClass,\n castToPixbufSimpleAnim, gTypePixbufSimpleAnim,\n toPixbufSimpleAnim,\n\n-- * Constructors\n pixbufAnimationNewFromFile,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimNew,\n#endif\n\n-- * Methods\n pixbufAnimationGetWidth,\n pixbufAnimationGetHeight,\n pixbufAnimationGetIter,\n pixbufAnimationIsStaticImage,\n pixbufAnimationGetStaticImage,\n pixbufAnimationIterAdvance,\n pixbufAnimationIterGetDelayTime,\n pixbufAnimationIterOnCurrentlyLoadingFrame,\n pixbufAnimationIterGetPixbuf,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimAddFrame,\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n pixbufSimpleAnimSetLoop,\n pixbufSimpleAnimGetLoop\n#endif\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\n{# import Graphics.UI.Gtk.Gdk.Pixbuf #}\n\n{# context prefix=\"gdk\" #}\n\n\n--CHECKME: Domain error doc, GFileError ???\n-- | Creates a new animation by loading it from a file. The file\n-- format is detected automatically. If the file's format does not\n-- support multi-frame images, then an animation with a single frame\n-- will be created. Possible errors are in the 'PixbufError' and\n-- 'GFileError' domains.\n--\n-- Any of several error conditions may occur: the file could not be\n-- opened, there was no loader for the file's format, there was not\n-- enough memory to allocate the image buffer, or the image file\n-- contained invalid data.\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' or 'GFileError'\n--\npixbufAnimationNewFromFile :: FilePath -- ^ Name of file to load, in the GLib file name encoding\n -> IO PixbufAnimation -- ^ A newly-created animation\npixbufAnimationNewFromFile fname =\n constructNewGObject mkPixbufAnimation $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,5)\n {#call unsafe pixbuf_animation_new_from_file_utf8#} strPtr errPtrPtr\n#else\n {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr\n#endif\n\n-- | Queries the width of the bounding box of a pixbuf animation.\npixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Width of the bounding box of the animation.\npixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self\n\n-- | Queries the height of the bounding box of a pixbuf animation.\npixbufAnimationGetHeight :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Height of the bounding box of the animation.\npixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self\n\n\n-- | Get an iterator for displaying an animation. The iterator\n-- provides the frames that should be displayed at a given time. The\n-- start time would normally come from 'gGetCurrentTime', and marks\n-- the beginning of animation playback. After creating an iterator,\n-- you should immediately display the pixbuf returned by\n-- 'pixbufAnimationIterGetPixbuf'. Then, you should install a\n-- timeout (with 'timeoutAdd') or by some other mechanism ensure\n-- that you'll update the image after\n-- 'pixbufAnimationIterGetDelayTime' milliseconds. Each time the\n-- image is updated, you should reinstall the timeout with the new,\n-- possibly-changed delay time.\n--\n-- As a shortcut, if start_time is @Nothing@, the result of\n-- 'gGetCurrentTime' will be used automatically.\n--\n-- To update the image (i.e. possibly change the result of\n-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),\n-- call 'pixbufAnimationIterAdvance'.\n--\n-- If you're using 'PixbufLoader', in addition to updating the image\n-- after the delay time, you should also update it whenever you\n-- receive the area_updated signal and\n-- 'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In\n-- this case, the frame currently being fed into the loader has\n-- received new data, so needs to be refreshed. The delay time for a\n-- frame may also be modified after an area_updated signal, for\n-- example if the delay time for a frame is encoded in the data after\n-- the frame itself. So your timeout should be reinstalled after any\n-- area_updated signal.\n--\n-- A delay time of -1 is possible, indicating \"infinite.\"\n--\npixbufAnimationGetIter :: PixbufAnimation -- ^ a 'PixbufAnimation'\n -> Maybe GTimeVal -- ^ time when the animation starts playing\n -> IO PixbufAnimationIter -- ^ an iterator to move over the animation\npixbufAnimationGetIter self tv = maybeWith with tv $ \\stPtr ->\n constructNewGObject mkPixbufAnimationIter $\n {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)\n\n\n\n-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns\n-- out to be a plain, unanimated image, then this function will\n-- return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve\n-- the image.\n--\npixbufAnimationIsStaticImage :: PixbufAnimation\n -> IO Bool -- ^ TRUE if the \"animation\" was really just an image\npixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self\n\n\n-- | If an animation is really just a plain image (has only one\n-- frame), this function returns that image. If the animation is an\n-- animation, this function returns a reasonable thing to display as\n-- a static unanimated image, which might be the first frame, or\n-- something more sophisticated. If an animation hasn't loaded any\n-- frames yet, this function will return @Nothing@.\n--\npixbufAnimationGetStaticImage :: PixbufAnimation\n -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation\npixbufAnimationGetStaticImage self =\n maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self\n\n\n\n-- | Possibly advances an animation to a new frame. Chooses the frame\n-- based on the start time passed to 'pixbufAnimationGetIter'.\n--\n-- current_time would normally come from 'gGetCurrentTime', and must\n-- be greater than or equal to the time passed to\n-- 'pixbufAnimationGetIter', and must increase or remain unchanged\n-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you\n-- can't go backward in time; animations only play forward.\n--\n-- As a shortcut, pass @Nothing@ for the current time and\n-- 'gGetCurrentTime' will be invoked on your behalf. So you only need\n-- to explicitly pass current_time if you're doing something odd like\n-- playing the animation at double speed.\n--\n-- If this function returns @False@, there's no need to update the\n-- animation display, assuming the display had been rendered prior to\n-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and\n-- update the display with the new pixbuf.\n--\npixbufAnimationIterAdvance :: PixbufAnimationIter -- ^ A 'PixbufAnimationIter'\n -> Maybe GTimeVal -- ^ current time\n -> IO Bool -- ^ @True@ if the image may need updating\npixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \\tvPtr ->\n {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)\n\n\n-- | Gets the number of milliseconds the current pixbuf should be\n-- displayed, or -1 if the current pixbuf should be displayed\n-- forever. 'timeoutAdd' conveniently takes a timeout in\n-- milliseconds, so you can use a timeout to schedule the next\n-- update.\n--\npixbufAnimationIterGetDelayTime :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Int -- ^ delay time in milliseconds (thousandths of a second)\npixbufAnimationIterGetDelayTime self = liftM fromIntegral $\n {#call unsafe pixbuf_animation_iter_get_delay_time#} self\n\n\n-- | Used to determine how to respond to the area_updated signal on\n-- 'PixbufLoader' when loading an animation. area_updated is emitted\n-- for an area of the frame currently streaming in to the loader. So\n-- if you're on the currently loading frame, you need to redraw the\n-- screen for the updated area.\n--\npixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter\n -> IO Bool -- ^ @True@ if the frame we're on is partially loaded, or the last frame\npixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $\n {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter\n\n--CHECKME: referencing, usage of constructNewGObject\n-- | Gets the current pixbuf which should be displayed; the pixbuf will\n-- be the same size as the animation itself\n-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This\n-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'\n-- milliseconds. The caller of this function does not own a reference\n-- to the returned pixbuf; the returned pixbuf will become invalid\n-- when the iterator advances to the next frame, which may happen\n-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to\n-- keep it (don't just add a reference), as it may get recycled as you\n-- advance the iterator.\n--\npixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Pixbuf -- ^ the pixbuf to be displayed\npixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $\n {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter\n\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Creates a new, empty animation.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimNew :: Int -- ^ the width of the animation\n -> Int -- ^ the height of the animation\n -> Float -- ^ the speed of the animation, in frames per second\n -> IO PixbufSimpleAnim -- ^ a newly allocated 'PixbufSimpleAnim'\npixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $\n {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)\n\n\n-- | Adds a new frame to animation. The pixbuf must have the\n-- dimensions specified when the animation was constructed.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimAddFrame :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Pixbuf -- ^ the pixbuf to add\n -> IO ()\npixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb\n\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n\n-- | Sets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimSetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Bool -- ^ whether to loop the animation\n -> IO ()\npixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)\n\n\n-- | Gets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimGetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> IO Bool -- ^ @True@ if the animation loops forever, @False@ otherwise\npixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf Animation\n--\n-- Author : Matthew Arsenault\n--\n-- Created: 14 November 2009\n--\n-- Copyright (C) 2009 Matthew Arsenault\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.Gdk.PixbufAnimation (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'PixbufAnimation'\n-- | +----'PixbufSimpleAnim'\n-- @\n\n-- * Types\n PixbufAnimation,\n PixbufAnimationClass,\n castToPixbufAnimation, gTypePixbufAnimation,\n toPixbufAnimation,\n\n PixbufAnimationIter,\n PixbufAnimationIterClass,\n castToPixbufAnimationIter, gTypePixbufAnimationIter,\n toPixbufAnimationIter,\n\n PixbufSimpleAnim,\n PixbufSimpleAnimClass,\n castToPixbufSimpleAnim, gTypePixbufSimpleAnim,\n toPixbufSimpleAnim,\n\n-- * Constructors\n pixbufAnimationNewFromFile,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimNew,\n#endif\n\n-- * Methods\n pixbufAnimationGetWidth,\n pixbufAnimationGetHeight,\n pixbufAnimationGetIter,\n pixbufAnimationIsStaticImage,\n pixbufAnimationGetStaticImage,\n pixbufAnimationIterAdvance,\n pixbufAnimationIterGetDelayTime,\n pixbufAnimationIterOnCurrentlyLoadingFrame,\n pixbufAnimationIterGetPixbuf,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimAddFrame,\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n pixbufSimpleAnimSetLoop,\n pixbufSimpleAnimGetLoop\n#endif\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\n{# import Graphics.UI.Gtk.Gdk.Pixbuf #}\n\n{# context prefix=\"gdk\" #}\n\n\n--CHECKME: Domain error doc, GFileError ???\n-- | Creates a new animation by loading it from a file. The file\n-- format is detected automatically. If the file's format does not\n-- support multi-frame images, then an animation with a single frame\n-- will be created. Possible errors are in the 'PixbufError' and\n-- 'GFileError' domains.\n--\n-- Any of several error conditions may occur: the file could not be\n-- opened, there was no loader for the file's format, there was not\n-- enough memory to allocate the image buffer, or the image file\n-- contained invalid data.\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' or 'GFileError'\n--\npixbufAnimationNewFromFile :: FilePath -- ^ Name of file to load, in the GLib file name encoding\n -> IO PixbufAnimation -- ^ A newly-created animation\npixbufAnimationNewFromFile fname =\n constructNewGObject mkPixbufAnimation $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr\n\n\n-- | Queries the width of the bounding box of a pixbuf animation.\npixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Width of the bounding box of the animation.\npixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self\n\n-- | Queries the height of the bounding box of a pixbuf animation.\npixbufAnimationGetHeight :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Height of the bounding box of the animation.\npixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self\n\n\n-- | Get an iterator for displaying an animation. The iterator\n-- provides the frames that should be displayed at a given time. The\n-- start time would normally come from 'gGetCurrentTime', and marks\n-- the beginning of animation playback. After creating an iterator,\n-- you should immediately display the pixbuf returned by\n-- 'pixbufAnimationIterGetPixbuf'. Then, you should install a\n-- timeout (with 'timeoutAdd') or by some other mechanism ensure\n-- that you'll update the image after\n-- 'pixbufAnimationIterGetDelayTime' milliseconds. Each time the\n-- image is updated, you should reinstall the timeout with the new,\n-- possibly-changed delay time.\n--\n-- As a shortcut, if start_time is @Nothing@, the result of\n-- 'gGetCurrentTime' will be used automatically.\n--\n-- To update the image (i.e. possibly change the result of\n-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),\n-- call 'pixbufAnimationIterAdvance'.\n--\n-- If you're using 'PixbufLoader', in addition to updating the image\n-- after the delay time, you should also update it whenever you\n-- receive the area_updated signal and\n-- 'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In\n-- this case, the frame currently being fed into the loader has\n-- received new data, so needs to be refreshed. The delay time for a\n-- frame may also be modified after an area_updated signal, for\n-- example if the delay time for a frame is encoded in the data after\n-- the frame itself. So your timeout should be reinstalled after any\n-- area_updated signal.\n--\n-- A delay time of -1 is possible, indicating \"infinite.\"\n--\npixbufAnimationGetIter :: PixbufAnimation -- ^ a 'PixbufAnimation'\n -> Maybe GTimeVal -- ^ time when the animation starts playing\n -> IO PixbufAnimationIter -- ^ an iterator to move over the animation\npixbufAnimationGetIter self tv = maybeWith with tv $ \\stPtr ->\n constructNewGObject mkPixbufAnimationIter $\n {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)\n\n\n\n-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns\n-- out to be a plain, unanimated image, then this function will\n-- return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve\n-- the image.\n--\npixbufAnimationIsStaticImage :: PixbufAnimation\n -> IO Bool -- ^ TRUE if the \"animation\" was really just an image\npixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self\n\n\n-- | If an animation is really just a plain image (has only one\n-- frame), this function returns that image. If the animation is an\n-- animation, this function returns a reasonable thing to display as\n-- a static unanimated image, which might be the first frame, or\n-- something more sophisticated. If an animation hasn't loaded any\n-- frames yet, this function will return @Nothing@.\n--\npixbufAnimationGetStaticImage :: PixbufAnimation\n -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation\npixbufAnimationGetStaticImage self =\n maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self\n\n\n\n-- | Possibly advances an animation to a new frame. Chooses the frame\n-- based on the start time passed to 'pixbufAnimationGetIter'.\n--\n-- current_time would normally come from 'gGetCurrentTime', and must\n-- be greater than or equal to the time passed to\n-- 'pixbufAnimationGetIter', and must increase or remain unchanged\n-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you\n-- can't go backward in time; animations only play forward.\n--\n-- As a shortcut, pass @Nothing@ for the current time and\n-- 'gGetCurrentTime' will be invoked on your behalf. So you only need\n-- to explicitly pass current_time if you're doing something odd like\n-- playing the animation at double speed.\n--\n-- If this function returns @False@, there's no need to update the\n-- animation display, assuming the display had been rendered prior to\n-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and\n-- update the display with the new pixbuf.\n--\npixbufAnimationIterAdvance :: PixbufAnimationIter -- ^ A 'PixbufAnimationIter'\n -> Maybe GTimeVal -- ^ current time\n -> IO Bool -- ^ @True@ if the image may need updating\npixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \\tvPtr ->\n {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)\n\n\n-- | Gets the number of milliseconds the current pixbuf should be\n-- displayed, or -1 if the current pixbuf should be displayed\n-- forever. 'timeoutAdd' conveniently takes a timeout in\n-- milliseconds, so you can use a timeout to schedule the next\n-- update.\n--\npixbufAnimationIterGetDelayTime :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Int -- ^ delay time in milliseconds (thousandths of a second)\npixbufAnimationIterGetDelayTime self = liftM fromIntegral $\n {#call unsafe pixbuf_animation_iter_get_delay_time#} self\n\n\n-- | Used to determine how to respond to the area_updated signal on\n-- 'PixbufLoader' when loading an animation. area_updated is emitted\n-- for an area of the frame currently streaming in to the loader. So\n-- if you're on the currently loading frame, you need to redraw the\n-- screen for the updated area.\n--\npixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter\n -> IO Bool -- ^ @True@ if the frame we're on is partially loaded, or the last frame\npixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $\n {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter\n\n--CHECKME: referencing, usage of constructNewGObject\n-- | Gets the current pixbuf which should be displayed; the pixbuf will\n-- be the same size as the animation itself\n-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This\n-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'\n-- milliseconds. The caller of this function does not own a reference\n-- to the returned pixbuf; the returned pixbuf will become invalid\n-- when the iterator advances to the next frame, which may happen\n-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to\n-- keep it (don't just add a reference), as it may get recycled as you\n-- advance the iterator.\n--\npixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Pixbuf -- ^ the pixbuf to be displayed\npixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $\n {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter\n\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Creates a new, empty animation.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimNew :: Int -- ^ the width of the animation\n -> Int -- ^ the height of the animation\n -> Float -- ^ the speed of the animation, in frames per second\n -> IO PixbufSimpleAnim -- ^ a newly allocated 'PixbufSimpleAnim'\npixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $\n {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)\n\n\n-- | Adds a new frame to animation. The pixbuf must have the\n-- dimensions specified when the animation was constructed.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimAddFrame :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Pixbuf -- ^ the pixbuf to add\n -> IO ()\npixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb\n\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n\n-- | Sets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimSetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Bool -- ^ whether to loop the animation\n -> IO ()\npixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)\n\n\n-- | Gets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimGetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> IO Bool -- ^ @True@ if the animation loops forever, @False@ otherwise\npixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1d872c7fbec2f1b13e2973f14bdcff4c69166908","subject":"give haskell-style names to texture data types","message":"give haskell-style names to texture data types\n\nIgnore-this: 2b4c592d38359825c1d116ff145955c8\n\ndarcs-hash:20100610001247-dcabc-d0e1878c79bf1ba9c8b28084093ccd9e04889f9c.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(Texture), AddressMode(..), FilterMode(..), Format(..),\n create, destroy,\n getPtr, getAddressMode, getFilterMode, getFormat,\n setPtr, setAddressMode, setFilterMode, setFormat\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\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-- |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-- |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-- |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--\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat tex fmt dim = nothingIfOk =<< cuTexRefSetFormat tex fmt dim\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(Texture), AddressMode(..), FilterMode(..), Format(..),\n create, destroy,\n getPtr, getAddressMode, getFilterMode, getFormat,\n setPtr, setAddressMode, setFilterMode, setFormat\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\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-- |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-- |Texture data formats\n--\n{# enum CUarray_format as Format\n { underscoreToCase }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Texture management\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--\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat tex fmt dim = nothingIfOk =<< cuTexRefSetFormat tex fmt dim\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"b797998cf75eb7ec44732cca5f7567bfbaac622a","subject":"add setArg on kernel","message":"add setArg on kernel\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Program.chs","new_file":"src\/System\/GPU\/OpenCL\/Program.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.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram, clGetProgramReferenceCount, \n clGetProgramContext, clGetProgramNumDevices, clGetProgramDevices,\n clGetProgramSource, clGetProgramBinarySizes, clGetProgramBinaries, \n clGetProgramBuildStatus, clGetProgramBuildOptions, clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clSetKernelArg, clGetKernelFunctionName, clGetKernelNumArgs, \n clGetKernelReferenceCount, clGetKernelContext, clGetKernelProgram, \n clGetKernelWorkGroupSize, clGetKernelCompileWorkGroupSize, \n clGetKernelLocalMemSize\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLulong, CLProgram, CLContext, CLKernel, CLDeviceID, \n CLError(..), CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, \n CLProgramBuildInfo_, CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, \n wrapPError, wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\n--foreign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n-- CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import ccall \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import ccall \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import ccall \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it returns one of the\nfollowing error values:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the program 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.\nclGetProgramReferenceCount :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\nclGetProgramContext :: CLProgram -> IO (Either CLError CLContext)\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\nclGetProgramNumDevices :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\nclGetProgramDevices :: CLProgram -> IO (Either CLError [CLDeviceID])\nclGetProgramDevices prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\nclGetProgramSource :: CLProgram -> IO (Either CLError String)\nclGetProgramSource prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\nclGetProgramBinarySizes :: CLProgram -> IO (Either CLError [CSize])\nclGetProgramBinarySizes prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n-}\nclGetProgramBinaries :: CLProgram -> IO (Either CLError [[Word8]])\nclGetProgramBinaries prg = do\n sval <- clGetProgramBinarySizes prg\n case sval of\n Left err -> return . Left $ err\n Right sizes -> do\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then do\n vals <- zipWithM peekArray (map fromIntegral sizes) buffers\n return . Right $ vals\n else return . Left . toEnum . fromIntegral $ errcode\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO (Either CLError CLBuildStatus)\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildOptions prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildLog prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it returns one of the following error values:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO (Either CLError CLKernel)\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, returns 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, returns 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and returns\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO (Either CLError [CLKernel])\nclCreateKernelsInProgram prg = do\n nks <- alloca $ \\pn -> do\n errcode <- raw_clCreateKernelsInProgram prg 0 nullPtr pn\n if errcode == (getCLValue CL_SUCCESS)\n then peek pn >>= (return . Right)\n else return $ Left errcode\n \n case nks of\n Left err -> return . Left . getEnumCL $ err\n Right n -> allocaArray (fromIntegral n) $ \\pks -> do\n errcode <- raw_clCreateKernelsInProgram prg n pks nullPtr\n if errcode == (getCLValue CL_SUCCESS)\n then peekArray (fromIntegral n) pks >>= (return . Right)\n else return . Left .getEnumCL $ errcode\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n{-| Used to set the argument value for a specific argument of a kernel.\n\nA kernel object does not update the reference count for objects such as memory,\nsampler objects specified as argument values by 'clSetKernelArg', Users may not\nrely on a kernel object to retain objects specified as argument values to the\nkernel.\n\nImplementations shall not allow 'CLKernel' objects to hold reference counts to\n'CLKernel' arguments, because no mechanism is provided for the user to tell the\nkernel to release that ownership right. If the kernel holds ownership rights on\nkernel args, that would make it impossible for the user to tell with certainty\nwhen he may safely release user allocated resources associated with OpenCL\nobjects such as the CLMem backing store used with 'CL_MEM_USE_HOST_PTR'.\n\n'clSetKernelArg' returns returns one of the following errors when fails:\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n \n * 'CL_INVALID_ARG_INDEX' if arg_index is not a valid argument index.\n\n * 'CL_INVALID_ARG_VALUE' if arg_value specified is NULL for an argument that is\nnot declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_MEM_OBJECT' for an argument declared to be a memory object when\nthe specified arg_value is not a valid memory object.\n\n * 'CL_INVALID_SAMPLER' for an argument declared to be of type sampler_t when\nthe specified arg_value is not a valid sampler object.\n\n * 'CL_INVALID_ARG_SIZE' if arg_size does not match the size of the data type\nfor an argument that is not a memory object or if the argument is a memory\nobject and arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is\ndeclared with the __local qualifier or if the argument is a sampler and arg_size\n!= sizeof(cl_sampler). \n-}\nclSetKernelArg :: Storable a => CLKernel -> CLuint -> a -> IO (Either CLError ())\nclSetKernelArg krn idx val = with val $ \\pval -> do\n errcode <- raw_clSetKernelArg krn idx (fromIntegral . sizeOf $ val) (castPtr pval)\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO (Either CLError CSize)\ngetKernelInfoSize krn infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetKernelInfo krn infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the kernel function name.\nclGetKernelFunctionName :: CLKernel -> IO (Either CLError String)\nclGetKernelFunctionName krn = do\n sval <- getKernelInfoSize krn infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\nclGetKernelNumArgs :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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.\nclGetKernelReferenceCount :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\nclGetKernelContext :: CLKernel -> IO (Either CLError CLContext)\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\nclGetKernelProgram :: CLKernel -> IO (Either CLError CLProgram)\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n\n#c\nenum CLKernelGroupInfo {\n cL_KERNEL_WORK_GROUP_SIZE=CL_KERNEL_WORK_GROUP_SIZE,\n cL_KERNEL_COMPILE_WORK_GROUP_SIZE=CL_KERNEL_COMPILE_WORK_GROUP_SIZE,\n cL_KERNEL_LOCAL_MEM_SIZE=CL_KERNEL_LOCAL_MEM_SIZE,\n };\n#endc\n{#enum CLKernelGroupInfo {upcaseFirstLetter} #}\n\n-- | This provides a mechanism for the application to query the work-group size\n-- that can be used to execute a kernel on a specific device given by\n-- device. The OpenCL implementation uses the resource requirements of the\n-- kernel (register usage etc.) to determine what this work-group size should\n-- be.\nclGetKernelWorkGroupSize :: CLKernel -> CLDeviceID -> IO (Either CLError CSize)\nclGetKernelWorkGroupSize krn device = wrapGetInfo (\\(dat :: Ptr CSize)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_WORK_GROUP_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Returns the work-group size specified by the __attribute__((reqd_work_gr\n-- oup_size(X, Y, Z))) qualifier. See Function Qualifiers. If the work-group\n-- size is not specified using the above attribute qualifier (0, 0, 0) is\n-- returned.\nclGetKernelCompileWorkGroupSize :: CLKernel -> CLDeviceID -> IO (Either CLError [CSize])\nclGetKernelCompileWorkGroupSize krn device = do\n allocaArray num $ \\(buff :: Ptr CSize) -> do\n errcode <- raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray num buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_KERNEL_COMPILE_WORK_GROUP_SIZE\n num = 3\n elemSize = fromIntegral $ sizeOf (0::CSize)\n size = fromIntegral $ num * elemSize\n\n\n-- | Returns the amount of local memory in bytes being used by a kernel. This\n-- includes local memory that may be needed by an implementation to execute the\n-- kernel, variables declared inside the kernel with the __local address\n-- qualifier and local memory to be allocated for arguments to the kernel\n-- declared as pointers with the __local address qualifier and whose size is\n-- specified with 'clSetKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel declared\n-- with the __local address qualifier, is not specified, its size is assumed to\n-- be 0.\nclGetKernelLocalMemSize :: CLKernel -> CLDeviceID -> IO (Either CLError CLulong)\nclGetKernelLocalMemSize krn device = wrapGetInfo (\\(dat :: Ptr CLulong)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_LOCAL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CLulong)\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.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram, clGetProgramReferenceCount, \n clGetProgramContext, clGetProgramNumDevices, clGetProgramDevices,\n clGetProgramSource, clGetProgramBinarySizes, clGetProgramBinaries, \n clGetProgramBuildStatus, clGetProgramBuildOptions, clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clGetKernelFunctionName, clGetKernelNumArgs, clGetKernelReferenceCount, \n clGetKernelContext, clGetKernelProgram\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLKernel, CLDeviceID, CLError(..), \n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, wrapPError, \n wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\n--foreign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n-- CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import ccall \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import ccall \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import ccall \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it returns one of the\nfollowing error values:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the program 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.\nclGetProgramReferenceCount :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\nclGetProgramContext :: CLProgram -> IO (Either CLError CLContext)\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\nclGetProgramNumDevices :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\nclGetProgramDevices :: CLProgram -> IO (Either CLError [CLDeviceID])\nclGetProgramDevices prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\nclGetProgramSource :: CLProgram -> IO (Either CLError String)\nclGetProgramSource prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\nclGetProgramBinarySizes :: CLProgram -> IO (Either CLError [CSize])\nclGetProgramBinarySizes prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n-}\nclGetProgramBinaries :: CLProgram -> IO (Either CLError [[Word8]])\nclGetProgramBinaries prg = do\n sval <- clGetProgramBinarySizes prg\n case sval of\n Left err -> return . Left $ err\n Right sizes -> do\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then do\n vals <- zipWithM peekArray (map fromIntegral sizes) buffers\n return . Right $ vals\n else return . Left . toEnum . fromIntegral $ errcode\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO (Either CLError CLBuildStatus)\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildOptions prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildLog prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it returns one of the following error values:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO (Either CLError CLKernel)\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, returns 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, returns 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and returns\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO (Either CLError [CLKernel])\nclCreateKernelsInProgram prg = do\n nks <- alloca $ \\pn -> do\n errcode <- raw_clCreateKernelsInProgram prg 0 nullPtr pn\n if errcode == (getCLValue CL_SUCCESS)\n then peek pn >>= (return . Right)\n else return $ Left errcode\n \n case nks of\n Left err -> return . Left . getEnumCL $ err\n Right n -> allocaArray (fromIntegral n) $ \\pks -> do\n errcode <- raw_clCreateKernelsInProgram prg n pks nullPtr\n if errcode == (getCLValue CL_SUCCESS)\n then peekArray (fromIntegral n) pks >>= (return . Right)\n else return . Left .getEnumCL $ errcode\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO (Either CLError CSize)\ngetKernelInfoSize krn infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetKernelInfo krn infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the kernel function name.\nclGetKernelFunctionName :: CLKernel -> IO (Either CLError String)\nclGetKernelFunctionName krn = do\n sval <- getKernelInfoSize krn infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\nclGetKernelNumArgs :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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.\nclGetKernelReferenceCount :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\nclGetKernelContext :: CLKernel -> IO (Either CLError CLContext)\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\nclGetKernelProgram :: CLKernel -> IO (Either CLError CLProgram)\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"664d82c730e147ff079207bd88d7c5d17b87f7e5","subject":"FIX: Montage was working wrong after last edit","message":"FIX: Montage was working wrong after last edit","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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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 = 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 (rh,rw)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) \n | y <- [0..u-1] , x <- [0..v-1] \n | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 = 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..u-1] , x <- [0..v-1] \n | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"59fe590fc8c5bf8ae0210707b516610efa5920b0","subject":"Sanitized getChannel, setCOI, resetCOI","message":"Sanitized getChannel, setCOI, resetCOI\n","repos":"aleator\/CV,TomMD\/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, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\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-- |\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 = withUniPtr withImage\nwithMutableImage (Mutable i) o = withGenImage i o\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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 -> 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\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\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\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\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\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 = 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 :: (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 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 (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 :: (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) = 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 return r\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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\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-- |\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 = withUniPtr withImage\nwithMutableImage (Mutable i) o = withGenImage i o\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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 -> 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\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\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\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\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\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 = 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 (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 :: (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) = 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 return r\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":"0d85d215693c513a40ba3639cb73c8b3dbdfb69d","subject":"Build attributes from glib properties whenever possible.","message":"Build attributes from glib properties whenever possible.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebView.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebView.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ViewPatterns #-}\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 be bound now,\n-- because it needs JavaScriptCore that hasn't binding.\n--\n-- Signal `create-plugin-widget` can't be bound now,\n-- no idea how to bind `GHaskellTable`\n--\n--\n-- * TODO:\n--\n-- Binding for webkit_web_view_get_snapshot\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebView (\n-- * Description\n-- | Cf http:\/\/webkitgtk.org\/reference\/webkitgtk\/stable\/webkitgtk-webkitwebview.html.\n\n-- * Types\n WebView,\n WebViewClass,\n\n-- * Enums\n NavigationResponse(..),\n TargetInfo(..),\n LoadStatus(..),\n ViewMode(..),\n\n-- * Constructors\n webViewNew,\n\n-- * Methods\n-- ** Load\n#if WEBKIT_CHECK_VERSION(1,1,1)\n webViewLoadUri,\n#endif\n webViewLoadHtmlString,\n#if WEBKIT_CHECK_VERSION(1,1,1)\n webViewLoadRequest,\n#endif\n webViewLoadString,\n#if WEBKIT_CHECK_VERSION(1,1,7)\n webViewGetLoadStatus,\n#endif\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#if WEBKIT_CHECK_VERSION(1,0,1)\n webViewGetZoomLevel,\n webViewSetZoomLevel,\n#endif\n webViewZoomIn,\n webViewZoomOut,\n webViewGetFullContentZoom,\n#if WEBKIT_CHECK_VERSION(1,0,1)\n webViewSetFullContentZoom,\n#endif\n-- ** Clipboard\n webViewCanCutClipboard,\n webViewCanCopyClipboard,\n webViewCanPasteClipboard,\n webViewCutClipboard,\n webViewCopyClipboard,\n webViewPasteClipboard,\n-- ** Undo\/Redo\n#if WEBKIT_CHECK_VERSION (1,1,14)\n webViewCanRedo,\n webViewCanUndo,\n webViewRedo,\n webViewUndo,\n#endif\n-- ** Selection\n webViewDeleteSelection,\n webViewHasSelection,\n webViewSelectAll,\n-- ** Encoding\n webViewGetEncoding,\n#if WEBKIT_CHECK_VERSION(1,1,1)\n webViewSetCustomEncoding,\n#endif\n webViewGetCustomEncoding,\n-- ** View Mode\n#if WEBKIT_CHECK_VERSION(1,3,4)\n webViewGetViewMode,\n webViewSetViewMode,\n#endif\n webViewGetViewSourceMode,\n#if WEBKIT_CHECK_VERSION(1,1,14)\n webViewSetViewSourceMode,\n#endif\n-- ** Transparent\n webViewGetTransparent,\n webViewSetTransparent,\n-- ** Target List\n webViewGetCopyTargetList,\n webViewGetPasteTargetList,\n-- ** Text Match\n webViewMarkTextMatches,\n webViewUnMarkTextMatches,\n webViewSetHighlightTextMatches,\n-- ** Icon\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewGetIconUri,\n#endif\n#if WEBKIT_CHECK_VERSION (1,3,13)\n webViewTryGetFaviconPixbuf,\n#endif\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#if WEBKIT_CHECK_VERSION(1,0,3)\n webViewGetWindowFeatures,\n#endif\n\n#if WEBKIT_CHECK_VERSION(1,1,4)\n webViewGetTitle,\n webViewGetUri,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,3,1)\n webViewGetDomDocument,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,15)\n -- webViewGetHitTestResult,\n#endif\n\n#if WEBKIT_CHECK_VERSION(1,3,8)\n -- webViewGetViewportAttributes,\n#endif\n\n-- * Attributes\n#if WEBKIT_CHECK_VERSION(1,0,1)\n webViewZoomLevel,\n#endif\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#if WEBKIT_CHECK_VERSION(1,3,4)\n webViewViewMode,\n#endif\n\n-- * Signals\n-- ** Loading\n loadStarted,\n loadCommitted,\n progressChanged,\n loadFinished,\n loadError,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n iconLoaded,\n#endif\n documentLoadFinished,\n resourceRequestStarting,\n titleChanged,\n-- ** Clipboard\n copyClipboard,\n cutClipboard,\n pasteClipboard,\n-- ** Script\n consoleMessage,\n scriptAlert,\n scriptConfirm,\n scriptPrompt,\n statusBarTextChanged,\n populatePopup,\n-- ** Selection\/edition\n editingBegan,\n editingEnded,\n selectAll,\n selectionChanged,\n-- ** Decision request\n mimeTypePolicyDecisionRequested,\n navigationPolicyDecisionRequested,\n newWindowPolicyDecisionRequested,\n#if WEBKIT_CHECK_VERSION (1,1,23)\n geolocationPolicyDecisionCancelled,\n geolocationPolicyDecisionRequested,\n#endif\n-- ** Display\n -- enteringFullscreen,\n moveCursor,\n setScrollAdjustments,\n-- ** Other\n hoveringOverLink,\n createWebView,\n webViewReady,\n#if WEBKIT_CHECK_VERSION(1,1,11)\n closeWebView,\n#endif\n printRequested,\n databaseQuotaExceeded,\n downloadRequested,\n redo,\n undo,\n) where\n\nimport Control.Monad (liftM, (<=<))\nimport Data.ByteString (ByteString, useAsCString)\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} deriving(Eq, Show) #}\n{#enum WebViewTargetInfo as TargetInfo {underscoreToCase} deriving(Eq, Show) #}\n{#enum WebViewViewMode as ViewMode {underscoreToCase} deriving(Eq, Show) #}\n{#enum LoadStatus {underscoreToCase} deriving(Eq, Show) #}\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.\nwebViewSetWebSettings :: (WebViewClass self, WebSettingsClass settings) => self -> settings -> IO ()\nwebViewSetWebSettings webview websettings =\n {#call web_view_set_settings#} (toWebView webview) (toWebSettings websettings)\n\n-- | Return the 'WebSettings' currently used by 'WebView'.\nwebViewGetWebSettings :: WebViewClass self => self -> IO WebSettings\nwebViewGetWebSettings = makeNewGObject mkWebSettings . {#call web_view_get_settings#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,0,3)\n-- | Returns the instance of WebKitWebWindowFeatures held by the given WebKitWebView.\nwebViewGetWindowFeatures :: WebViewClass self => self -> IO WebWindowFeatures\nwebViewGetWindowFeatures = makeNewGObject mkWebWindowFeatures . {#call web_view_get_window_features#} . toWebView\n#endif\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, GlibString string) => self -> IO (Maybe string)\nwebViewGetIconUri webview =\n {#call webkit_web_view_get_icon_uri #} (toWebView webview)\n >>= maybePeek peekUTFString\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,3,13)\n-- | Obtains a GdkPixbuf of the favicon for the given 'WebView'.\n-- This will return @Nothing@ if there is no icon for the current 'WebView' or if the icon is in the database but not available at the moment of this call.\n-- Use 'webViewGetIconUri' if you need to distinguish these cases.\n--\n-- Usually you want to connect to WebKitWebView::icon-loaded and call this method in the callback.\n--\n-- See also 'faviconDatabaseTryGetFaviconPixbuf'. Contrary to this function the icon database one returns the URL of the page containing the icon.\nwebViewTryGetFaviconPixbuf ::\n WebView\n -> Int -- ^ the desired width for the icon\n -> Int -- ^ the desired height for the icon\n -> IO (Maybe Pixbuf) -- ^ a new reference to a 'Pixbuf', or @Nothing@.\nwebViewTryGetFaviconPixbuf webView width length = do\n faviconPtr <- {#call webkit_web_view_try_get_favicon_pixbuf#} webView (fromIntegral width) (fromIntegral length)\n if faviconPtr == nullPtr then return Nothing else liftM Just . makeNewGObject mkPixbuf $ return faviconPtr\n#endif\n\n\n-- | Return the main 'WebFrame' of the given 'WebView'.\nwebViewGetMainFrame :: WebViewClass self => self -> IO WebFrame\nwebViewGetMainFrame = makeNewGObject mkWebFrame . {#call web_view_get_main_frame#} . toWebView\n\n\n-- | Return the focused 'WebFrame' (if any) of the given 'WebView'.\nwebViewGetFocusedFrame :: WebViewClass self => self -> IO (Maybe WebFrame)\nwebViewGetFocusedFrame webView = do\n framePtr <- {#call web_view_get_focused_frame#} $ toWebView webView\n if framePtr == nullPtr then return Nothing else liftM Just . makeNewGObject mkWebFrame $ return framePtr\n\n#if WEBKIT_CHECK_VERSION(1,1,1)\n-- | Requests loading of the specified URI string in a 'WebView'\nwebViewLoadUri :: (WebViewClass self, GlibString string) => self -> string -> IO ()\nwebViewLoadUri webview url = withUTFString url $ {#call web_view_load_uri#} (toWebView webview)\n#endif\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 :: WebViewClass self => self -> IO ()\nwebViewGoBack = {#call web_view_go_back#} . toWebView\n\n-- | Loads the next history item.\nwebViewGoForward :: WebViewClass self => self -> IO ()\nwebViewGoForward = {#call web_view_go_forward#} . toWebView\n\n-- | Set the 'WebView' to maintian a back or forward list of history items.\nwebViewSetMaintainsBackForwardList :: 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#} (toWebView webview) (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'\nwebViewGoToBackForwardItem :: (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\nwebViewCanGoBackOrForward :: 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, 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-- Negative values represent steps backward while positive values represent steps forward.\nwebViewGoBackOrForward :: WebViewClass self => self -> Int -> IO ()\nwebViewGoBackOrForward webview steps = {#call web_view_go_back_or_forward#} (toWebView webview) (fromIntegral steps)\n\n#if WEBKIT_CHECK_VERSION (1,1,14)\n-- | Determines whether or not it is currently possible to redo the last editing command in the view\nwebViewCanRedo :: WebViewClass self => self -> IO Bool\nwebViewCanRedo = liftM toBool . {#call web_view_can_redo#} . toWebView\n\n-- | Determines whether or not it is currently possible to undo the last editing command in the view\nwebViewCanUndo :: WebViewClass self => self -> IO Bool\nwebViewCanUndo = liftM toBool . {#call web_view_can_undo#} . toWebView\n\n-- | Redoes the last editing command in the view, if possible.\nwebViewRedo :: WebViewClass self => self -> IO ()\nwebViewRedo = {#call web_view_redo#} . toWebView\n\n-- | Undoes the last editing command in the view, if possible.\nwebViewUndo :: WebViewClass self => self -> IO ()\nwebViewUndo = {#call web_view_undo#} . toWebView\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,0,3)\n-- | Returns whether or not a @mimetype@ can be displayed using this view.\nwebViewCanShowMimeType :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @mimetype@ - a MIME type\n -> IO Bool -- ^ True if the @mimetype@ can be displayed, otherwise False\nwebViewCanShowMimeType webview mime = withUTFString mime $ liftM toBool . {#call web_view_can_show_mime_type#} (toWebView webview)\n#endif\n\n-- | Returns whether the user is allowed to edit the document.\nwebViewGetEditable :: WebViewClass self => self -> IO Bool\nwebViewGetEditable = liftM toBool . {#call web_view_get_editable#} . toWebView\n\n-- | Sets whether allows the user to edit its HTML document.\nwebViewSetEditable :: WebViewClass self => self -> Bool -> IO ()\nwebViewSetEditable webview editable = {#call web_view_set_editable#} (toWebView webview) (fromBool editable)\n\n#if WEBKIT_CHECK_VERSION(1,3,4)\n-- | Gets the value of the \"view-mode\" property of the 'WebView'\nwebViewGetViewMode :: WebViewClass self => self -> IO ViewMode\nwebViewGetViewMode = liftM (toEnum . fromIntegral) . {#call web_view_get_view_source_mode#} . toWebView\n\nwebViewSetViewMode :: WebViewClass self => self -> ViewMode -> IO ()\nwebViewSetViewMode (toWebView -> webView) viewMode = {#call web_view_set_view_source_mode#} webView (fromIntegral . fromEnum $ viewMode)\n#endif\n\n-- | Returns whether 'WebView' is in view source mode\nwebViewGetViewSourceMode :: WebViewClass self => self -> IO Bool\nwebViewGetViewSourceMode = liftM toBool . {#call web_view_get_view_source_mode#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,1,14)\n-- | Set whether the view should be in view source mode.\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 :: WebViewClass self => self -> Bool -> IO ()\nwebViewSetViewSourceMode webview mode =\n {#call web_view_set_view_source_mode#} (toWebView webview) (fromBool mode)\n#endif\n\n-- | Returns whether the 'WebView' has a transparent background\nwebViewGetTransparent :: WebViewClass self => self -> IO Bool\nwebViewGetTransparent = liftM toBool . {#call web_view_get_transparent#} . toWebView\n\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 :: WebViewClass self => self -> Bool -> IO ()\nwebViewSetTransparent webview trans =\n {#call web_view_set_transparent#} (toWebView webview) (fromBool trans)\n\n-- | Obtains the 'WebInspector' associated with the 'WebView'\nwebViewGetInspector :: WebViewClass self => self -> IO WebInspector\nwebViewGetInspector = makeNewGObject mkWebInspector . {#call web_view_get_inspector#} . toWebView\n\n\n#if WEBKIT_CHECK_VERSION(1,1,1)\n-- | Requests loading of the specified asynchronous client request.\n-- Creates a provisional data source that will transition to a committed data source once any data has been received.\n-- Use 'webViewStopLoading' to stop the load.\nwebViewLoadRequest :: (WebViewClass self, NetworkRequestClass request) => self -> request -> IO()\nwebViewLoadRequest webview request = {#call web_view_load_request#} (toWebView webview) (toNetworkRequest request)\n#endif\n\n\n#if WEBKIT_CHECK_VERSION(1,0,1)\n-- | Returns the zoom level of 'WebView'\n-- i.e. the factor by which elements in the page are scaled with respect to their original size.\nwebViewGetZoomLevel :: WebViewClass self => self -> IO Float\nwebViewGetZoomLevel = liftM realToFrac . {#call web_view_get_zoom_level#} . toWebView\n\n-- | Sets the zoom level of 'WebView'.\nwebViewSetZoomLevel :: 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#endif\n\n\n-- | Loading the @content@ string as html. The URI passed in base_uri has to be an absolute URI.\n-- Deprecated since webkit v1.1.1, use 'webViewLoadString' instead.\nwebViewLoadHtmlString :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @content@ - the html string\n -> string -- ^ @base_uri@ - the base URI\n -> IO()\nwebViewLoadHtmlString webview htmlstr url = withUTFString htmlstr $ \\htmlPtr -> withUTFString 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@ and @base_uri@.\n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n-- If want control over the encoding use `webViewLoadByteString`\nwebViewLoadString :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @content@ - the content string to be loaded.\n -> (Maybe string) -- ^ @mime_type@ - the MIME type or @Nothing@.\n -> string -- ^ @base_uri@ - the base URI for relative locations.\n -> IO ()\nwebViewLoadString webview content mimetype baseuri =\n withUTFString content $ \\contentPtr ->\n maybeWith withUTFString mimetype $ \\mimetypePtr ->\n withUTFString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#}\n (toWebView webview)\n contentPtr\n mimetypePtr\n nullPtr\n baseuriPtr\n\n-- | Requests loading of the given @content@ with the specified @mime_type@, @encoding@ and @base_uri@.\n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n-- If @encoding@ is @Nothing@, \"UTF-8\" is assumed.\nwebViewLoadByteString :: (WebViewClass self, GlibString string) => self\n -> ByteString -- ^ @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 ()\nwebViewLoadByteString webview content mimetype encoding baseuri =\n useAsCString content $ \\contentPtr ->\n maybeWith withUTFString mimetype $ \\mimetypePtr ->\n maybeWith withUTFString encoding $ \\encodingPtr ->\n withUTFString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#}\n (toWebView webview)\n contentPtr\n mimetypePtr\n encodingPtr\n baseuriPtr\n\n#if WEBKIT_CHECK_VERSION(1,1,4)\n-- | Returns the title of 'WebView' document, or Nothing in case of failure\nwebViewGetTitle :: (WebViewClass self, GlibString string) => self -> IO (Maybe string)\nwebViewGetTitle = maybePeek peekUTFString <=< {#call web_view_get_title#} . toWebView\n\n-- | Returns the current URI of the contents displayed by the 'WebView', or Nothing in case of failure\nwebViewGetUri :: (WebViewClass self, GlibString string) => self -> IO (Maybe string)\nwebViewGetUri = maybePeek peekUTFString <=< {#call web_view_get_uri#} . toWebView\n#endif\n\n\n-- | Stops and pending loads on the given data source.\nwebViewStopLoading :: WebViewClass self => self -> IO ()\nwebViewStopLoading = {#call web_view_stop_loading#} . toWebView\n\n-- | Reloads the 'WebView'\nwebViewReload :: WebViewClass self => self -> IO ()\nwebViewReload = {#call web_view_reload#} . toWebView\n\n-- | Reloads the 'WebView' without using any cached data.\nwebViewReloadBypassCache :: WebViewClass self => self -> IO ()\nwebViewReloadBypassCache = {#call web_view_reload_bypass_cache#} . toWebView\n\n-- | Increases the zoom level of 'WebView'.\nwebViewZoomIn :: WebViewClass self => self -> IO()\nwebViewZoomIn = {#call web_view_zoom_in#} . toWebView\n\n-- | Decreases the zoom level of 'WebView'.\nwebViewZoomOut :: WebViewClass self => self -> IO ()\nwebViewZoomOut = {#call web_view_zoom_out#} . toWebView\n\n-- | Looks for a specified string inside 'WebView'\nwebViewSearchText :: (WebViewClass self, GlibString string) => 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 after reaching the end\n -> IO Bool -- ^ True on success or False on failure\nwebViewSearchText webview text case_sensitive forward wrap =\n withUTFString text $ \\textPtr ->\n liftM 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 :: (WebViewClass self, GlibString string) => 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 = withUTFString text $ \\textPtr -> liftM fromIntegral $\n {#call web_view_mark_text_matches#} (toWebView webview) textPtr (fromBool case_sensitive) (fromIntegral limit)\n\n-- | Move the cursor in view as described by step and count.\nwebViewMoveCursor :: WebViewClass self => self -> MovementStep -> Int -> 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 :: WebViewClass self => self -> IO ()\nwebViewUnMarkTextMatches = {#call web_view_unmark_text_matches#} . toWebView\n\n-- | Highlights text matches previously marked by 'webViewMarkTextMatches'\nwebViewSetHighlightTextMatches :: WebViewClass self => self\n -> Bool -- ^ @highlight@ - whether to highlight text matches\n -> IO ()\nwebViewSetHighlightTextMatches webview highlight =\n {#call web_view_set_highlight_text_matches#} (toWebView webview) (fromBool highlight)\n\n-- | Execute the script specified by @script@\nwebViewExecuteScript :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @script@ - script to be executed\n -> IO()\nwebViewExecuteScript webview script = withUTFString script $ {#call web_view_execute_script#} (toWebView webview)\n\n-- | Determines whether can cuts the current selection inside 'WebView' to the clipboard\nwebViewCanCutClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanCutClipboard = liftM toBool . {#call web_view_can_cut_clipboard#} . toWebView\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 = {#call web_view_paste_clipboard#} . toWebView\n\n-- | Deletes the current selection inside the 'WebView'\nwebViewDeleteSelection :: WebViewClass self => self -> IO ()\nwebViewDeleteSelection = {#call web_view_delete_selection#} . toWebView\n\n-- | Determines whether text was selected\nwebViewHasSelection :: WebViewClass self => self -> IO Bool\nwebViewHasSelection = liftM toBool . {#call web_view_has_selection#} . toWebView\n\n-- | Attempts to select everything inside the 'WebView'\nwebViewSelectAll :: WebViewClass self => self -> IO ()\nwebViewSelectAll = {#call web_view_select_all#} . toWebView\n\n-- | Returns whether the zoom level affects only text or all elements.\nwebViewGetFullContentZoom :: 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 = liftM toBool . {#call web_view_get_full_content_zoom#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,0,1)\n-- | Sets whether the zoom level affects only text or all elements.\nwebViewSetFullContentZoom :: 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#endif\n\n-- | Returns the default encoding of the 'WebView'\nwebViewGetEncoding :: (WebViewClass self, GlibString string) => self\n -> IO (Maybe string) -- ^ the default encoding or @Nothing@ in case of failed\nwebViewGetEncoding webview = {#call web_view_get_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n#if WEBKIT_CHECK_VERSION(1,1,1)\n-- | Sets the current 'WebView' encoding,\n-- without modifying the default one, and reloads the page\nwebViewSetCustomEncoding :: (WebViewClass self, GlibString string) => self\n -> (Maybe string) -- ^ @encoding@ - the new encoding, or @Nothing@ to restore the default encoding.\n -> IO ()\nwebViewSetCustomEncoding webview encoding =\n maybeWith withUTFString encoding $ \\encodingPtr ->\n {#call web_view_set_custom_encoding#} (toWebView webview) encodingPtr\n#endif\n\n-- | Returns the current encoding of 'WebView',not the default encoding.\nwebViewGetCustomEncoding :: (WebViewClass self, GlibString string) => self\n -> IO (Maybe string) -- ^ the current encoding string or @Nothing@ if there is none set.\nwebViewGetCustomEncoding = maybePeek peekUTFString <=< {#call web_view_get_custom_encoding#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,1,7)\n-- | Determines the current status of the load.\nwebViewGetLoadStatus :: WebViewClass self => self -> IO LoadStatus\nwebViewGetLoadStatus = liftM (toEnum . fromIntegral) . {#call web_view_get_load_status#} . toWebView\n#endif\n\n-- | Determines the current progress of the load\nwebViewGetProgress :: WebViewClass self => self\n -> IO Double -- ^ the load progress\nwebViewGetProgress = liftM realToFrac . {#call web_view_get_progress#} . toWebView\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 :: WebViewClass self => self -> 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 :: WebViewClass self => self -> IO (Maybe TargetList)\nwebViewGetPasteTargetList = maybePeek mkTargetList <=< {#call web_view_get_paste_target_list#} . toWebView\n\n-- * Attibutes\n\n#if WEBKIT_CHECK_VERSION(1,0,1)\n-- | Zoom level of the 'WebView' instance\nwebViewZoomLevel :: WebViewClass self => Attr self Float\nwebViewZoomLevel = newAttrFromFloatProperty \"zoom-level\"\n#endif\n\n-- | Whether the full content is scaled when zooming\n--\n-- Default value: False\nwebViewFullContentZoom :: WebViewClass self => Attr self Bool\nwebViewFullContentZoom = newAttrFromBoolProperty \"full-content-zoom\"\n\n-- | The default encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewEncoding :: (WebViewClass self, GlibString string) => ReadAttr self (Maybe string)\nwebViewEncoding = readAttrFromMaybeStringProperty \"encoding\"\n\n-- | Determines the current status of the load.\n--\n-- Default value: @LoadFinished@\nwebViewLoadStatus :: WebViewClass self => ReadAttr self LoadStatus\nwebViewLoadStatus = readAttrFromEnumProperty \"load-status\" {#call pure unsafe webkit_load_status_get_type#}\n\n-- |Determines the current progress of the load\n--\n-- Default Value: 1\nwebViewProgress :: WebViewClass self => ReadAttr self Double\nwebViewProgress = readAttrFromDoubleProperty \"progress\"\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, GlibString string) => ReadAttr self (Maybe string)\nwebViewTitle = readAttrFromMaybeStringProperty \"title\"\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, GlibString string) => Attr self (Maybe string)\nwebViewCustomEncoding = newAttrFromMaybeStringProperty \"custom-encoding\"\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 = newAttrFromBoolProperty \"transparent\"\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 = newAttrFromBoolProperty \"editable\"\n\n-- | Returns the current URI of the contents displayed by the @web_view@.\n--\n-- Default value: Nothing\nwebViewUri :: (WebViewClass self, GlibString string) => ReadAttr self (Maybe string)\nwebViewUri = readAttrFromMaybeStringProperty \"uri\"\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, GlibString string) => ReadAttr self (Maybe string)\nwebViewIconUri = readAttrFromMaybeStringProperty \"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#if WEBKIT_CHECK_VERSION(1,3,4)\n-- | The \"view-mode\" property of the 'WebView'\nwebViewViewMode :: (WebViewClass self) => Attr self ViewMode\nwebViewViewMode = newAttr\n webViewGetViewMode\n webViewSetViewMode\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,3,1)\nwebViewGetDomDocument :: WebView -> IO (Maybe Document)\nwebViewGetDomDocument webView = do\n docPtr <- {#call webkit_web_view_get_dom_document#} webView\n if docPtr == nullPtr then return Nothing else liftM Just . makeNewGObject mkDocument $ return docPtr\n#endif\n\n\n-- #if WEBKIT_CHECK_VERSION (1,1,15)\n-- -- | Does a \"hit test\" in the coordinates specified by @event@ to figure out context information about that position in the @web_view@.\n-- webViewGetHitTestResult ::\n-- WebView -- ^ @web_view\n-- -> EventButton -- ^ @event@\n-- -> IO HitTestResult\n-- webViewGetHitTestResult webView eventButton = makeNewGObject mkHitTestResult $ {#call webkit_web_view_get_hit_test_result#} webView eventButton\n-- #endif\n\n\n-- #if WEBKIT_CHECK_VERSION(1,3,8)\n-- -- | Obtains the 'ViewportAttributes' associated with the 'WebView'.\n-- -- Do note however that the viewport attributes object only contains valid information when the current page has a viewport meta tag.\n-- -- You can check whether the data should be used by checking the \"valid\" property.\n-- webViewGetViewportAttributes :: WebView -> IO ViewportAttributes\n-- webViewGetViewportAttributes = makeNewGObject mkViewportAttributes . {#call webkit_web_view_get_viewport_attributes#}\n-- #endif\n\n\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-- webframe - which 'WebFrame' changes the document title.\n--\n-- title - current title string.\ntitleChanged :: (WebViewClass self, GlibString string) => Signal self ( WebFrame -> string -> IO() )\ntitleChanged = Signal (connect_OBJECT_GLIBSTRING__NONE \"title_changed\")\n\n\n-- | When the cursor is over a link, this signal is emitted.\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, GlibString string) => Signal self (Maybe string -> Maybe string -> IO())\nhoveringOverLink = Signal (connect_MGLIBSTRING_MGLIBSTRING__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 = Signal (connect_INT__NONE \"load_progress_changed\")\n\n-- | When loading finished, this signal is emitted\nloadFinished :: WebViewClass self => Signal self (WebFrame -> IO())\nloadFinished = 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, GlibString string) => Signal self (WebFrame -> string -> GError -> IO Bool)\nloadError = Signal (connect_OBJECT_GLIBSTRING_BOXED__BOOL \"load_error\" peek)\n\ncreateWebView :: WebViewClass self => Signal self (WebFrame -> IO WebView)\ncreateWebView = Signal (connect_OBJECT__OBJECTPTR \"create_web_view\")\n\n#if WEBKIT_CHECK_VERSION(1,1,11)\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 = Signal (connect_NONE__BOOL \"close_web_view\")\n#endif\n\n-- | A JavaScript console message was created.\nconsoleMessage :: (WebViewClass self, GlibString string) => Signal self (string -> string -> Int -> string -> IO Bool)\nconsoleMessage = Signal (connect_GLIBSTRING_GLIBSTRING_INT_GLIBSTRING__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, GlibString string) => Signal self (WebFrame -> string -> IO Bool)\nscriptAlert = Signal (connect_OBJECT_GLIBSTRING__BOOL \"script_alert\")\n\n-- | A JavaScript confirm dialog was created, providing Yes and No buttons.\nscriptConfirm :: (WebViewClass self, GlibString string) => Signal self (WebFrame -> string -> IO Bool)\nscriptConfirm = Signal (connect_OBJECT_GLIBSTRING__BOOL \"script_confirm\")\n\n-- | A JavaScript prompt dialog was created, providing an entry to input text.\nscriptPrompt :: (WebViewClass self, GlibString string) => Signal self (WebFrame -> string -> string -> IO Bool)\nscriptPrompt = Signal (connect_OBJECT_GLIBSTRING_GLIBSTRING__BOOL \"script_prompt\")\n\n-- | When status-bar text changed, this signal will emitted.\nstatusBarTextChanged :: (WebViewClass self, GlibString string) => Signal self (string -> IO ())\nstatusBarTextChanged = Signal (connect_GLIBSTRING__NONE \"status_bar_text_changed\")\n\n\neditingBegan :: WebViewClass self => Signal self (IO ())\neditingBegan = Signal (connect_NONE__NONE \"editing_began\")\n\n\neditingEnded :: WebViewClass self => Signal self (IO ())\neditingEnded = Signal (connect_NONE__NONE \"editing_ended\")\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, GlibString string) => Signal self (string -> IO ())\niconLoaded =\n Signal (connect_GLIBSTRING__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 = 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 = 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, GlibString string) => Signal self (WebFrame -> NetworkRequest -> string -> WebPolicyDecision -> IO Bool)\nmimeTypePolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_GLIBSTRING_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 Bool)\ngeolocationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT__BOOL \"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 be bound now,\n-- because it needs JavaScriptCore that hasn't binding.\n--\n-- Signal `create-plugin-widget` can't be bound now,\n-- no idea how to bind `GHaskellTable`\n--\n--\n-- * TODO:\n--\n-- Binding for webkit_web_view_get_snapshot\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebView (\n-- * Description\n-- | Cf http:\/\/webkitgtk.org\/reference\/webkitgtk\/stable\/webkitgtk-webkitwebview.html.\n\n-- * Types\n WebView,\n WebViewClass,\n\n-- * Enums\n NavigationResponse(..),\n TargetInfo(..),\n LoadStatus(..),\n ViewMode(..),\n\n-- * Constructors\n webViewNew,\n\n-- * Methods\n-- ** Load\n#if WEBKIT_CHECK_VERSION(1,1,1)\n webViewLoadUri,\n#endif\n webViewLoadHtmlString,\n#if WEBKIT_CHECK_VERSION(1,1,1)\n webViewLoadRequest,\n#endif\n webViewLoadString,\n#if WEBKIT_CHECK_VERSION(1,1,7)\n webViewGetLoadStatus,\n#endif\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#if WEBKIT_CHECK_VERSION(1,0,1)\n webViewGetZoomLevel,\n webViewSetZoomLevel,\n#endif\n webViewZoomIn,\n webViewZoomOut,\n webViewGetFullContentZoom,\n#if WEBKIT_CHECK_VERSION(1,0,1)\n webViewSetFullContentZoom,\n#endif\n-- ** Clipboard\n webViewCanCutClipboard,\n webViewCanCopyClipboard,\n webViewCanPasteClipboard,\n webViewCutClipboard,\n webViewCopyClipboard,\n webViewPasteClipboard,\n-- ** Undo\/Redo\n#if WEBKIT_CHECK_VERSION (1,1,14)\n webViewCanRedo,\n webViewCanUndo,\n webViewRedo,\n webViewUndo,\n#endif\n-- ** Selection\n webViewDeleteSelection,\n webViewHasSelection,\n webViewSelectAll,\n-- ** Encoding\n webViewGetEncoding,\n#if WEBKIT_CHECK_VERSION(1,1,1)\n webViewSetCustomEncoding,\n#endif\n webViewGetCustomEncoding,\n-- ** View Mode\n#if WEBKIT_CHECK_VERSION(1,3,4)\n webViewGetViewMode,\n webViewSetViewMode,\n#endif\n webViewGetViewSourceMode,\n#if WEBKIT_CHECK_VERSION(1,1,14)\n webViewSetViewSourceMode,\n#endif\n-- ** Transparent\n webViewGetTransparent,\n webViewSetTransparent,\n-- ** Target List\n webViewGetCopyTargetList,\n webViewGetPasteTargetList,\n-- ** Text Match\n webViewMarkTextMatches,\n webViewUnMarkTextMatches,\n webViewSetHighlightTextMatches,\n-- ** Icon\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewGetIconUri,\n#endif\n#if WEBKIT_CHECK_VERSION (1,3,13)\n webViewTryGetFaviconPixbuf,\n#endif\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#if WEBKIT_CHECK_VERSION(1,0,3)\n webViewGetWindowFeatures,\n#endif\n\n#if WEBKIT_CHECK_VERSION(1,1,4)\n webViewGetTitle,\n webViewGetUri,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,3,1)\n webViewGetDomDocument,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,15)\n -- webViewGetHitTestResult,\n#endif\n\n#if WEBKIT_CHECK_VERSION(1,3,8)\n -- webViewGetViewportAttributes,\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#if WEBKIT_CHECK_VERSION (1,1,20)\n webViewImContext,\n#endif\n\n-- * Signals\n-- ** Loading\n loadStarted,\n loadCommitted,\n progressChanged,\n loadFinished,\n loadError,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n iconLoaded,\n#endif\n documentLoadFinished,\n resourceRequestStarting,\n titleChanged,\n-- ** Clipboard\n copyClipboard,\n cutClipboard,\n pasteClipboard,\n-- ** Script\n consoleMessage,\n scriptAlert,\n scriptConfirm,\n scriptPrompt,\n statusBarTextChanged,\n populatePopup,\n-- ** Selection\/edition\n editingBegan,\n editingEnded,\n selectAll,\n selectionChanged,\n-- ** Decision request\n mimeTypePolicyDecisionRequested,\n navigationPolicyDecisionRequested,\n newWindowPolicyDecisionRequested,\n#if WEBKIT_CHECK_VERSION (1,1,23)\n geolocationPolicyDecisionCancelled,\n geolocationPolicyDecisionRequested,\n#endif\n-- ** Display\n -- enteringFullscreen,\n moveCursor,\n setScrollAdjustments,\n-- ** Other\n hoveringOverLink,\n createWebView,\n webViewReady,\n#if WEBKIT_CHECK_VERSION(1,1,11)\n closeWebView,\n#endif\n printRequested,\n databaseQuotaExceeded,\n downloadRequested,\n redo,\n undo,\n) where\n\nimport Control.Monad (liftM, (<=<))\nimport Data.ByteString (ByteString, useAsCString)\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} deriving(Eq, Show) #}\n{#enum WebViewTargetInfo as TargetInfo {underscoreToCase} deriving(Eq, Show) #}\n{#enum WebViewViewMode as ViewMode {underscoreToCase} deriving(Eq, Show) #}\n{#enum LoadStatus {underscoreToCase} deriving(Eq, Show) #}\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.\nwebViewSetWebSettings :: (WebViewClass self, WebSettingsClass settings) => self -> settings -> IO ()\nwebViewSetWebSettings webview websettings =\n {#call web_view_set_settings#} (toWebView webview) (toWebSettings websettings)\n\n-- | Return the 'WebSettings' currently used by 'WebView'.\nwebViewGetWebSettings :: WebViewClass self => self -> IO WebSettings\nwebViewGetWebSettings = makeNewGObject mkWebSettings . {#call web_view_get_settings#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,0,3)\n-- | Returns the instance of WebKitWebWindowFeatures held by the given WebKitWebView.\nwebViewGetWindowFeatures :: WebViewClass self => self -> IO WebWindowFeatures\nwebViewGetWindowFeatures = makeNewGObject mkWebWindowFeatures . {#call web_view_get_window_features#} . toWebView\n#endif\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, GlibString string) => self -> IO (Maybe string)\nwebViewGetIconUri webview =\n {#call webkit_web_view_get_icon_uri #} (toWebView webview)\n >>= maybePeek peekUTFString\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,3,13)\n-- | Obtains a GdkPixbuf of the favicon for the given 'WebView'.\n-- This will return @Nothing@ if there is no icon for the current 'WebView' or if the icon is in the database but not available at the moment of this call.\n-- Use 'webViewGetIconUri' if you need to distinguish these cases.\n--\n-- Usually you want to connect to WebKitWebView::icon-loaded and call this method in the callback.\n--\n-- See also 'faviconDatabaseTryGetFaviconPixbuf'. Contrary to this function the icon database one returns the URL of the page containing the icon.\nwebViewTryGetFaviconPixbuf ::\n WebView\n -> Int -- ^ the desired width for the icon\n -> Int -- ^ the desired height for the icon\n -> IO (Maybe Pixbuf) -- ^ a new reference to a 'Pixbuf', or @Nothing@.\nwebViewTryGetFaviconPixbuf webView width length = do\n faviconPtr <- {#call webkit_web_view_try_get_favicon_pixbuf#} webView (fromIntegral width) (fromIntegral length)\n if faviconPtr == nullPtr then return Nothing else liftM Just . makeNewGObject mkPixbuf $ return faviconPtr\n#endif\n\n\n-- | Return the main 'WebFrame' of the given 'WebView'.\nwebViewGetMainFrame :: WebViewClass self => self -> IO WebFrame\nwebViewGetMainFrame = makeNewGObject mkWebFrame . {#call web_view_get_main_frame#} . toWebView\n\n\n-- | Return the focused 'WebFrame' (if any) of the given 'WebView'.\nwebViewGetFocusedFrame :: WebViewClass self => self -> IO (Maybe WebFrame)\nwebViewGetFocusedFrame webView = do\n framePtr <- {#call web_view_get_focused_frame#} $ toWebView webView\n if framePtr == nullPtr then return Nothing else liftM Just . makeNewGObject mkWebFrame $ return framePtr\n\n#if WEBKIT_CHECK_VERSION(1,1,1)\n-- | Requests loading of the specified URI string in a 'WebView'\nwebViewLoadUri :: (WebViewClass self, GlibString string) => self -> string -> IO ()\nwebViewLoadUri webview url = withUTFString url $ {#call web_view_load_uri#} (toWebView webview)\n#endif\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 :: WebViewClass self => self -> IO ()\nwebViewGoBack = {#call web_view_go_back#} . toWebView\n\n-- | Loads the next history item.\nwebViewGoForward :: WebViewClass self => self -> IO ()\nwebViewGoForward = {#call web_view_go_forward#} . toWebView\n\n-- | Set the 'WebView' to maintian a back or forward list of history items.\nwebViewSetMaintainsBackForwardList :: 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#} (toWebView webview) (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'\nwebViewGoToBackForwardItem :: (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\nwebViewCanGoBackOrForward :: 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, 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-- Negative values represent steps backward while positive values represent steps forward.\nwebViewGoBackOrForward :: WebViewClass self => self -> Int -> IO ()\nwebViewGoBackOrForward webview steps = {#call web_view_go_back_or_forward#} (toWebView webview) (fromIntegral steps)\n\n#if WEBKIT_CHECK_VERSION (1,1,14)\n-- | Determines whether or not it is currently possible to redo the last editing command in the view\nwebViewCanRedo :: WebViewClass self => self -> IO Bool\nwebViewCanRedo = liftM toBool . {#call web_view_can_redo#} . toWebView\n\n-- | Determines whether or not it is currently possible to undo the last editing command in the view\nwebViewCanUndo :: WebViewClass self => self -> IO Bool\nwebViewCanUndo = liftM toBool . {#call web_view_can_undo#} . toWebView\n\n-- | Redoes the last editing command in the view, if possible.\nwebViewRedo :: WebViewClass self => self -> IO ()\nwebViewRedo = {#call web_view_redo#} . toWebView\n\n-- | Undoes the last editing command in the view, if possible.\nwebViewUndo :: WebViewClass self => self -> IO ()\nwebViewUndo = {#call web_view_undo#} . toWebView\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,0,3)\n-- | Returns whether or not a @mimetype@ can be displayed using this view.\nwebViewCanShowMimeType :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @mimetype@ - a MIME type\n -> IO Bool -- ^ True if the @mimetype@ can be displayed, otherwise False\nwebViewCanShowMimeType webview mime = withUTFString mime $ liftM toBool . {#call web_view_can_show_mime_type#} (toWebView webview)\n#endif\n\n-- | Returns whether the user is allowed to edit the document.\nwebViewGetEditable :: WebViewClass self => self -> IO Bool\nwebViewGetEditable = liftM toBool . {#call web_view_get_editable#} . toWebView\n\n-- | Sets whether allows the user to edit its HTML document.\nwebViewSetEditable :: WebViewClass self => self -> Bool -> IO ()\nwebViewSetEditable webview editable = {#call web_view_set_editable#} (toWebView webview) (fromBool editable)\n\n#if WEBKIT_CHECK_VERSION(1,3,4)\n-- | Gets the value of the \"view-mode\" property of the 'WebView'\nwebViewGetViewMode :: WebView -> IO ViewMode\nwebViewGetViewMode = liftM (toEnum . fromIntegral) . {#call web_view_get_view_source_mode#}\n\nwebViewSetViewMode :: WebView -> ViewMode -> IO ()\nwebViewSetViewMode webView viewMode = {#call web_view_set_view_source_mode#} webView (fromIntegral . fromEnum $ viewMode)\n#endif\n\n-- | Returns whether 'WebView' is in view source mode\nwebViewGetViewSourceMode :: WebViewClass self => self -> IO Bool\nwebViewGetViewSourceMode = liftM toBool . {#call web_view_get_view_source_mode#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,1,14)\n-- | Set whether the view should be in view source mode.\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 :: WebViewClass self => self -> Bool -> IO ()\nwebViewSetViewSourceMode webview mode =\n {#call web_view_set_view_source_mode#} (toWebView webview) (fromBool mode)\n#endif\n\n-- | Returns whether the 'WebView' has a transparent background\nwebViewGetTransparent :: WebViewClass self => self -> IO Bool\nwebViewGetTransparent = liftM toBool . {#call web_view_get_transparent#} . toWebView\n\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 :: WebViewClass self => self -> Bool -> IO ()\nwebViewSetTransparent webview trans =\n {#call web_view_set_transparent#} (toWebView webview) (fromBool trans)\n\n-- | Obtains the 'WebInspector' associated with the 'WebView'\nwebViewGetInspector :: WebViewClass self => self -> IO WebInspector\nwebViewGetInspector = makeNewGObject mkWebInspector . {#call web_view_get_inspector#} . toWebView\n\n\n#if WEBKIT_CHECK_VERSION(1,1,1)\n-- | Requests loading of the specified asynchronous client request.\n-- Creates a provisional data source that will transition to a committed data source once any data has been received.\n-- Use 'webViewStopLoading' to stop the load.\nwebViewLoadRequest :: (WebViewClass self, NetworkRequestClass request) => self -> request -> IO()\nwebViewLoadRequest webview request = {#call web_view_load_request#} (toWebView webview) (toNetworkRequest request)\n#endif\n\n\n#if WEBKIT_CHECK_VERSION(1,0,1)\n-- | Returns the zoom level of 'WebView'\n-- i.e. the factor by which elements in the page are scaled with respect to their original size.\nwebViewGetZoomLevel :: WebViewClass self => self -> IO Float\nwebViewGetZoomLevel = liftM realToFrac . {#call web_view_get_zoom_level#} . toWebView\n\n-- | Sets the zoom level of 'WebView'.\nwebViewSetZoomLevel :: 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#endif\n\n\n-- | Loading the @content@ string as html. The URI passed in base_uri has to be an absolute URI.\n-- Deprecated since webkit v1.1.1, use 'webViewLoadString' instead.\nwebViewLoadHtmlString :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @content@ - the html string\n -> string -- ^ @base_uri@ - the base URI\n -> IO()\nwebViewLoadHtmlString webview htmlstr url = withUTFString htmlstr $ \\htmlPtr -> withUTFString 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@ and @base_uri@.\n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n-- If want control over the encoding use `webViewLoadByteString`\nwebViewLoadString :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @content@ - the content string to be loaded.\n -> (Maybe string) -- ^ @mime_type@ - the MIME type or @Nothing@.\n -> string -- ^ @base_uri@ - the base URI for relative locations.\n -> IO ()\nwebViewLoadString webview content mimetype baseuri =\n withUTFString content $ \\contentPtr ->\n maybeWith withUTFString mimetype $ \\mimetypePtr ->\n withUTFString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#}\n (toWebView webview)\n contentPtr\n mimetypePtr\n nullPtr\n baseuriPtr\n\n-- | Requests loading of the given @content@ with the specified @mime_type@, @encoding@ and @base_uri@.\n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n-- If @encoding@ is @Nothing@, \"UTF-8\" is assumed.\nwebViewLoadByteString :: (WebViewClass self, GlibString string) => self\n -> ByteString -- ^ @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 ()\nwebViewLoadByteString webview content mimetype encoding baseuri =\n useAsCString content $ \\contentPtr ->\n maybeWith withUTFString mimetype $ \\mimetypePtr ->\n maybeWith withUTFString encoding $ \\encodingPtr ->\n withUTFString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#}\n (toWebView webview)\n contentPtr\n mimetypePtr\n encodingPtr\n baseuriPtr\n\n#if WEBKIT_CHECK_VERSION(1,1,4)\n-- | Returns the title of 'WebView' document, or Nothing in case of failure\nwebViewGetTitle :: (WebViewClass self, GlibString string) => self -> IO (Maybe string)\nwebViewGetTitle = maybePeek peekUTFString <=< {#call web_view_get_title#} . toWebView\n\n-- | Returns the current URI of the contents displayed by the 'WebView', or Nothing in case of failure\nwebViewGetUri :: (WebViewClass self, GlibString string) => self -> IO (Maybe string)\nwebViewGetUri = maybePeek peekUTFString <=< {#call web_view_get_uri#} . toWebView\n#endif\n\n\n-- | Stops and pending loads on the given data source.\nwebViewStopLoading :: WebViewClass self => self -> IO ()\nwebViewStopLoading = {#call web_view_stop_loading#} . toWebView\n\n-- | Reloads the 'WebView'\nwebViewReload :: WebViewClass self => self -> IO ()\nwebViewReload = {#call web_view_reload#} . toWebView\n\n-- | Reloads the 'WebView' without using any cached data.\nwebViewReloadBypassCache :: WebViewClass self => self -> IO ()\nwebViewReloadBypassCache = {#call web_view_reload_bypass_cache#} . toWebView\n\n-- | Increases the zoom level of 'WebView'.\nwebViewZoomIn :: WebViewClass self => self -> IO()\nwebViewZoomIn = {#call web_view_zoom_in#} . toWebView\n\n-- | Decreases the zoom level of 'WebView'.\nwebViewZoomOut :: WebViewClass self => self -> IO ()\nwebViewZoomOut = {#call web_view_zoom_out#} . toWebView\n\n-- | Looks for a specified string inside 'WebView'\nwebViewSearchText :: (WebViewClass self, GlibString string) => 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 after reaching the end\n -> IO Bool -- ^ True on success or False on failure\nwebViewSearchText webview text case_sensitive forward wrap =\n withUTFString text $ \\textPtr ->\n liftM 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 :: (WebViewClass self, GlibString string) => 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 = withUTFString text $ \\textPtr -> liftM fromIntegral $\n {#call web_view_mark_text_matches#} (toWebView webview) textPtr (fromBool case_sensitive) (fromIntegral limit)\n\n-- | Move the cursor in view as described by step and count.\nwebViewMoveCursor :: WebViewClass self => self -> MovementStep -> Int -> 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 :: WebViewClass self => self -> IO ()\nwebViewUnMarkTextMatches = {#call web_view_unmark_text_matches#} . toWebView\n\n-- | Highlights text matches previously marked by 'webViewMarkTextMatches'\nwebViewSetHighlightTextMatches :: WebViewClass self => self\n -> Bool -- ^ @highlight@ - whether to highlight text matches\n -> IO ()\nwebViewSetHighlightTextMatches webview highlight =\n {#call web_view_set_highlight_text_matches#} (toWebView webview) (fromBool highlight)\n\n-- | Execute the script specified by @script@\nwebViewExecuteScript :: (WebViewClass self, GlibString string) => self\n -> string -- ^ @script@ - script to be executed\n -> IO()\nwebViewExecuteScript webview script = withUTFString script $ {#call web_view_execute_script#} (toWebView webview)\n\n-- | Determines whether can cuts the current selection inside 'WebView' to the clipboard\nwebViewCanCutClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanCutClipboard = liftM toBool . {#call web_view_can_cut_clipboard#} . toWebView\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 = {#call web_view_paste_clipboard#} . toWebView\n\n-- | Deletes the current selection inside the 'WebView'\nwebViewDeleteSelection :: WebViewClass self => self -> IO ()\nwebViewDeleteSelection = {#call web_view_delete_selection#} . toWebView\n\n-- | Determines whether text was selected\nwebViewHasSelection :: WebViewClass self => self -> IO Bool\nwebViewHasSelection = liftM toBool . {#call web_view_has_selection#} . toWebView\n\n-- | Attempts to select everything inside the 'WebView'\nwebViewSelectAll :: WebViewClass self => self -> IO ()\nwebViewSelectAll = {#call web_view_select_all#} . toWebView\n\n-- | Returns whether the zoom level affects only text or all elements.\nwebViewGetFullContentZoom :: 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 = liftM toBool . {#call web_view_get_full_content_zoom#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,0,1)\n-- | Sets whether the zoom level affects only text or all elements.\nwebViewSetFullContentZoom :: 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#endif\n\n-- | Returns the default encoding of the 'WebView'\nwebViewGetEncoding :: (WebViewClass self, GlibString string) => self\n -> IO (Maybe string) -- ^ the default encoding or @Nothing@ in case of failed\nwebViewGetEncoding webview = {#call web_view_get_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n#if WEBKIT_CHECK_VERSION(1,1,1)\n-- | Sets the current 'WebView' encoding,\n-- without modifying the default one, and reloads the page\nwebViewSetCustomEncoding :: (WebViewClass self, GlibString string) => self\n -> (Maybe string) -- ^ @encoding@ - the new encoding, or @Nothing@ to restore the default encoding.\n -> IO ()\nwebViewSetCustomEncoding webview encoding =\n maybeWith withUTFString encoding $ \\encodingPtr ->\n {#call web_view_set_custom_encoding#} (toWebView webview) encodingPtr\n#endif\n\n-- | Returns the current encoding of 'WebView',not the default encoding.\nwebViewGetCustomEncoding :: (WebViewClass self, GlibString string) => self\n -> IO (Maybe string) -- ^ the current encoding string or @Nothing@ if there is none set.\nwebViewGetCustomEncoding = maybePeek peekUTFString <=< {#call web_view_get_custom_encoding#} . toWebView\n\n#if WEBKIT_CHECK_VERSION(1,1,7)\n-- | Determines the current status of the load.\nwebViewGetLoadStatus :: WebViewClass self => self -> IO LoadStatus\nwebViewGetLoadStatus = liftM (toEnum . fromIntegral) . {#call web_view_get_load_status#} . toWebView\n#endif\n\n-- | Determines the current progress of the load\nwebViewGetProgress :: WebViewClass self => self\n -> IO Double -- ^ the load progress\nwebViewGetProgress = liftM realToFrac . {#call web_view_get_progress#} . toWebView\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 :: WebViewClass self => self -> 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 :: WebViewClass self => self -> IO (Maybe TargetList)\nwebViewGetPasteTargetList = maybePeek mkTargetList <=< {#call web_view_get_paste_target_list#} . toWebView\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, GlibString string) => 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, GlibString string) => 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, GlibString string) => 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, GlibString string) => 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, GlibString string) => 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\n#if WEBKIT_CHECK_VERSION (1,3,1)\nwebViewGetDomDocument :: WebView -> IO (Maybe Document)\nwebViewGetDomDocument webView = do\n docPtr <- {#call webkit_web_view_get_dom_document#} webView\n if docPtr == nullPtr then return Nothing else liftM Just . makeNewGObject mkDocument $ return docPtr\n#endif\n\n\n-- #if WEBKIT_CHECK_VERSION (1,1,15)\n-- -- | Does a \"hit test\" in the coordinates specified by @event@ to figure out context information about that position in the @web_view@.\n-- webViewGetHitTestResult ::\n-- WebView -- ^ @web_view\n-- -> EventButton -- ^ @event@\n-- -> IO HitTestResult\n-- webViewGetHitTestResult webView eventButton = makeNewGObject mkHitTestResult $ {#call webkit_web_view_get_hit_test_result#} webView eventButton\n-- #endif\n\n\n-- #if WEBKIT_CHECK_VERSION(1,3,8)\n-- -- | Obtains the 'ViewportAttributes' associated with the 'WebView'.\n-- -- Do note however that the viewport attributes object only contains valid information when the current page has a viewport meta tag.\n-- -- You can check whether the data should be used by checking the \"valid\" property.\n-- webViewGetViewportAttributes :: WebView -> IO ViewportAttributes\n-- webViewGetViewportAttributes = makeNewGObject mkViewportAttributes . {#call webkit_web_view_get_viewport_attributes#}\n-- #endif\n\n\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-- webframe - which 'WebFrame' changes the document title.\n--\n-- title - current title string.\ntitleChanged :: (WebViewClass self, GlibString string) => Signal self ( WebFrame -> string -> IO() )\ntitleChanged = Signal (connect_OBJECT_GLIBSTRING__NONE \"title_changed\")\n\n\n-- | When the cursor is over a link, this signal is emitted.\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, GlibString string) => Signal self (Maybe string -> Maybe string -> IO())\nhoveringOverLink = Signal (connect_MGLIBSTRING_MGLIBSTRING__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 = Signal (connect_INT__NONE \"load_progress_changed\")\n\n-- | When loading finished, this signal is emitted\nloadFinished :: WebViewClass self => Signal self (WebFrame -> IO())\nloadFinished = 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, GlibString string) => Signal self (WebFrame -> string -> GError -> IO Bool)\nloadError = Signal (connect_OBJECT_GLIBSTRING_BOXED__BOOL \"load_error\" peek)\n\ncreateWebView :: WebViewClass self => Signal self (WebFrame -> IO WebView)\ncreateWebView = Signal (connect_OBJECT__OBJECTPTR \"create_web_view\")\n\n#if WEBKIT_CHECK_VERSION(1,1,11)\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 = Signal (connect_NONE__BOOL \"close_web_view\")\n#endif\n\n-- | A JavaScript console message was created.\nconsoleMessage :: (WebViewClass self, GlibString string) => Signal self (string -> string -> Int -> string -> IO Bool)\nconsoleMessage = Signal (connect_GLIBSTRING_GLIBSTRING_INT_GLIBSTRING__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, GlibString string) => Signal self (WebFrame -> string -> IO Bool)\nscriptAlert = Signal (connect_OBJECT_GLIBSTRING__BOOL \"script_alert\")\n\n-- | A JavaScript confirm dialog was created, providing Yes and No buttons.\nscriptConfirm :: (WebViewClass self, GlibString string) => Signal self (WebFrame -> string -> IO Bool)\nscriptConfirm = Signal (connect_OBJECT_GLIBSTRING__BOOL \"script_confirm\")\n\n-- | A JavaScript prompt dialog was created, providing an entry to input text.\nscriptPrompt :: (WebViewClass self, GlibString string) => Signal self (WebFrame -> string -> string -> IO Bool)\nscriptPrompt = Signal (connect_OBJECT_GLIBSTRING_GLIBSTRING__BOOL \"script_prompt\")\n\n-- | When status-bar text changed, this signal will emitted.\nstatusBarTextChanged :: (WebViewClass self, GlibString string) => Signal self (string -> IO ())\nstatusBarTextChanged = Signal (connect_GLIBSTRING__NONE \"status_bar_text_changed\")\n\n\neditingBegan :: WebViewClass self => Signal self (IO ())\neditingBegan = Signal (connect_NONE__NONE \"editing_began\")\n\n\neditingEnded :: WebViewClass self => Signal self (IO ())\neditingEnded = Signal (connect_NONE__NONE \"editing_ended\")\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, GlibString string) => Signal self (string -> IO ())\niconLoaded =\n Signal (connect_GLIBSTRING__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 = 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 = 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, GlibString string) => Signal self (WebFrame -> NetworkRequest -> string -> WebPolicyDecision -> IO Bool)\nmimeTypePolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_GLIBSTRING_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 Bool)\ngeolocationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT__BOOL \"geolocation_policy_decision_requested\")\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"483a4f3998f7653759f9ce3aaa0c28ad8f923c30","subject":"fixed compilation issues (unfinished code?)","message":"fixed compilation issues (unfinished code?)\n","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/Histogram.chs","new_file":"CV\/Histogram.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport C2HSTools\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype (Num a) => HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\n--histogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n-- -> I.Histogram\n\n--histogram imageBins\n-- I.creatingHistogram $ do\n-- hist <- I.emptyUniformHistogramND ds\n-- withPtrList (map imageFPTR images) $ \\ptrs ->\n-- case mask of\n-- Just m -> do\n-- withImage m $ \\c_mask -> do\n-- I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n-- return hist\n-- Nothing -> do\n-- I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n-- return hist\n-- where\n-- (images,ds) = unzip imageBins\n-- c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Ptr\nimport C2HSTools\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype (Num a) => HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs -> \n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\" \n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\n\nhistogram imageBins \n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds \n withPtrList (map imageFPTR images) $ \\ptrs -> \n case mask of\n Just m -> do \n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do \n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where \n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) -> \n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins \n-- let u2 = sum.map (\\(value,bin) -> \n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins \n---- \n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b) \nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b \n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n \n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image \n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $ \n withImage img $ \\i -> \n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start) \n (realToFrac end) \n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8) \n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount \n let isCum | cumulative == True = 1\n | cumulative == False = 0\n \n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end) \n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr) \n (realToFrac start) (realToFrac end) \n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r \n\n \n \n \n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image \n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do \n-- h <- buildHistogram cbins image \n-- values <- mapM (getBin h) \n-- [0..fromIntegral bins-1] \n-- return.HGD $ \n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3c9dd340405d1ae6c68e3f4e43af90c3e2ee9db7","subject":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM","message":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"eed32320bff3ac9adcf77cf76b225c859ad93e9a","subject":"work around c2hs #151","message":"work around c2hs #151\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/CPLError.chs","new_file":"src\/GDAL\/Internal\/CPLError.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , setQuietErrorHandler\n , throwIfError\n , throwIfError_\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Concurrent (runInBoundThread, rtsSupportsBoundThreads)\nimport Control.Exception (Exception(..), SomeException, bracket, throw)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad.Catch (MonadThrow(throwM))\n\nimport Data.IORef (newIORef, readIORef, writeIORef)\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, cast)\n\nimport Foreign.C.String (CString, peekCString)\nimport Foreign.C.Types (CInt(..), CChar(..))\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport Foreign.Ptr (Ptr, FunPtr, freeHaskellFunPtr)\n\nimport GDAL.Internal.Util (toEnumC)\n\n#include \"cpl_error.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ntype CErrorHandler = CInt -> CInt -> CString -> IO ()\n\n{#pointer ErrorHandler#}\n\ndata GDALException\n = forall e. Exception e =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !String\n }\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException :: Exception e => e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException :: Exception e => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\ninstance NFData GDALException where\n rnf a = a `seq` () -- All fields are already strict so no need to rnf them\n\nthrowBindingException :: (MonadThrow m, Exception e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\ninstance NFData ErrorType where\n rnf a = a `seq` ()\n\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: ErrorHandler\n\nsetQuietErrorHandler :: IO ErrorHandler\nsetQuietErrorHandler = {#call unsafe SetErrorHandler as ^#} c_quietErrorHandler\n\nforeign import ccall safe \"wrapper\"\n mkErrorHandler :: CErrorHandler -> IO ErrorHandler\n\nthrowIfError_ :: String -> IO a -> IO ()\nthrowIfError_ prefix act = throwIfError prefix act >> return ()\n\nthrowIfError :: String -> IO a -> IO a\nthrowIfError prefix act = do\n ref <- newIORef Nothing\n let mkHandler = mkErrorHandler $ \\err errno cmsg -> do\n msg <- peekCString cmsg\n writeIORef ref $ Just $ GDALException (toEnumC err)\n (toEnumC errno)\n (prefix ++ \": \" ++ msg)\n bracket mkHandler freeHaskellFunPtr $ \\h -> do\n ret <- runBounded $ bracket ({#call unsafe PushErrorHandler as ^#} h)\n (const {#call unsafe PopErrorHandler as ^#})\n (const act)\n readIORef ref >>= maybe (return ret) throw\n where\n runBounded\n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n","old_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , setQuietErrorHandler\n , throwIfError\n , throwIfError_\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Concurrent (runInBoundThread, rtsSupportsBoundThreads)\nimport Control.Exception (Exception(..), SomeException, bracket, throw)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad.Catch (MonadThrow(throwM))\n\nimport Data.IORef (newIORef, readIORef, writeIORef)\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, cast)\n\nimport Foreign.C.String (CString, peekCString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, freeHaskellFunPtr)\n\nimport GDAL.Internal.Util (toEnumC)\n\n#include \"cpl_error.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ntype CErrorHandler = CInt -> CInt -> CString -> IO ()\n\n{#pointer ErrorHandler#}\n\ndata GDALException\n = forall e. Exception e =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !String\n }\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException :: Exception e => e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException :: Exception e => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\ninstance NFData GDALException where\n rnf a = a `seq` () -- All fields are already strict so no need to rnf them\n\nthrowBindingException :: (MonadThrow m, Exception e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\ninstance NFData ErrorType where\n rnf a = a `seq` ()\n\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: ErrorHandler\n\nsetQuietErrorHandler :: IO ErrorHandler\nsetQuietErrorHandler = {#call unsafe SetErrorHandler as ^#} c_quietErrorHandler\n\nforeign import ccall safe \"wrapper\"\n mkErrorHandler :: CErrorHandler -> IO ErrorHandler\n\nthrowIfError_ :: String -> IO a -> IO ()\nthrowIfError_ prefix act = throwIfError prefix act >> return ()\n\nthrowIfError :: String -> IO a -> IO a\nthrowIfError prefix act = do\n ref <- newIORef Nothing\n let mkHandler = mkErrorHandler $ \\err errno cmsg -> do\n msg <- peekCString cmsg\n writeIORef ref $ Just $ GDALException (toEnumC err)\n (toEnumC errno)\n (prefix ++ \": \" ++ msg)\n bracket mkHandler freeHaskellFunPtr $ \\h -> do\n ret <- runBounded $ bracket ({#call unsafe PushErrorHandler as ^#} h)\n (const {#call unsafe PopErrorHandler as ^#})\n (const act)\n readIORef ref >>= maybe (return ret) throw\n where\n runBounded\n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0be52e8177ee63aa0a75fc4ab9983793d5125d2f","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\/CPLString.chs","new_file":"src\/GDAL\/Internal\/CPLString.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\nmodule GDAL.Internal.CPLString (\n OptionList\n , withOptionList\n , toOptionListPtr\n , fromOptionListPtr\n , peekCPLString\n) where\n\nimport Control.Exception (bracket, bracketOnError)\nimport Control.Monad (forM, foldM, liftM, when, void)\n\nimport Data.ByteString.Internal (ByteString(..))\nimport Data.Monoid (mempty)\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Word (Word8)\n\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (peek, peekElemOff)\nimport Foreign.ForeignPtr (newForeignPtr)\nimport Foreign.Marshal.Utils (with)\n\nimport GDAL.Internal.Util (useAsEncodedCString, peekEncodedCString)\nimport GDAL.Internal.CPLConv (c_cplFree, cplFree)\n\n#include \"cpl_string.h\"\n\ntype OptionList = [(Text,Text)]\n\nwithOptionList :: OptionList -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionListPtr opts) freeOptionList\n where freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ntoOptionListPtr :: OptionList -> IO (Ptr CString)\ntoOptionListPtr = foldM folder nullPtr\n where\n folder acc (k,v) =\n useAsEncodedCString k $ \\k' ->\n useAsEncodedCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n\nfromOptionListPtr :: Ptr CString -> IO OptionList\nfromOptionListPtr ptr = do\n n <- {#call unsafe CSLCount as ^#} ptr\n forM [0..n-1] $ \\ix -> do\n s <- {#call unsafe CSLGetField as ^#} ptr ix >>= peekEncodedCString\n return $ T.break (\/='=') s\n\npeekCPLString :: (Ptr CString -> IO a) -> IO ByteString\npeekCPLString act = with nullPtr $ \\pptr ->\n bracketOnError (go pptr) (const (freeIfNotNull pptr)) return\n where\n go pptr = do\n void (act pptr)\n p <- liftM castPtr (peek pptr) :: IO (Ptr Word8)\n let findLen !n = do\n v <- p `peekElemOff` n :: IO Word8\n if v==0 then return n else findLen (n+1)\n if p \/= nullPtr\n then do len <- findLen 0\n fp <- newForeignPtr c_cplFree p\n return $! PS fp 0 len\n else return mempty\n\n freeIfNotNull pptr = do\n p <- peek pptr\n when (p \/= nullPtr) (cplFree p)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\nmodule GDAL.Internal.CPLString (\n OptionList\n , withOptionList\n , toOptionListPtr\n , fromOptionListPtr\n , peekCPLString\n) where\n\nimport Control.Exception (bracket, bracketOnError)\nimport Control.Monad (forM, foldM, liftM, when, void)\n\nimport Data.ByteString.Internal (ByteString(..))\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Word (Word8)\n\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (peek, peekElemOff)\nimport Foreign.ForeignPtr (newForeignPtr)\nimport Foreign.Marshal.Utils (with)\n\nimport GDAL.Internal.Util (useAsEncodedCString, peekEncodedCString)\nimport GDAL.Internal.CPLConv (c_cplFree, cplFree)\n\n#include \"cpl_string.h\"\n\ntype OptionList = [(Text,Text)]\n\nwithOptionList :: OptionList -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionListPtr opts) freeOptionList\n where freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ntoOptionListPtr :: OptionList -> IO (Ptr CString)\ntoOptionListPtr = foldM folder nullPtr\n where\n folder acc (k,v) =\n useAsEncodedCString k $ \\k' ->\n useAsEncodedCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n\nfromOptionListPtr :: Ptr CString -> IO OptionList\nfromOptionListPtr ptr = do\n n <- {#call unsafe CSLCount as ^#} ptr\n forM [0..n-1] $ \\ix -> do\n s <- {#call unsafe CSLGetField as ^#} ptr ix >>= peekEncodedCString\n return $ T.break (\/='=') s\n\npeekCPLString :: (Ptr CString -> IO a) -> IO ByteString\npeekCPLString act = with nullPtr $ \\pptr ->\n bracketOnError (go pptr) (const (freeIfNotNull pptr)) return\n where\n go pptr = do\n void (act pptr)\n p <- liftM castPtr (peek pptr) :: IO (Ptr Word8)\n let findLen !n = do\n v <- p `peekElemOff` n :: IO Word8\n if v==0 then return n else findLen (n+1)\n if p \/= nullPtr\n then do len <- findLen 0\n fp <- newForeignPtr c_cplFree p\n return $! PS fp 0 len\n else return mempty\n\n freeIfNotNull pptr = do\n p <- peek pptr\n when (p \/= nullPtr) (cplFree p)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"101bf7caeda1a0fc3a3646017317590da1abafb0","subject":"Must not use _static version of pango_font_description_set_family Since the string buffer is only kept around temporarily, not forever like pango_font_description_set_family_static requires.","message":"Must not use _static version of pango_font_description_set_family\nSince the string buffer is only kept around temporarily, not forever like\npango_font_description_set_family_static requires.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\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-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions to manage font descriptions.\n--\n-- * Font descriptions provide a way to query and state requirements on\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n FontMask(..),\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#} ()\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family_static#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- | Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleOblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Double -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (puToInt p)\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Double)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (intToPu x)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns @True@ if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns @False@.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- @[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]@ where @FAMILY_LIST@ is a comma\n-- separated list of font families optionally terminated by a comma,\n-- @STYLE_OPTIONS@ is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. @SIZE@ is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"028e3f540662412ae92ad5f6b4a9f20a8b3ce290","subject":"Fix for older versions of webkit","message":"Fix for older versions of webkit\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/StorageInfo.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/StorageInfo.chs","new_contents":"module Graphics.UI.Gtk.WebKit.DOM.StorageInfo\n (\n#if WEBKIT_CHECK_VERSION(1,10,0)\n cTEMPORARY, cPERSISTENT, StorageInfo, StorageInfoClass,\n castToStorageInfo, gTypeStorageInfo, toStorageInfo\n#endif\n ) where\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Graphics.UI.Gtk.WebKit.DOM.EventM\ncTEMPORARY = 0\ncPERSISTENT = 1\n","old_contents":"module Graphics.UI.Gtk.WebKit.DOM.StorageInfo\n (cTEMPORARY, cPERSISTENT, StorageInfo, StorageInfoClass,\n castToStorageInfo, gTypeStorageInfo, toStorageInfo)\n where\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Graphics.UI.Gtk.WebKit.DOM.EventM\ncTEMPORARY = 0\ncPERSISTENT = 1\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"c9ed64999819a2e28fd710c63a904e41521c9d20","subject":"[project @ 2003-01-18 17:44:07 by as49] Move Plug.chs to ..\/embedding. It makes more sense and makes building on Windows easier.","message":"[project @ 2003-01-18 17:44:07 by as49]\nMove Plug.chs to ..\/embedding. It makes more sense and makes building on\nWindows easier.\n","repos":"vincenthz\/webkit","old_file":"gtk\/windows\/Plug.chs","new_file":"gtk\/windows\/Plug.chs","new_contents":"","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Plug@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/08\/05 16:41:35 $\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-- * Plug is a window that is to be attached to the window of another\n-- application. If you have managed to receive the @ref type XID@ from\n-- the inviting application you can construct the Plug and add your widgets\n-- to it.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Plug(\n Plug,\n PlugClass,\n castToPlug,\n XID,\n plugNew\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs\t(XID)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\nplugNew :: XID -> IO Plug\nplugNew nw = makeNewObject mkPlug $ liftM castPtr $\n {#call unsafe plug_new#} nw\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e8dab68acdf7d00fc9d33537317786a13dc8197e","subject":"fix warning for ghc >= 7.2","message":"fix warning for ghc >= 7.2\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) [2009..2011] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error (\n\n Status(..), CUDAException(..),\n\n cudaError, describe, requireSDK,\n resultIfOk, nothingIfOk\n\n) where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign hiding ( unsafePerformIO )\nimport Foreign.C\nimport Data.Typeable\nimport Control.Exception.Extensible\nimport System.IO.Unsafe\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n-- |\n-- Return codes from API functions\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- A specially formatted error message\n--\nrequireSDK :: Double -> String -> IO a\nrequireSDK v s = cudaError (\"'\" ++ s ++ \"' requires at least cuda-\" ++ show v)\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorStringWrapper as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the 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-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) [2009..2011] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error (\n\n Status(..), CUDAException(..),\n\n cudaError, describe, requireSDK,\n resultIfOk, nothingIfOk\n\n) where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Typeable\nimport Control.Exception.Extensible\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n-- |\n-- Return codes from API functions\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- A specially formatted error message\n--\nrequireSDK :: Double -> String -> IO a\nrequireSDK v s = cudaError (\"'\" ++ s ++ \"' requires at least cuda-\" ++ show v)\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorStringWrapper as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the 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-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\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":"94767539707006160afef110beebb43a7f264051","subject":"expose Types and flags constructors in System.GIO.File","message":"expose Types and flags constructors in System.GIO.File\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/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-- \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":"baf5289af641eeb3c4eac1c362e75c85310bbc3a","subject":"[project @ 2002-07-08 09:13:09 by as49] Changed the type of eventsPending to the propper one.","message":"[project @ 2002-07-08 09:13:09 by as49]\nChanged the type of eventsPending to the propper one.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/webkit","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:13:09 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/05\/24 09:43:24 $\n--\n-- Copyright (c) [1998..2001] Manuel M. T. Chakravarty\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-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Bool\neventsPending = liftM toBool {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"ea9c80bba46bb15dfd49cbb95a2f0d0f41d02348","subject":"[project @ 2002-12-16 16:27:14 by as49] Removed an empty line.","message":"[project @ 2002-12-16 16:27:14 by as49]\nRemoved an empty line.\n\n","repos":"gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General@\n--\n-- Author : Axel Simon\n--\t Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.9 $ from $Date: 2002\/12\/16 16:27:14 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\nmodule General(\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport LocalData(newIORef, readIORef, writeIORef)\nimport Exception (ioError, Exception(ErrorCall))\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @function getDefaultLanguage@ 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 <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @function initGUI@ 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: @literal ErrorCall \"Cannot initialize GUI.\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\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 peekCString addrs'\n else ioError (ErrorCall \"Cannot initialize GUI.\")\n\n-- @function eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @function mainGUI@ Run GTK+'s main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- @function mainLevel@ Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call \n-- @ref function loopIteration@ to keep the GUI responsive. Each time\n-- the main loop is restarted this way, the main loop counter is\n-- increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @function mainQuit@ Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @function mainIteration@ Process an event, block if necessary.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @function mainIterationDo@ Process a single event.\n--\n-- * Called with @literal True@, this function behaves as\n-- @ref function loopIteration@ in that it waits until an event is available\n-- for processing. The function will return immediately, if passed\n-- @literal False@.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\n\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @function grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @function grabGetCurrent@ 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-- @function grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @function timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @function timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @function idleAdd@ Add a callback that is called whenever the system is\n-- idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @function idleRemove@ Remove a previously added idle handler by its\n-- @ref type TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General@\n--\n-- Author : Axel Simon\n--\t Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.8 $ from $Date: 2002\/12\/03 13:20:07 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\nmodule General(\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport LocalData(newIORef, readIORef, writeIORef)\nimport Exception (ioError, Exception(ErrorCall))\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @function getDefaultLanguage@ 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 <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @function initGUI@ Initialize the GUI binding.\n--\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: @literal ErrorCall \"Cannot initialize GUI.\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\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 peekCString addrs'\n else ioError (ErrorCall \"Cannot initialize GUI.\")\n\n-- @function eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @function mainGUI@ Run GTK+'s main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- @function mainLevel@ Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call \n-- @ref function loopIteration@ to keep the GUI responsive. Each time\n-- the main loop is restarted this way, the main loop counter is\n-- increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @function mainQuit@ Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @function mainIteration@ Process an event, block if necessary.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @function mainIterationDo@ Process a single event.\n--\n-- * Called with @literal True@, this function behaves as\n-- @ref function loopIteration@ in that it waits until an event is available\n-- for processing. The function will return immediately, if passed\n-- @literal False@.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\n\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @function grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @function grabGetCurrent@ 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-- @function grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @function timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @function timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @function idleAdd@ Add a callback that is called whenever the system is\n-- idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @function idleRemove@ Remove a previously added idle handler by its\n-- @ref type TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1b68b909c3c29decb1f2af5fd0fe29dc4b437e00","subject":"More bindings","message":"More bindings\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(..), 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\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {int2cint `Int',\n int2cint `Int',\n int2cint `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' 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.\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.\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.\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","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(..), Affection(..), TrickMode(..),\n xine_stream_new, xine_stream_master_slave, xine_open, xine_play,\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 ) 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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {int2cint `Int',\n int2cint `Int',\n int2cint `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' 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.\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.\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.\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-- | 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"74dd2792b2ba0cd89d9cdecf6c8825d6f28e17be","subject":"[project @ 2002-07-08 09:13:09 by as49] Changed the type of eventsPending to the propper one.","message":"[project @ 2002-07-08 09:13:09 by as49]\nChanged the type of eventsPending to the propper one.\n","repos":"vincenthz\/webkit","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:13:09 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/05\/24 09:43:24 $\n--\n-- Copyright (c) [1998..2001] Manuel M. T. Chakravarty\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-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Bool\neventsPending = liftM toBool {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e665bf505e175709582d395cb93adc09dbf993a5","subject":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members","message":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult(..),\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult,\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"818c37afb2e8aabf700a6b08c3ac476f4c11ac13","subject":"gconf: S.G.G.GConfValue: remove -fallow-overlapping-instances (it's handled in the makefile)","message":"gconf: S.G.G.GConfValue: remove -fallow-overlapping-instances (it's handled in the makefile)","repos":"vincenthz\/webkit","old_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_contents":"-- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Control.Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","old_contents":"{-# OPTIONS -fallow-overlapping-instances #-} -- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Control.Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a9f673ce568e2c3e85302da7acbba5e16d692377","subject":"Add function `widgetGetAllocation` and fix version tag.","message":"Add function `widgetGetAllocation` and fix version tag.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"cb3d9010de95c9ff412084dff8a8850a693ee8b2","subject":"Temporary commit. About to change a lot","message":"Temporary commit. About to change a lot\n","repos":"travitch\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/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.C.String\nimport Foreign.C.Types\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 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 -- = 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\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = cToEnum <$> ({#get CValue->valueTag#} v)\n\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\n\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\n\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#}\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 #}\n\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#}\n\ndata CBinaryOpInfo\n{#pointer *CBinaryOpInfo as BinaryInfoPtr -> CBinaryOpInfo #}\ncBinaryOpLHS :: BinaryInfoPtr -> IO ValuePtr\ncBinaryOpLHS = {#get CBinaryOpInfo->lhs #}\ncBinaryOpRHS :: BinaryInfoPtr -> IO ValuePtr\ncBinaryOpRHS = {#get CBinaryOpInfo->rhs #}\ncBinaryOpFlags :: BinaryInfoPtr -> IO ArithFlags\ncBinaryOpFlags o = cToEnum <$> {#get CBinaryOpInfo->flags#} o\n\ndata CUnaryOpInfo\n{#pointer *CUnaryOpInfo as UnaryInfoPtr -> CUnaryOpInfo #}\ncUnaryOpOperand :: UnaryInfoPtr -> IO ValuePtr\ncUnaryOpOperand = {#get CUnaryOpInfo->val#}\ncUnaryOpAlign :: UnaryInfoPtr -> IO Int64\ncUnaryOpAlign u = cIntConv <$> {#get CUnaryOpInfo->align#} u\ncUnaryOpIsVolatile :: UnaryInfoPtr -> IO Bool\ncUnaryOpIsVolatile u = cToBool <$> {#get CUnaryOpInfo->isVolatile#} u\ncUnaryOpAddrSpace :: UnaryInfoPtr -> IO Int\ncUnaryOpAddrSpace u = cIntConv <$> {#get CUnaryOpInfo->addrSpace#} u\n\ndata CCmpInfo\n{#pointer *CCmpInfo as CmpInfoPtr -> CCmpInfo #}\ncCmpOp1 :: CmpInfoPtr -> IO ValuePtr\ncCmpOp1 = {#get CCmpInfo->op1 #}\ncCmpOp2 :: CmpInfoPtr -> IO ValuePtr\ncCmpOp2 = {#get CCmpInfo->op2 #}\ncCmpPred :: CmpInfoPtr -> IO CmpPredicate\ncCmpPred c = cToEnum <$> {#get CCmpInfo->pred#} c\n\n\ndata CStoreInfo\n{#pointer *CStoreInfo as StoreInfoPtr -> CStoreInfo #}\ncStoreValue :: StoreInfoPtr -> IO ValuePtr\ncStoreValue = {#get CStoreInfo->value#}\ncStorePointer :: StoreInfoPtr -> IO ValuePtr\ncStorePointer = {#get CStoreInfo->pointer#}\ncStoreAddrSpace :: StoreInfoPtr -> IO Int\ncStoreAddrSpace s = cIntConv <$> {#get CStoreInfo->addrSpace#} s\ncStoreAlign :: StoreInfoPtr -> IO Int64\ncStoreAlign s = cIntConv <$> {#get CStoreInfo->align#} s\ncStoreIsVolatile :: StoreInfoPtr -> IO Bool\ncStoreIsVolatile s = cToBool <$> {#get CStoreInfo->isVolatile#} s\n\ndata CGEPInfo\n{#pointer *CGEPInfo as GEPInfoPtr -> CGEPInfo #}\ncGEPOperand :: GEPInfoPtr -> IO ValuePtr\ncGEPOperand = {#get CGEPInfo->operand#}\ncGEPIndices :: GEPInfoPtr -> IO [ValuePtr]\ncGEPIndices g =\n peekArray g {#get CGEPInfo->indices#} {#get CGEPInfo->indexListLen#}\ncGEPInBounds :: GEPInfoPtr -> IO Bool\ncGEPInBounds g = cToBool <$> {#get CGEPInfo->inBounds#} g\ncGEPAddrSpace :: GEPInfoPtr -> IO Int\ncGEPAddrSpace g = cIntConv <$> {#get CGEPInfo->addrSpace#} g\n\ndata CInsExtValInfo\n{#pointer *CInsExtValInfo as InsExtPtr -> CInsExtValInfo #}\ncInsExtAggregate :: InsExtPtr -> IO ValuePtr\ncInsExtAggregate = {#get CInsExtValInfo->aggregate#}\ncInsExtValue :: InsExtPtr -> IO ValuePtr\ncInsExtValue = {#get CInsExtValInfo->val#}\ncInsExtIndices :: InsExtPtr -> IO [Int]\ncInsExtIndices ie =\n peekArray ie {#get CInsExtValInfo->indices#} {#get CInsExtValInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag = {#get CConstExprInfo->instrType#}\ncConstExprOperands :: ConstExprPtr -> IO [ValuePtr]\ncConstExprOperands ce =\n peekArray ce {#get CConstExprInfo->operands#} {#get CConstExprInfo->numOperands#}\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 = undefined\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 isExtern <- liftIO $ cGlobalIsExternal dataPtr'\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\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 , globalVariableAddressSpace = undefined\n , globalVariableAnnotation = undefined\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 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 = undefined\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 BinaryInfoPtr -> KnotMonad ValueT\ntranslateFlaggedBinaryOp finalState constructor dataPtr = do\n lhs <- liftIO $ cBinaryOpLHS dataPtr\n rhs <- liftIO $ cBinaryOpRHS dataPtr\n flags <- liftIO $ cBinaryOpFlags dataPtr\n\n lhs' <- translateConstOrRef finalState lhs\n rhs' <- translateConstOrRef finalState rhs\n\n return $! constructor flags lhs' rhs'\n\ntranslateBinaryOp :: KnotState -> (Value -> Value -> ValueT) ->\n BinaryInfoPtr -> KnotMonad ValueT\ntranslateBinaryOp finalState constructor dataPtr = do\n lhs <- liftIO $ cBinaryOpLHS dataPtr\n rhs <- liftIO $ cBinaryOpRHS dataPtr\n\n lhs' <- translateConstOrRef finalState lhs\n rhs' <- translateConstOrRef finalState rhs\n\n return $! constructor lhs' rhs'\n\ntranslateAllocaInst :: KnotState -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateAllocaInst finalState dataPtr = do\n vptr <- liftIO $ cUnaryOpOperand dataPtr\n align <- liftIO $ cUnaryOpAlign dataPtr\n\n val <- translateConstOrRef finalState vptr\n\n return $! AllocaInst val align\n\ntranslateLoadInst :: KnotState -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateLoadInst finalState dataPtr = do\n addrptr <- liftIO $ cUnaryOpOperand dataPtr\n align <- liftIO $ cUnaryOpAlign dataPtr\n volFlag <- liftIO $ cUnaryOpIsVolatile dataPtr\n\n addr <- translateConstOrRef finalState addrptr\n\n return $! LoadInst volFlag addr align\n\ntranslateStoreInst :: KnotState -> StoreInfoPtr -> KnotMonad ValueT\ntranslateStoreInst finalState dataPtr = do\n vptr <- liftIO $ cStoreValue dataPtr\n pptr <- liftIO $ cStorePointer dataPtr\n addrSpace <- liftIO $ cStoreAddrSpace dataPtr\n align <- liftIO $ cStoreAlign dataPtr\n isVol <- liftIO $ cStoreIsVolatile dataPtr\n\n val' <- translateConstOrRef finalState vptr\n ptr' <- translateConstOrRef finalState pptr\n\n return $! StoreInst isVol val' ptr' align\n\ntranslateGEPInst :: KnotState -> GEPInfoPtr -> KnotMonad ValueT\ntranslateGEPInst finalState dataPtr = do\n vptr <- liftIO $ cGEPOperand dataPtr\n iptrs <- liftIO $ cGEPIndices dataPtr\n inBounds <- liftIO $ cGEPInBounds dataPtr\n addrSpace <- liftIO $ cGEPAddrSpace dataPtr\n\n oper <- translateConstOrRef finalState vptr\n is <- mapM (translateConstOrRef finalState) iptrs\n\n return $! GetElementPtrInst { getElementPtrInBounds = inBounds\n , getElementPtrValue = oper\n , getElementPtrIndices = is\n }\n\ntranslateCastInst :: KnotState -> (Value -> ValueT) -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateCastInst finalState constructor dataPtr = do\n vptr <- liftIO $ cUnaryOpOperand dataPtr\n v <- translateConstOrRef finalState vptr\n return $! constructor v\n\ntranslateCmpInst :: KnotState -> (CmpPredicate -> Value -> Value -> ValueT) ->\n CmpInfoPtr -> KnotMonad ValueT\ntranslateCmpInst finalState constructor dataPtr = do\n op1ptr <- liftIO $ cCmpOp1 dataPtr\n op2ptr <- liftIO $ cCmpOp2 dataPtr\n predicate <- liftIO $ cCmpPred dataPtr\n\n op1 <- translateConstOrRef finalState op1ptr\n op2 <- translateConstOrRef finalState op2ptr\n\n return $! constructor predicate op1 op2\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 -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateVarArgInst finalState dataPtr = do\n opptr <- liftIO $ cUnaryOpOperand dataPtr\n op <- translateConstOrRef finalState opptr\n return $! VaArgInst op\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{-\ncInsExtAggregate :: InsExtPtr -> IO ValuePtr\ncInsExtValue :: InsExtPtr -> IO ValuePtr\ncInsExtIndices :: InsExtPtr -> IO [Int]\n-}\ntranslateExtractValueInst :: KnotState -> InsExtPtr -> KnotMonad ValueT\ntranslateExtractValueInst finalState dataPtr = do\n aggPtr <- liftIO $ cInsExtAggregate dataPtr\n indices <- liftIO $ cInsExtIndices dataPtr\n\n agg <- translateConstOrRef finalState aggPtr\n\n return $! ExtractValueInst { extractValueAggregate = agg\n , extractValueIndices = indices\n }\n\ntranslateInsertValueInst :: KnotState -> InsExtPtr -> KnotMonad ValueT\ntranslateInsertValueInst finalState dataPtr = do\n aggPtr <- liftIO $ cInsExtAggregate dataPtr\n valPtr <- liftIO $ cInsExtValue dataPtr\n indices <- liftIO $ cInsExtIndices dataPtr\n\n agg <- translateConstOrRef finalState aggPtr\n val <- translateConstOrRef finalState valPtr\n\n return $! InsertValueInst { insertValueAggregate = agg\n , insertValueValue = val\n , insertValueIndices = indices\n }\n\ntranslateConstantExpr :: KnotState -> ConstExprPtr -> KnotMonad ValueT\ntranslateConstantExpr finalState dataPtr = undefined -- do\n -- opPtrs <- liftIO $ cConstExprOperands dataPtr\n -- tag <- liftIO $ cConstExprTag dataPtr\n -- ops <- mapM (translateConstOrRef finalState) opPtrs\n\n -- case tag of","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.C.String\nimport Foreign.C.Types\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 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 -- = 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\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = cToEnum <$> ({#get CValue->valueTag#} v)\n\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\n\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\n\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#}\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 #}\n\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#}\n\ndata CBinaryOpInfo\n{#pointer *CBinaryOpInfo as BinaryInfoPtr -> CBinaryOpInfo #}\ncBinaryOpLHS :: BinaryInfoPtr -> IO ValuePtr\ncBinaryOpLHS = {#get CBinaryOpInfo->lhs #}\ncBinaryOpRHS :: BinaryInfoPtr -> IO ValuePtr\ncBinaryOpRHS = {#get CBinaryOpInfo->rhs #}\ncBinaryOpFlags :: BinaryInfoPtr -> IO ArithFlags\ncBinaryOpFlags o = cToEnum <$> {#get CBinaryOpInfo->flags#} o\n\ndata CUnaryOpInfo\n{#pointer *CUnaryOpInfo as UnaryInfoPtr -> CUnaryOpInfo #}\ncUnaryOpOperand :: UnaryInfoPtr -> IO ValuePtr\ncUnaryOpOperand = {#get CUnaryOpInfo->val#}\ncUnaryOpAlign :: UnaryInfoPtr -> IO Int64\ncUnaryOpAlign u = cIntConv <$> {#get CUnaryOpInfo->align#} u\ncUnaryOpIsVolatile :: UnaryInfoPtr -> IO Bool\ncUnaryOpIsVolatile u = cToBool <$> {#get CUnaryOpInfo->isVolatile#} u\ncUnaryOpAddrSpace :: UnaryInfoPtr -> IO Int\ncUnaryOpAddrSpace u = cIntConv <$> {#get CUnaryOpInfo->addrSpace#} u\n\ndata CCmpInfo\n{#pointer *CCmpInfo as CmpInfoPtr -> CCmpInfo #}\ncCmpOp1 :: CmpInfoPtr -> IO ValuePtr\ncCmpOp1 = {#get CCmpInfo->op1 #}\ncCmpOp2 :: CmpInfoPtr -> IO ValuePtr\ncCmpOp2 = {#get CCmpInfo->op2 #}\ncCmpPred :: CmpInfoPtr -> IO CmpPredicate\ncCmpPred c = cToEnum <$> {#get CCmpInfo->pred#} c\n\n\ndata CStoreInfo\n{#pointer *CStoreInfo as StoreInfoPtr -> CStoreInfo #}\ncStoreValue :: StoreInfoPtr -> IO ValuePtr\ncStoreValue = {#get CStoreInfo->value#}\ncStorePointer :: StoreInfoPtr -> IO ValuePtr\ncStorePointer = {#get CStoreInfo->pointer#}\ncStoreAddrSpace :: StoreInfoPtr -> IO Int\ncStoreAddrSpace s = cIntConv <$> {#get CStoreInfo->addrSpace#} s\ncStoreAlign :: StoreInfoPtr -> IO Int64\ncStoreAlign s = cIntConv <$> {#get CStoreInfo->align#} s\ncStoreIsVolatile :: StoreInfoPtr -> IO Bool\ncStoreIsVolatile s = cToBool <$> {#get CStoreInfo->isVolatile#} s\n\ndata CGEPInfo\n{#pointer *CGEPInfo as GEPInfoPtr -> CGEPInfo #}\ncGEPOperand :: GEPInfoPtr -> IO ValuePtr\ncGEPOperand = {#get CGEPInfo->operand#}\ncGEPIndices :: GEPInfoPtr -> IO [ValuePtr]\ncGEPIndices g =\n peekArray g {#get CGEPInfo->indices#} {#get CGEPInfo->indexListLen#}\ncGEPInBounds :: GEPInfoPtr -> IO Bool\ncGEPInBounds g = cToBool <$> {#get CGEPInfo->inBounds#} g\ncGEPAddrSpace :: GEPInfoPtr -> IO Int\ncGEPAddrSpace g = cIntConv <$> {#get CGEPInfo->addrSpace#} g\n\ndata CInsExtValInfo\n{#pointer *CInsExtValInfo as InsExtPtr -> CInsExtValInfo #}\ncInsExtAggregate :: InsExtPtr -> IO ValuePtr\ncInsExtAggregate = {#get CInsExtValInfo->aggregate#}\ncInsExtValue :: InsExtPtr -> IO ValuePtr\ncInsExtValue = {#get CInsExtValInfo->val#}\ncInsExtIndices :: InsExtPtr -> IO [Int]\ncInsExtIndices ie =\n peekArray ie {#get CInsExtValInfo->indices#} {#get CInsExtValInfo->numIndices#}\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 = undefined\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 isExtern <- liftIO $ cGlobalIsExternal dataPtr'\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\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 , globalVariableAddressSpace = undefined\n , globalVariableAnnotation = undefined\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-- | 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 -- ValCnstantexpr\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\n uid <- nextId\n\n let tv = Value { valueType = tt\n , valueName = name\n , valueMetadata = undefined\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 BinaryInfoPtr -> KnotMonad ValueT\ntranslateFlaggedBinaryOp finalState constructor dataPtr = do\n lhs <- liftIO $ cBinaryOpLHS dataPtr\n rhs <- liftIO $ cBinaryOpRHS dataPtr\n flags <- liftIO $ cBinaryOpFlags dataPtr\n\n lhs' <- translateConstOrRef finalState lhs\n rhs' <- translateConstOrRef finalState rhs\n\n return $! constructor flags lhs' rhs'\n\ntranslateBinaryOp :: KnotState -> (Value -> Value -> ValueT) ->\n BinaryInfoPtr -> KnotMonad ValueT\ntranslateBinaryOp finalState constructor dataPtr = do\n lhs <- liftIO $ cBinaryOpLHS dataPtr\n rhs <- liftIO $ cBinaryOpRHS dataPtr\n\n lhs' <- translateConstOrRef finalState lhs\n rhs' <- translateConstOrRef finalState rhs\n\n return $! constructor lhs' rhs'\n\ntranslateAllocaInst :: KnotState -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateAllocaInst finalState dataPtr = do\n vptr <- liftIO $ cUnaryOpOperand dataPtr\n align <- liftIO $ cUnaryOpAlign dataPtr\n\n val <- translateConstOrRef finalState vptr\n\n return $! AllocaInst val align\n\ntranslateLoadInst :: KnotState -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateLoadInst finalState dataPtr = do\n addrptr <- liftIO $ cUnaryOpOperand dataPtr\n align <- liftIO $ cUnaryOpAlign dataPtr\n volFlag <- liftIO $ cUnaryOpIsVolatile dataPtr\n\n addr <- translateConstOrRef finalState addrptr\n\n return $! LoadInst volFlag addr align\n\ntranslateStoreInst :: KnotState -> StoreInfoPtr -> KnotMonad ValueT\ntranslateStoreInst finalState dataPtr = do\n vptr <- liftIO $ cStoreValue dataPtr\n pptr <- liftIO $ cStorePointer dataPtr\n addrSpace <- liftIO $ cStoreAddrSpace dataPtr\n align <- liftIO $ cStoreAlign dataPtr\n isVol <- liftIO $ cStoreIsVolatile dataPtr\n\n val' <- translateConstOrRef finalState vptr\n ptr' <- translateConstOrRef finalState pptr\n\n return $! StoreInst isVol val' ptr' align\n\ntranslateGEPInst :: KnotState -> GEPInfoPtr -> KnotMonad ValueT\ntranslateGEPInst finalState dataPtr = do\n vptr <- liftIO $ cGEPOperand dataPtr\n iptrs <- liftIO $ cGEPIndices dataPtr\n inBounds <- liftIO $ cGEPInBounds dataPtr\n addrSpace <- liftIO $ cGEPAddrSpace dataPtr\n\n oper <- translateConstOrRef finalState vptr\n is <- mapM (translateConstOrRef finalState) iptrs\n\n return $! GetElementPtrInst { getElementPtrInBounds = inBounds\n , getElementPtrValue = oper\n , getElementPtrIndices = is\n }\n\ntranslateCastInst :: KnotState -> (Value -> ValueT) -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateCastInst finalState constructor dataPtr = do\n vptr <- liftIO $ cUnaryOpOperand dataPtr\n v <- translateConstOrRef finalState vptr\n return $! constructor v\n\ntranslateCmpInst :: KnotState -> (CmpPredicate -> Value -> Value -> ValueT) ->\n CmpInfoPtr -> KnotMonad ValueT\ntranslateCmpInst finalState constructor dataPtr = do\n op1ptr <- liftIO $ cCmpOp1 dataPtr\n op2ptr <- liftIO $ cCmpOp2 dataPtr\n predicate <- liftIO $ cCmpPred dataPtr\n\n op1 <- translateConstOrRef finalState op1ptr\n op2 <- translateConstOrRef finalState op2ptr\n\n return $! constructor predicate op1 op2\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 -> UnaryInfoPtr -> KnotMonad ValueT\ntranslateVarArgInst finalState dataPtr = do\n opptr <- liftIO $ cUnaryOpOperand dataPtr\n op <- translateConstOrRef finalState opptr\n return $! VaArgInst op\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{-\ncInsExtAggregate :: InsExtPtr -> IO ValuePtr\ncInsExtValue :: InsExtPtr -> IO ValuePtr\ncInsExtIndices :: InsExtPtr -> IO [Int]\n-}\ntranslateExtractValueInst :: KnotState -> InsExtPtr -> KnotMonad ValueT\ntranslateExtractValueInst finalState dataPtr = do\n aggPtr <- liftIO $ cInsExtAggregate dataPtr\n indices <- liftIO $ cInsExtIndices dataPtr\n\n agg <- translateConstOrRef finalState aggPtr\n\n return $! ExtractValueInst { extractValueAggregate = agg\n , extractValueIndices = indices\n }\n\ntranslateInsertValueInst :: KnotState -> InsExtPtr -> KnotMonad ValueT\ntranslateInsertValueInst finalState dataPtr = do\n aggPtr <- liftIO $ cInsExtAggregate dataPtr\n valPtr <- liftIO $ cInsExtValue dataPtr\n indices <- liftIO $ cInsExtIndices dataPtr\n\n agg <- translateConstOrRef finalState aggPtr\n val <- translateConstOrRef finalState valPtr\n\n return $! InsertValueInst { insertValueAggregate = agg\n , insertValueValue = val\n , insertValueIndices = indices\n }\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2941559de19edf2359be81ad96609b929385c039","subject":"Image.withCloneValue","message":"Image.withCloneValue","repos":"BeautifulDestinations\/CV,aleator\/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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue img fun = do \n result <- cloneImage img\n r <- fun result\n return r\n\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\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\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\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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":"3db1701385d5324a8835a5ba326a408cb9209cec","subject":"Made composing multichannel images safer","message":"Made composing multichannel images safer\n","repos":"BeautifulDestinations\/CV,aleator\/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 #-}\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.Unsafe (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\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\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\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 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\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 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\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 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\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 #-}\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, 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.Unsafe (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\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\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\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 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\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 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\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 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\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":"07dbbf0ef4d64cf81896f5be62acd6686baff49c","subject":"Fix docu.","message":"Fix docu.\n","repos":"gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'keyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e03718b21ea1153478b2528529069a555a62471d","subject":"Add mutex functions to Gtk and remove the funky threaded intialisation function.","message":"Add mutex functions to Gtk and remove the funky threaded intialisation function.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n threadsEnter,\n threadsLeave,\n \n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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\nunsafeInitGUIForThreadedRTS = initGUI\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 header 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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\n--\n-- * If you want to use Gtk2Hs and in a multi-threaded application then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'. See also 'threadsEnter'.\n--\ninitGUI :: IO [String]\ninitGUI = do\n when rtsSupportsBoundThreads initialiseGThreads\n threadsEnter\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\n\n-- | Acquired the global Gtk lock.\n--\n-- * During normal operation, this lock is held by the thread from which all\n-- interaction with Gtk is performed. When calling 'mainGUI', the thread will\n-- release this global lock before it waits for user interaction. During this\n-- time it is, in principle, possible to use a different OS thread (any other\n-- Haskell thread that is bound to the Gtk OS thread will be blocked anyway)\n-- to interact with Gtk by explicitly acquiring the lock, calling Gtk functions\n-- and releasing the lock. However, the Gtk functions that are called from this\n-- different thread may not trigger any calls to the OS since this will\n-- lead to a crash on Windows (the Win32 API can only be used from a single\n-- thread). Since it is very hard to tell which function only interacts on\n-- Gtk data structures and which function call actual OS functions, it\n-- is best not to use this feature at all. A better way to perform updates\n-- in the background is to spawn a Haskell thread and to perform the update\n-- to Gtk widgets using 'postGUIAsync' or 'postGUISync'. These will execute\n-- their arguments from the main loop, that is, from the OS thread of Gtk,\n-- thereby ensuring that any Gtk and OS function can be called.\n--\n{#fun unsafe gdk_threads_enter as threadsEnter {} -> `()' #}\n\n-- | Release the global Gtk lock.\n--\n-- * The use of this function is not recommended. See 'threadsEnter'.\n--\n{#fun unsafe gdk_threads_leave as threadsLeave {} -> `()' #}\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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 header 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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"71bc4f2b8971eb0be4c2c21a8aaa6275e824cf35","subject":"sourceBufferSet\/GetStyleScheme should pass\/return 'Maybe SourceStyleScheme'","message":"sourceBufferSet\/GetStyleScheme should pass\/return 'Maybe SourceStyleScheme'\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBuffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n sb \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBuffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBuffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n sb \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBuffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBuffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBuffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n buffer \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n buffer\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n buffer\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBuffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: Signal SourceBuffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: Signal SourceBuffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: Signal SourceBuffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBuffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n sb \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBuffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBuffer \n -> SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBuffer \n -> IO SourceStyleScheme -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBuffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBuffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n buffer \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n buffer\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n buffer\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBuffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: Signal SourceBuffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: Signal SourceBuffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: Signal SourceBuffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9c36d3b7d385316a28c282be5bdc40cb1867aff9","subject":"[project @ 2002-07-17 16:00:41 by juhp] (treeViewInsertColumnWithAttributes): Haskell implementation to avoid binding to original variad function.","message":"[project @ 2002-07-17 16:00:41 by juhp]\n(treeViewInsertColumnWithAttributes): Haskell implementation\nto avoid binding to original variad function.\n\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gtksourceview","old_file":"gtk\/treeList\/TreeView.chs","new_file":"gtk\/treeList\/TreeView.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget TreeView@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 May 2001\n--\n-- Version $Revision: 1.5 $ from $Date: 2002\/07\/17 16:00:41 $\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-- * This widget constitutes the main widget for displaying lists and other\n-- structured data.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * treeViewGetPathAtPos is surely useful but has to be used with events in\n-- order not to pass GdkWindows around.\n--\nmodule TreeView(\n TreeView,\n TreeViewClass,\n castToTreeView,\n treeViewNew,\n treeViewNewWithModel,\n treeViewGetModel,\n treeViewSetModel,\n treeViewGetSelection,\n treeViewGetHadjustment,\n treeViewSetHadjustment,\n treeViewGetVadjustment,\n treeViewSetVadjustment,\n treeViewGetHeadersVisible,\n treeViewSetHeadersVisible,\n treeViewColumnsAutosize,\n treeViewSetHeadersClickable,\n treeViewAppendColumn,\n treeViewRemoveColumn,\n treeViewInsertColumn,\n treeViewInsertColumnWithAttributes,\n treeViewGetColumn,\n treeViewScrollToCell,\n treeViewExpandAll,\n treeViewCollapseAll,\n treeViewCollapseRow\n ) where\n\nimport Monad\t(liftM)\nimport Maybe\t(fromMaybe)\nimport Foreign\nimport UTFCForeign\nimport Structs\t(nullForeignPtr)\nimport GObject\t(objectRef, objectUnref)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n{#import TreeModel#}\n{#import TreeViewColumn#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor treeViewNew@ Make a new TreeView widget.\n--\ntreeViewNew :: IO TreeView\ntreeViewNew = makeNewObject mkTreeView (liftM castPtr {#call tree_view_new#})\n\n-- @constructor treeViewNewWithModel@ Make a new TreeView widget with \n-- @ref arg tm@ as the storage model.\n--\ntreeViewNewWithModel :: TreeModelClass tm => tm -> IO TreeView\ntreeViewNewWithModel tm = makeNewObject mkTreeView $ liftM castPtr $\n {#call tree_view_new_with_model#} (toTreeModel tm)\n\n-- @method treeViewGetModel@ Retrieve the TreeModel that supplies the data for\n-- this TreeView. Returns Nothing if no model is currently set.\n--\ntreeViewGetModel :: TreeViewClass tv => tv -> IO (Maybe TreeModel)\ntreeViewGetModel tv = do\n tmPtr <- {#call unsafe tree_view_get_model#} (toTreeView tv)\n if tmPtr==nullPtr then return Nothing else do\n objectRef tmPtr\n liftM (Just . mkTreeModel) $ newForeignPtr tmPtr (objectUnref tmPtr)\n\n-- @method treeViewSetModel@ Set the TreeModel for the current View.\n--\ntreeViewSetModel :: (TreeViewClass tv, TreeModelClass tm) => tv -> tm -> IO ()\ntreeViewSetModel tv tm =\n {#call tree_view_set_model#} (toTreeView tv) (toTreeModel tm)\n\n-- @method treeViewGetSelection@ Retrieve a @ref type TreeSelection@ that\n-- holds the current selected nodes of the View.\n--\ntreeViewGetSelection :: TreeViewClass tv => tv -> IO TreeSelection\ntreeViewGetSelection tv = makeNewObject mkTreeSelection $\n {#call unsafe tree_view_get_selection#} (toTreeView tv)\n\n-- @method treeViewGetHadjustment@ Get the @ref arg Adjustment@ that\n-- represents the horizontal aspect.\n--\ntreeViewGetHadjustment :: TreeViewClass tv => tv -> IO (Maybe Adjustment)\ntreeViewGetHadjustment tv = do\n adjPtr <- {#call unsafe tree_view_get_hadjustment#} (toTreeView tv)\n if adjPtr==nullPtr then return Nothing else do\n liftM Just $ makeNewObject mkAdjustment (return adjPtr)\n\n-- @method treeViewSetHadjustment@ Set the @ref arg Adjustment@ that controls\n-- the horizontal aspect. If @ref arg adj@ is Nothing then set no Adjustment\n-- widget.\n--\ntreeViewSetHadjustment :: TreeViewClass tv => (Maybe Adjustment) -> tv -> IO ()\ntreeViewSetHadjustment adj tv = {#call tree_view_set_hadjustment#} \n (toTreeView tv) (fromMaybe (mkAdjustment nullForeignPtr) adj)\n\n-- @method treeViewGetVadjustment@ Get the @ref arg Adjustment@ that\n-- represents the vertical aspect.\n--\ntreeViewGetVadjustment :: TreeViewClass tv => tv -> IO (Maybe Adjustment)\ntreeViewGetVadjustment tv = do\n adjPtr <- {#call unsafe tree_view_get_vadjustment#} (toTreeView tv)\n if adjPtr==nullPtr then return Nothing else do\n liftM Just $ makeNewObject mkAdjustment (return adjPtr)\n\n-- @method treeViewSetVadjustment@ Set the @ref arg Adjustment@ that controls\n-- the vertical aspect. If @ref arg adj@ is Nothing then set no Adjustment\n-- widget.\n--\ntreeViewSetVadjustment :: TreeViewClass tv => (Maybe Adjustment) -> tv -> IO ()\ntreeViewSetVadjustment adj tv = {#call tree_view_set_vadjustment#} \n (toTreeView tv) (fromMaybe (mkAdjustment nullForeignPtr) adj)\n\n\n-- @method treeViewGetHeadersVisible@ Query if the column headers are visible.\n--\ntreeViewGetHeadersVisible :: TreeViewClass tv => tv -> IO Bool\ntreeViewGetHeadersVisible tv = liftM toBool $\n {#call unsafe tree_view_get_headers_visible#} (toTreeView tv)\n\n-- @method treeViewSetHeadersVisible@ Set the visibility state of the column\n-- headers.\n--\ntreeViewSetHeadersVisible :: TreeViewClass tv => tv -> Bool -> IO ()\ntreeViewSetHeadersVisible tv vis = {#call tree_view_set_headers_visible#}\n (toTreeView tv) (fromBool vis)\n\n-- @method treeViewColumnsAutosize@ Resize the columns to their optimal size.\n--\ntreeViewColumnsAutosize :: TreeViewClass tv => tv -> IO ()\ntreeViewColumnsAutosize tv =\n {#call tree_view_columns_autosize#} (toTreeView tv)\n\n-- @method treeViewSetHeadersClickable@ Set wether the columns headers are\n-- sensitive to mouse clicks.\n--\n-- * @literal@\n-- \n\n--\ntreeViewSetHeadersClickable :: TreeViewClass tv => tv -> Bool -> IO ()\ntreeViewSetHeadersClickable tv click = {#call tree_view_set_headers_clickable#}\n (toTreeView tv) (fromBool click)\n\n-- @method treeViewAppendColumn@ Append a new column to the TreeView. Returns\n-- the new number of columns.\n--\ntreeViewAppendColumn :: TreeViewClass tv => tv -> TreeViewColumn -> IO Int\ntreeViewAppendColumn tv tvc = liftM fromIntegral $\n {#call tree_view_append_column#} (toTreeView tv) tvc\n\n-- @method treeViewRemoveColumn@ Remove column @ref arg tvc@ from the TreeView\n-- widget. The number of remaining columns is returned.\n--\ntreeViewRemoveColumn :: TreeViewClass tv => tv -> TreeViewColumn -> IO Int\ntreeViewRemoveColumn tv tvc = liftM fromIntegral $\n {#call tree_view_remove_column#} (toTreeView tv) tvc\n\n-- @method treeViewInsertColumn@ Inserts column @ref arg tvc@ into the\n-- TreeView widget at the position @ref arg pos@. Returns the number of\n-- columns after insertion. Specify -1 for @ref arg pos@ to insert the column\n-- at the end.\n--\ntreeViewInsertColumn :: TreeViewClass tv => tv -> TreeViewColumn -> Int ->\n IO Int\ntreeViewInsertColumn tv tvc pos = liftM fromIntegral $ \n {#call tree_view_insert_column#} (toTreeView tv) tvc (fromIntegral pos)\n\n\n-- @method treeViewInsertColumnWithAttributes@ Inserts new column into the\n-- TreeView @ref arg tv@ at position @ref arg pos@ with title\n-- @ref argtitle@, cell renderer @ref arg cr@ and attributes\n-- @ref arg attribs@. Specify -1 for @ref arg pos@ to insert the column at\n-- the end.\n--\ntreeViewInsertColumnWithAttributes :: (TreeViewClass tv, CellRendererClass cr)\n => tv -> Int -> String -> cr -> [(String,Int)] -> IO ()\ntreeViewInsertColumnWithAttributes tv pos title cr attribs = \n do\n column <- treeViewColumnNew\n treeViewColumnSetTitle column title\n treeViewColumnPackStart column cr True\n treeViewColumnAddAttributes column cr attribs\n treeViewInsertColumn tv column pos\n return ()\n\n-- @method treeViewGetColumn@ Retrieve the @ref arg pos@ th columns of\n-- TreeView. If the index is out of range Nothing is returned.\n--\ntreeViewGetColumn :: TreeViewClass tv => tv -> Int -> IO (Maybe TreeViewColumn)\ntreeViewGetColumn tv pos = do\n tvcPtr <- {#call unsafe tree_view_get_column#} (toTreeView tv) \n (fromIntegral pos)\n if tvcPtr==nullPtr then return Nothing else \n liftM Just $ makeNewObject mkTreeViewColumn (return tvcPtr)\n\n-- @method treeViewScrollToCell@ Scroll to a cell specified by @ref arg path@\n-- and @ref arg tvc@. The cell is aligned within the TreeView widget as\n-- follows: horizontally by @ref arg hor@ from left (0.0) to right (1.0) and\n-- vertically by @ref arg ver@ from top (0.0) to buttom (1.0).\n--\ntreeViewScrollToCell :: TreeViewClass tv => tv -> TreePath -> TreeViewColumn ->\n Maybe (Float,Float) -> IO ()\ntreeViewScrollToCell tv path tvc (Just (ver,hor)) = \n {#call tree_view_scroll_to_cell#} \n (toTreeView tv) path tvc 1 (realToFrac ver) (realToFrac hor)\ntreeViewScrollToCell tv path tvc Nothing = \n {#call tree_view_scroll_to_cell#} \n (toTreeView tv) path tvc 0 0.0 0.0\n\n-- @method treeViewExpandAll@ Expand all nodes in the TreeView.\n--\ntreeViewExpandAll :: TreeViewClass tv => tv -> IO ()\ntreeViewExpandAll tv =\n {#call tree_view_expand_all#} (toTreeView tv)\n\n-- @method treeViewCollapseAll@ Collapse all nodes in the TreeView.\n--\ntreeViewCollapseAll :: TreeViewClass tv => tv -> IO ()\ntreeViewCollapseAll tv =\n {#call tree_view_collapse_all#} (toTreeView tv)\n\n-- Expand a node that is specified by @path. If the flag @all is True every\n-- child will be expanded recursively. Returns True if the row existed and\n-- had children.(EXPORTED)\n--\ntreeViewExpandRow :: TreeViewClass tv => TreePath -> Bool -> tv -> IO Bool\ntreeViewExpandRow path all tv = liftM toBool $\n {#call tree_view_expand_row#} (toTreeView tv) path (fromBool all)\n\n-- @method treeViewCollapseRow@ Collapse a row. Returns True if the row\n-- existed.\n--\ntreeViewCollapseRow :: TreeViewClass tv => tv -> TreePath -> IO Bool\ntreeViewCollapseRow tv path = liftM toBool $\n {#call tree_view_collapse_row#} (toTreeView tv) path\n\n\n\n\n\n \n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget TreeView@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 May 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/08 13:22:46 $\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-- * This widget constitutes the main widget for displaying lists and other\n-- structured data.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * treeViewGetPathAtPos is surely useful but has to be used with events in\n-- order not to pass GdkWindows around.\n--\nmodule TreeView(\n TreeView,\n TreeViewClass,\n castToTreeView,\n treeViewNew,\n treeViewNewWithModel,\n treeViewGetModel,\n treeViewSetModel,\n treeViewGetSelection,\n treeViewGetHadjustment,\n treeViewSetHadjustment,\n treeViewGetVadjustment,\n treeViewSetVadjustment,\n treeViewGetHeadersVisible,\n treeViewSetHeadersVisible,\n treeViewColumnsAutosize,\n treeViewSetHeadersClickable,\n treeViewAppendColumn,\n treeViewRemoveColumn,\n treeViewInsertColumn,\n treeViewGetColumn,\n treeViewScrollToCell,\n treeViewExpandAll,\n treeViewCollapseAll,\n treeViewCollapseRow\n ) where\n\nimport Monad\t(liftM)\nimport Maybe\t(fromMaybe)\nimport Foreign\nimport UTFCForeign\nimport Structs\t(nullForeignPtr)\nimport GObject\t(objectRef, objectUnref)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n{#import TreeModel#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor treeViewNew@ Make a new TreeView widget.\n--\ntreeViewNew :: IO TreeView\ntreeViewNew = makeNewObject mkTreeView (liftM castPtr {#call tree_view_new#})\n\n-- @constructor treeViewNewWithModel@ Make a new TreeView widget with \n-- @ref arg tm@ as the storage model.\n--\ntreeViewNewWithModel :: TreeModelClass tm => tm -> IO TreeView\ntreeViewNewWithModel tm = makeNewObject mkTreeView $ liftM castPtr $\n {#call tree_view_new_with_model#} (toTreeModel tm)\n\n-- @method treeViewGetModel@ Retrieve the TreeModel that supplies the data for\n-- this TreeView. Returns Nothing if no model is currently set.\n--\ntreeViewGetModel :: TreeViewClass tv => tv -> IO (Maybe TreeModel)\ntreeViewGetModel tv = do\n tmPtr <- {#call unsafe tree_view_get_model#} (toTreeView tv)\n if tmPtr==nullPtr then return Nothing else do\n objectRef tmPtr\n liftM (Just . mkTreeModel) $ newForeignPtr tmPtr (objectUnref tmPtr)\n\n-- @method treeViewSetModel@ Set the TreeModel for the current View.\n--\ntreeViewSetModel :: (TreeViewClass tv, TreeModelClass tm) => tv -> tm -> IO ()\ntreeViewSetModel tv tm =\n {#call tree_view_set_model#} (toTreeView tv) (toTreeModel tm)\n\n-- @method treeViewGetSelection@ Retrieve a @ref type TreeSelection@ that\n-- holds the current selected nodes of the View.\n--\ntreeViewGetSelection :: TreeViewClass tv => tv -> IO TreeSelection\ntreeViewGetSelection tv = makeNewObject mkTreeSelection $\n {#call unsafe tree_view_get_selection#} (toTreeView tv)\n\n-- @method treeViewGetHadjustment@ Get the @ref arg Adjustment@ that\n-- represents the horizontal aspect.\n--\ntreeViewGetHadjustment :: TreeViewClass tv => tv -> IO (Maybe Adjustment)\ntreeViewGetHadjustment tv = do\n adjPtr <- {#call unsafe tree_view_get_hadjustment#} (toTreeView tv)\n if adjPtr==nullPtr then return Nothing else do\n liftM Just $ makeNewObject mkAdjustment (return adjPtr)\n\n-- @method treeViewSetHadjustment@ Set the @ref arg Adjustment@ that controls\n-- the horizontal aspect. If @ref arg adj@ is Nothing then set no Adjustment\n-- widget.\n--\ntreeViewSetHadjustment :: TreeViewClass tv => (Maybe Adjustment) -> tv -> IO ()\ntreeViewSetHadjustment adj tv = {#call tree_view_set_hadjustment#} \n (toTreeView tv) (fromMaybe (mkAdjustment nullForeignPtr) adj)\n\n-- @method treeViewGetVadjustment@ Get the @ref arg Adjustment@ that\n-- represents the vertical aspect.\n--\ntreeViewGetVadjustment :: TreeViewClass tv => tv -> IO (Maybe Adjustment)\ntreeViewGetVadjustment tv = do\n adjPtr <- {#call unsafe tree_view_get_vadjustment#} (toTreeView tv)\n if adjPtr==nullPtr then return Nothing else do\n liftM Just $ makeNewObject mkAdjustment (return adjPtr)\n\n-- @method treeViewSetVadjustment@ Set the @ref arg Adjustment@ that controls\n-- the vertical aspect. If @ref arg adj@ is Nothing then set no Adjustment\n-- widget.\n--\ntreeViewSetVadjustment :: TreeViewClass tv => (Maybe Adjustment) -> tv -> IO ()\ntreeViewSetVadjustment adj tv = {#call tree_view_set_vadjustment#} \n (toTreeView tv) (fromMaybe (mkAdjustment nullForeignPtr) adj)\n\n\n-- @method treeViewGetHeadersVisible@ Query if the column headers are visible.\n--\ntreeViewGetHeadersVisible :: TreeViewClass tv => tv -> IO Bool\ntreeViewGetHeadersVisible tv = liftM toBool $\n {#call unsafe tree_view_get_headers_visible#} (toTreeView tv)\n\n-- @method treeViewSetHeadersVisible@ Set the visibility state of the column\n-- headers.\n--\ntreeViewSetHeadersVisible :: TreeViewClass tv => tv -> Bool -> IO ()\ntreeViewSetHeadersVisible tv vis = {#call tree_view_set_headers_visible#}\n (toTreeView tv) (fromBool vis)\n\n-- @method treeViewColumnsAutosize@ Resize the columns to their optimal size.\n--\ntreeViewColumnsAutosize :: TreeViewClass tv => tv -> IO ()\ntreeViewColumnsAutosize tv =\n {#call tree_view_columns_autosize#} (toTreeView tv)\n\n-- @method treeViewSetHeadersClickable@ Set wether the columns headers are\n-- sensitive to mouse clicks.\n--\n-- * @literal@\n-- \n\n--\ntreeViewSetHeadersClickable :: TreeViewClass tv => tv -> Bool -> IO ()\ntreeViewSetHeadersClickable tv click = {#call tree_view_set_headers_clickable#}\n (toTreeView tv) (fromBool click)\n\n-- @method treeViewAppendColumn@ Append a new column to the TreeView. Returns\n-- the new number of columns.\n--\ntreeViewAppendColumn :: TreeViewClass tv => tv -> TreeViewColumn -> IO Int\ntreeViewAppendColumn tv tvc = liftM fromIntegral $\n {#call tree_view_append_column#} (toTreeView tv) tvc\n\n-- @method treeViewRemoveColumn@ Remove column @ref arg tvc@ from the TreeView\n-- widget. The number of remaining columns is returned.\n--\ntreeViewRemoveColumn :: TreeViewClass tv => tv -> TreeViewColumn -> IO Int\ntreeViewRemoveColumn tv tvc = liftM fromIntegral $\n {#call tree_view_remove_column#} (toTreeView tv) tvc\n\n-- @method treeViewInsertColumn@ Inserts column @ref arg tvc@ into the\n-- TreeView widget at the position @ref arg pos@. Returns the number of\n-- columns after insertion. Specify -1 for @ref arg pos@ to insert the column\n-- at the end.\n--\ntreeViewInsertColumn :: TreeViewClass tv => tv -> TreeViewColumn -> Int ->\n IO Int\ntreeViewInsertColumn tv tvc pos = liftM fromIntegral $ \n {#call tree_view_insert_column#} (toTreeView tv) tvc (fromIntegral pos)\n\n\n-- @method treeViewGetColumn@ Retrieve the @ref arg pos@ th columns of\n-- TreeView. If the index is out of range Nothing is returned.\n--\ntreeViewGetColumn :: TreeViewClass tv => tv -> Int -> IO (Maybe TreeViewColumn)\ntreeViewGetColumn tv pos = do\n tvcPtr <- {#call unsafe tree_view_get_column#} (toTreeView tv) \n (fromIntegral pos)\n if tvcPtr==nullPtr then return Nothing else \n liftM Just $ makeNewObject mkTreeViewColumn (return tvcPtr)\n\n-- @method treeViewScrollToCell@ Scroll to a cell specified by @ref arg path@\n-- and @ref arg tvc@. The cell is aligned within the TreeView widget as\n-- follows: horizontally by @ref arg hor@ from left (0.0) to right (1.0) and\n-- vertically by @ref arg ver@ from top (0.0) to buttom (1.0).\n--\ntreeViewScrollToCell :: TreeViewClass tv => tv -> TreePath -> TreeViewColumn ->\n Maybe (Float,Float) -> IO ()\ntreeViewScrollToCell tv path tvc (Just (ver,hor)) = \n {#call tree_view_scroll_to_cell#} \n (toTreeView tv) path tvc 1 (realToFrac ver) (realToFrac hor)\ntreeViewScrollToCell tv path tvc Nothing = \n {#call tree_view_scroll_to_cell#} \n (toTreeView tv) path tvc 0 0.0 0.0\n\n-- @method treeViewExpandAll@ Expand all nodes in the TreeView.\n--\ntreeViewExpandAll :: TreeViewClass tv => tv -> IO ()\ntreeViewExpandAll tv =\n {#call tree_view_expand_all#} (toTreeView tv)\n\n-- @method treeViewCollapseAll@ Collapse all nodes in the TreeView.\n--\ntreeViewCollapseAll :: TreeViewClass tv => tv -> IO ()\ntreeViewCollapseAll tv =\n {#call tree_view_collapse_all#} (toTreeView tv)\n\n-- Expand a node that is specified by @path. If the flag @all is True every\n-- child will be expanded recursively. Returns True if the row existed and\n-- had children.(EXPORTED)\n--\ntreeViewExpandRow :: TreeViewClass tv => TreePath -> Bool -> tv -> IO Bool\ntreeViewExpandRow path all tv = liftM toBool $\n {#call tree_view_expand_row#} (toTreeView tv) path (fromBool all)\n\n-- @method treeViewCollapseRow@ Collapse a row. Returns True if the row\n-- existed.\n--\ntreeViewCollapseRow :: TreeViewClass tv => tv -> TreePath -> IO Bool\ntreeViewCollapseRow tv path = liftM toBool $\n {#call tree_view_collapse_row#} (toTreeView tv) path\n\n\n\n\n\n \n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"413f02b193cc444678d2683016e748809963f27f","subject":"Add a function that checks if Ref is null.","message":"Add a function that checks if Ref is null.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Types.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Types.chs","new_contents":"{-# LANGUAGE CPP, EmptyDataDecls, ExistentialQuantification #-}\n\n#ifdef CALLSTACK_AVAILABLE\n{-# LANGUAGE ImplicitParams #-}\n#endif\n\nmodule Graphics.UI.FLTK.LowLevel.Fl_Types where\n#include \"Fl_Types.h\"\n#include \"Fl_Text_EditorC.h\"\nimport Foreign\nimport Foreign.C hiding (CClock)\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport qualified Foreign.ForeignPtr.Unsafe as Unsafe\nimport Debug.Trace\nimport Control.Exception\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\n#ifdef CALLSTACK_AVAILABLE\nimport GHC.Stack\n#endif\nimport qualified Data.ByteString as B\n#c\n enum SliderType {\n VertSliderType = FL_VERT_SLIDER,\n HorSliderType = FL_HOR_SLIDER,\n VertFillSliderType = FL_VERT_FILL_SLIDER,\n HorFillSliderType = FL_HOR_FILL_SLIDER,\n VertNiceSliderType = FL_VERT_NICE_SLIDER,\n HorNiceSliderType = FL_HOR_NICE_SLIDER\n };\n enum ScrollbarType {\n VertScrollbar = FL_VERT_SLIDER,\n HorScrollbar = FL_HOR_SLIDER\n };\n enum BrowserType {\n NormalBrowserType = FL_NORMAL_BROWSER,\n SelectBrowserType = FL_SELECT_BROWSER,\n HoldBrowserType = FL_HOLD_BROWSER,\n MultiBrowserType = FL_MULTI_BROWSER\n };\n enum SortType {\n SortAscending = FL_SORT_ASCENDING,\n SortDescending = FL_SORT_DESCENDING\n };\n enum FileBrowserType {\n FileBrowserFiles = FL_FILE_BROWSER_FILES,\n FileBrowserDirectories = FL_FILE_BROWSER_DIRECTORIES,\n };\n enum FileIconType {\n FileIconAny = FL_FILE_ICON_ANY,\n FileIconPlain = FL_FILE_ICON_PLAIN,\n FileIconFifo = FL_FILE_ICON_FIFO,\n FileIconDevice = FL_FILE_ICON_DEVICE,\n FileIconLink = FL_FILE_ICON_LINK,\n FileIconDirectory = FL_FILE_ICON_DIRECTORY\n };\n enum FileIconProps {\n FileIconEnd = FL_FILE_ICON_END,\n FileIconColor = FL_FILE_ICON_COLOR,\n FileIconLine = FL_FILE_ICON_LINE,\n FileIconClosedline = FL_FILE_ICON_CLOSEDLINE,\n FileIconPolygon = FL_FILE_ICON_POLYGON,\n FileIconOutlinepolygon = FL_FILE_ICON_OUTLINEPOLYGON,\n FileIconVertex = FL_FILE_ICON_VERTEX\n };\n enum FileChooserType {\n FileChooserSingle = FL_FILE_CHOOSER_SINGLE,\n FileChooserMulti = FL_FILE_CHOOSER_MULTI,\n FileChooserCreate = FL_FILE_CHOOSER_CREATE,\n FileChooserDirectory = FL_FILE_CHOOSER_DIRECTORY\n };\n enum ButtonType{\n NormalButtonType = FL_NORMAL_BUTTON,\n ToggleButtonType = FL_TOGGLE_BUTTON,\n RadioButtonType = FL_RADIO_BUTTON,\n HiddenButtonType = FL_HIDDEN_BUTTON\n };\n enum TreeReasonType {\n TreeReasonNone = FL_TREE_REASON_NONE,\n TreeReasonSelected = FL_TREE_REASON_SELECTED,\n TreeReasonDeselected = FL_TREE_REASON_DESELECTED,\n#if FLTK_ABI_VERSION >= 10302\n TreeReasonReselected = FL_TREE_REASON_RESELECTED,\n#endif \/*FLTK_ABI_VERSION*\/\n TreeReasonOpened = FL_TREE_REASON_OPENED,\n TreeReasonClosed = FL_TREE_REASON_CLOSED,\n TreeReasonDragged = FL_TREE_REASON_DRAGGED\n };\n enum MenuItemFlag{\n MenuItemNormal = 0,\n MenuItemInactive = FL_MENU_INACTIVE,\n MenuItemToggle = FL_MENU_TOGGLE,\n MenuItemValue = FL_MENU_VALUE,\n MenuItemRadio = FL_MENU_RADIO,\n MenuItemInvisible = FL_MENU_INVISIBLE,\n SubmenuPointer = FL_SUBMENU_POINTER,\n Submenu = FL_SUBMENU,\n MenuItemDivider = FL_MENU_DIVIDER,\n MenuItemHorizontal = FL_MENU_HORIZONTAL\n };\n enum ScrollbarMode {\n HorizontalScrollBar = HORIZONTAL,\n VerticalScrollBar = VERTICAL,\n BothScrollBar = BOTH,\n AlwaysOnScrollBar = ALWAYS_ON,\n HorizontalAlwaysScrollBar = HORIZONTAL_ALWAYS,\n VerticalAlwaysScrollBar = VERTICAL_ALWAYS,\n BothAlwaysScrollBar = BOTH_ALWAYS\n };\n enum CursorType {\n NormalCursor = NORMAL_CURSOR,\n CaretCursor = CARET_CURSOR,\n DimCursor = DIM_CURSOR,\n BlockCursor = BLOCK_CURSOR,\n HeavyCursor = HEAVY_CURSOR,\n SimpleCursor = SIMPLE_CURSOR\n };\n enum PositionType {\n CursorPos = CURSOR_POS,\n CharacterPos = CHARACTER_POS\n };\n enum DragType {\n DragNone = DRAG_NONE,\n DragStartDnd = DRAG_START_DND,\n DragChar = DRAG_CHAR,\n DragWord = DRAG_WORD,\n DragLine = DRAG_LINE\n };\n enum WrapType {\n WrapNone = WRAP_NONE,\n WrapAtColumn = WRAP_AT_COLUMN,\n WrapAtPixel = WRAP_AT_PIXEL,\n WrapAtBounds = WRAP_AT_BOUNDS\n };\n enum PageFormat {\n A0 = 0,\n A1 = 1,\n A2 = 2,\n A3 = 3,\n A4 = 4,\n A5 = 5,\n A6 = 6,\n A7 = 7,\n A8 = 8,\n A9 = 9,\n B0 = 10,\n B1 = 11,\n B2 = 12,\n B3 = 13,\n B4 = 14,\n B5 = 15,\n B6 = 16,\n B7 = 17,\n B8 = 18,\n B9 = 19,\n B10 = 20,\n C5E = 21,\n DLE = 22,\n Executive = EXECUTIVE,\n Folio = FOLIO,\n Ledger = LEDGER,\n Legal = LEGAL,\n Letter = LETTER,\n Tabloid = TABLOID,\n Envelope = ENVELOPE,\n Media = MEDIA\n };\n enum PageLayout {\n Portrait = PORTRAIT,\n Landscape = LANDSCAPE,\n Reversed = REVERSED,\n Orientation = ORIENTATION\n };\n typedef struct KeyBinding {\n int key;\n int state;\n fl_Key_Func* function;\n } KeyBinding;\n enum TableRowSelectMode {\n SelectNone = SELECT_NONEC,\n SelectSingle = SELECT_SINGLEC,\n SelectMulti = SELECT_MULTIC\n };\n enum TableContext {\n ContextNone = CONTEXT_NONEC,\n ContextStartPage = CONTEXT_STARTPAGEC,\n ContextEndPage = CONTEXT_ENDPAGEC,\n ContextRowHeader = CONTEXT_ROW_HEADERC,\n ContextColHeader = CONTEXT_COL_HEADERC,\n ContextCell = CONTEXT_CELLC,\n ContextTable = CONTEXT_TABLEC,\n ContextRCResize = CONTEXT_RC_RESIZEC\n };\n enum LinePosition {\n LinePositionTop = TOP,\n LinePositionMiddle = MIDDLE,\n LinePositionBottom = BOTTOM\n };\n enum PackType {\n PackVertical = PACK_VERTICAL,\n PackHorizontal = PACK_HORIZONTAL\n };\n typedef FL_SOCKET Fl_Socket;\n\n enum ColorChooserMode {\n RgbMode = 0,\n ByteMode = 1,\n HexMode = 2,\n HsvMode = 3\n };\n#endc\n{#enum SliderType {} deriving (Show, Eq) #}\n{#enum ScrollbarType {} deriving (Show, Eq) #}\n{#enum BrowserType {} deriving (Show, Eq) #}\n{#enum SortType {} deriving (Show, Eq) #}\n{#enum FileBrowserType {} deriving (Show, Eq) #}\n{#enum FileIconType {} deriving (Show, Eq) #}\n{#enum FileIconProps {} deriving (Show, Eq) #}\n{#enum FileChooserType {} deriving (Show, Eq) #}\n{#enum ButtonType {} deriving (Show, Eq) #}\n{#enum TreeReasonType {} deriving (Show, Eq) #}\n{#enum MenuItemFlag {} deriving (Show, Eq, Ord) #}\n{#enum ColorChooserMode {} deriving (Show, Eq, Ord) #}\nnewtype MenuItemFlags = MenuItemFlags [MenuItemFlag] deriving Show\nallMenuItemFlags :: [MenuItemFlag]\nallMenuItemFlags =\n [\n MenuItemInactive,\n MenuItemToggle,\n MenuItemValue,\n MenuItemRadio,\n MenuItemInvisible,\n SubmenuPointer,\n Submenu,\n MenuItemDivider,\n MenuItemHorizontal\n ]\n{#enum CursorType {} deriving (Show, Eq) #}\n{#enum PositionType {} deriving (Show, Eq) #}\n{#enum DragType {} deriving (Show, Eq) #}\n{#enum WrapType {} deriving (Show, Eq) #}\n{#enum PageFormat {} deriving (Show, Eq) #}\n{#enum PageLayout {} deriving (Show, Eq) #}\n{#enum TableRowSelectMode {} deriving (Show, Eq) #}\n{#enum TableContext {} deriving (Show, Eq) #}\n{#enum LinePosition {} deriving (Show, Eq) #}\n{#enum ScrollbarMode {} deriving (Show, Eq) #}\ndata StyleTableEntry = StyleTableEntry (Maybe Color) (Maybe Font) (Maybe FontSize) deriving Show\n\n{#enum PackType{} deriving (Show, Eq, Ord) #}\n\ndata GLUTproc = GLUTproc {#type GLUTproc#} deriving Show\nnewtype GLUTIdleFunction = GLUTIdleFunction (FunPtr (IO ()))\nnewtype GLUTMenuStateFunction = GLUTMenuStateFunction (FunPtr (CInt -> IO()))\nnewtype GLUTMenuStatusFunction = GLUTMenuStatusFunction\n (FunPtr (CInt -> CInt -> CInt -> IO ()))\n{#pointer *Fl_Glut_Bitmap_Font as GlutBitmapFontPtr newtype #}\n{#pointer *Fl_Glut_StrokeVertex as GlutStrokeVertexPtr newtype#}\n{#pointer *Fl_Glut_StrokeStrip as GlutStrokeStripPtr newtype#}\n{#pointer *Fl_Glut_StrokeFont as GlutStrokeFontPtr newtype#}\ntype FlShortcut = {#type Fl_Shortcut #}\ntype FlColor = {#type Fl_Color #}\ntype FlFont = {#type Fl_Font #}\ntype FlAlign = {#type Fl_Align #}\ntype LineDelta = Maybe Int\ntype Delta = Maybe Int\ntype FlIntPtr = {#type fl_intptr_t #}\ntype FlUIntPtr = {#type fl_uintptr_t#}\ntype ID = {#type ID#}\ndata Ref a = Ref !(ForeignPtr (Ptr ())) deriving (Eq, Show)\ndata FunRef = FunRef !(FunPtr ())\n-- * The FLTK widget hierarchy\ndata CBase parent\ntype Base = CBase ()\n\ntype GlobalCallback = IO ()\ntype CallbackWithUserDataPrim = Ptr () -> Ptr () -> IO ()\ntype CallbackPrim = Ptr () -> IO ()\ntype ColorAverageCallbackPrim = Ptr () -> CUInt -> CFloat -> IO ()\ntype ImageDrawCallbackPrim = Ptr () -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()\ntype ImageCopyCallbackPrim = Ptr () -> CInt -> CInt -> IO (Ptr ())\ntype GlobalEventHandlerPrim = CInt -> IO CInt\ntype GlobalEventHandlerF = Event -> IO Int\ntype DrawCallback = String -> Position -> IO ()\ntype DrawCallbackPrim = CString -> CInt -> CInt -> CInt -> IO ()\ntype TextBufferCallback = FunPtr (Ptr () -> IO ())\ntype FileChooserCallback = FunPtr (Ptr () -> Ptr () -> IO())\ntype SharedImageHandler = FunPtr (CString -> CUChar -> CInt -> Ptr ())\ntype BoxDrawF = Rectangle -> Color -> IO ()\ntype BoxDrawFPrim = CInt -> CInt -> CInt -> CInt -> FlColor -> IO ()\ntype TextModifyCb = Int -> Int -> Int -> Int -> String -> IO ()\ntype TextModifyCbPrim = CInt -> CInt -> CInt -> CInt -> Ptr CChar -> Ptr () -> IO ()\ntype TextPredeleteCb = BufferOffset -> Int -> IO ()\ntype TextPredeleteCbPrim = CInt -> CInt -> Ptr () -> IO ()\ntype UnfinishedStyleCb = BufferOffset -> IO ()\ntype UnfinishedStyleCbPrim = CInt -> Ptr () -> IO ()\n\nnewtype Width = Width Int deriving (Eq, Show)\nnewtype Height = Height Int deriving (Eq, Show)\nnewtype Depth = Depth Int deriving Show\nnewtype LineSize = LineSize Int deriving Show\nnewtype X = X Int deriving (Eq, Show)\nnewtype Y = Y Int deriving (Eq, Show)\nnewtype ByX = ByX Double deriving Show\nnewtype ByY = ByY Double deriving Show\nnewtype Angle = Angle CShort deriving Show\ndata Position = Position X Y deriving (Eq,Show)\ndata CountDirection = CountUp | CountDown deriving Show\ndata DPI = DPI Float Float deriving Show\nnewtype TextDisplayStyle = TextDisplayStyle CInt deriving Show\nnewtype BufferOffset = BufferOffset Int deriving Show\ndata BufferRange = BufferRange BufferOffset BufferOffset deriving Show\nstatusToBufferRange :: (Ptr CInt -> Ptr CInt -> IO Int) -> IO (Maybe BufferRange)\nstatusToBufferRange f =\n alloca $ \\start' ->\n alloca $ \\end' ->\n f start' end' >>= \\status' ->\n case status' of\n 0 -> return Nothing\n _ -> do\n start'' <- peekIntConv start'\n end'' <- peekIntConv end'\n return (Just (BufferRange (BufferOffset start'') (BufferOffset end'')))\n\ndata ColorChooserRGB = Decimals (Between0And1, Between0And1, Between0And1) | Words RGB deriving Show\ndata Rectangle = Rectangle Position Size deriving (Eq,Show)\ndata ByXY = ByXY ByX ByY deriving Show\ndata Intersection = Contained | Partial deriving Show\ndata Size = Size Width Height deriving (Eq, Show)\ndata KeyType = SpecialKeyType SpecialKey | NormalKeyType Char deriving (Show, Eq)\ndata ShortcutKeySequence = ShortcutKeySequence [EventState] KeyType deriving Show\ndata Shortcut = KeySequence ShortcutKeySequence | KeyFormat String deriving Show\ndata KeyBindingKeySequence = KeyBindingKeySequence (Maybe [EventState]) KeyType deriving Show\nnewtype Between0And1 = Between0And1 Double deriving Show\nnewtype Between0And6 = Between0And6 Double deriving Show\ndata ScreenLocation = Intersect Rectangle\n | ScreenNumber Int\n | ScreenPosition Position deriving Show\nnewtype FontSize = FontSize CInt deriving Show\nnewtype PixmapHs = PixmapHs [String] deriving Show\ndata BitmapHs = BitmapHs B.ByteString Size deriving Show\ndata Clipboard = InternalClipboard | SharedClipboard deriving Show\ndata UnknownError = UnknownError deriving Show\ndata NotFound = NotFound deriving Show\ndata OutOfRange = OutOfRange deriving Show\nsuccessOrOutOfRange :: a -> Bool -> (a -> IO b) -> IO (Either OutOfRange b)\nsuccessOrOutOfRange a pred' tr = if pred' then return (Left OutOfRange) else tr a >>= return . Right\ndata NoChange = NoChange deriving Show\nsuccessOrNoChange :: Int -> Either NoChange ()\nsuccessOrNoChange status = if (status == 0) then Left NoChange else Right ()\ndata DataProcessingError = NoDataProcessedError | PartialDataProcessedError | UnknownDataError Int\nsuccessOrDataProcessingError :: Int -> Either DataProcessingError ()\nsuccessOrDataProcessingError status = case status of\n 0 -> Right ()\n 1 -> Left NoDataProcessedError\n 2 -> Left PartialDataProcessedError\n x -> Left $ UnknownDataError x\ntoRectangle :: (Int,Int,Int,Int) -> Rectangle\ntoRectangle (x_pos, y_pos, width, height) =\n Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))\n\nfromRectangle :: Rectangle -> (Int,Int,Int,Int)\nfromRectangle (Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n (x_pos, y_pos, width, height)\n\ntoSize :: (Int, Int) -> Size\ntoSize (width', height') = Size (Width width') (Height height')\n\nthrowStackOnError :: IO a -> IO a\nthrowStackOnError f =\n f `catch` throwStack\n where\n throwStack :: SomeException -> IO b\n throwStack e = traceStack (show e) $ error \"\"\n\nwithForeignPtrs :: [ForeignPtr a] -> ([Ptr a] -> IO c) -> IO c\nwithForeignPtrs fptrs io = do\n let ptrs = map Unsafe.unsafeForeignPtrToPtr fptrs\n r <- io ptrs\n mapM_ touchForeignPtr fptrs\n return r\n\n#ifdef CALLSTACK_AVAILABLE\ntoRefPtr :: (?loc :: CallStack) => Ptr (Ptr a) -> IO (Ptr a)\n#else\ntoRefPtr :: Ptr (Ptr a) -> IO (Ptr a)\n#endif\ntoRefPtr ptrToRefPtr = do\n refPtr <- peek ptrToRefPtr\n if (refPtr == nullPtr)\n#ifdef CALLSTACK_AVAILABLE\n then error $ \"Ref does not exist. \" ++ (showCallStack ?loc)\n#else\n then error \"Ref does not exist. \"\n#endif\n else return refPtr\n\n#ifdef CALLSTACK_AVAILABLE\nwithRef :: (?loc :: CallStack) => Ref a -> (Ptr b -> IO c) -> IO c\n#else\nwithRef :: Ref a -> (Ptr b -> IO c) -> IO c\n#endif\nwithRef (Ref fptr) f =\n throwStackOnError $\n withForeignPtr fptr\n (\\ptrToRefPtr -> do\n refPtr <- toRefPtr ptrToRefPtr\n f (castPtr refPtr)\n )\n\nisNull :: Ref a -> IO Bool\nisNull (Ref fptr) =\n withForeignPtr fptr $\n (\\ptrToRefPtr -> do\n refPtr <- peek ptrToRefPtr\n if (refPtr == nullPtr)\n then return True\n else return False\n )\n\nunsafeRefToPtr :: Ref a -> IO (Ptr ())\nunsafeRefToPtr (Ref fptr) =\n throwStackOnError $ do\n refPtr <- toRefPtr $ Unsafe.unsafeForeignPtrToPtr fptr\n return $ castPtr refPtr\n\nwithRefs :: [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\nwithRefs refs f =\n throwStackOnError\n $ withForeignPtrs\n (map (\\(Ref fptr) -> fptr) refs)\n (\\ptrToRefPtrs -> do\n refPtrs <- mapM toRefPtr ptrToRefPtrs\n arrayPtr <- newArray refPtrs\n f (castPtr arrayPtr)\n )\n\nwithMaybeRef :: Maybe (Ref a) -> (Ptr () -> IO c) -> IO c\nwithMaybeRef (Just o) f = withRef o f\nwithMaybeRef Nothing f = f (castPtr nullPtr)\n\nswapRef :: Ref a -> (Ptr b -> IO (Ptr ())) -> IO ()\nswapRef ref@(Ref fptr) f = do\n result <- withRef ref f\n withForeignPtr fptr $ \\p -> poke p result\n\nwrapInRef :: ForeignPtr (Ptr ()) -> Ref a\nwrapInRef = Ref . castForeignPtr\n\ntoFunRef :: FunPtr a -> FunRef\ntoFunRef fptr = FunRef $ castFunPtr fptr\n\nfromFunRef :: FunRef -> (FunPtr ())\nfromFunRef (FunRef f) = castFunPtr f\n","old_contents":"{-# LANGUAGE CPP, EmptyDataDecls, ExistentialQuantification #-}\n\n#ifdef CALLSTACK_AVAILABLE\n{-# LANGUAGE ImplicitParams #-}\n#endif\n\nmodule Graphics.UI.FLTK.LowLevel.Fl_Types where\n#include \"Fl_Types.h\"\n#include \"Fl_Text_EditorC.h\"\nimport Foreign\nimport Foreign.C hiding (CClock)\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport qualified Foreign.ForeignPtr.Unsafe as Unsafe\nimport Debug.Trace\nimport Control.Exception\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\n#ifdef CALLSTACK_AVAILABLE\nimport GHC.Stack\n#endif\nimport qualified Data.ByteString as B\n#c\n enum SliderType {\n VertSliderType = FL_VERT_SLIDER,\n HorSliderType = FL_HOR_SLIDER,\n VertFillSliderType = FL_VERT_FILL_SLIDER,\n HorFillSliderType = FL_HOR_FILL_SLIDER,\n VertNiceSliderType = FL_VERT_NICE_SLIDER,\n HorNiceSliderType = FL_HOR_NICE_SLIDER\n };\n enum ScrollbarType {\n VertScrollbar = FL_VERT_SLIDER,\n HorScrollbar = FL_HOR_SLIDER\n };\n enum BrowserType {\n NormalBrowserType = FL_NORMAL_BROWSER,\n SelectBrowserType = FL_SELECT_BROWSER,\n HoldBrowserType = FL_HOLD_BROWSER,\n MultiBrowserType = FL_MULTI_BROWSER\n };\n enum SortType {\n SortAscending = FL_SORT_ASCENDING,\n SortDescending = FL_SORT_DESCENDING\n };\n enum FileBrowserType {\n FileBrowserFiles = FL_FILE_BROWSER_FILES,\n FileBrowserDirectories = FL_FILE_BROWSER_DIRECTORIES,\n };\n enum FileIconType {\n FileIconAny = FL_FILE_ICON_ANY,\n FileIconPlain = FL_FILE_ICON_PLAIN,\n FileIconFifo = FL_FILE_ICON_FIFO,\n FileIconDevice = FL_FILE_ICON_DEVICE,\n FileIconLink = FL_FILE_ICON_LINK,\n FileIconDirectory = FL_FILE_ICON_DIRECTORY\n };\n enum FileIconProps {\n FileIconEnd = FL_FILE_ICON_END,\n FileIconColor = FL_FILE_ICON_COLOR,\n FileIconLine = FL_FILE_ICON_LINE,\n FileIconClosedline = FL_FILE_ICON_CLOSEDLINE,\n FileIconPolygon = FL_FILE_ICON_POLYGON,\n FileIconOutlinepolygon = FL_FILE_ICON_OUTLINEPOLYGON,\n FileIconVertex = FL_FILE_ICON_VERTEX\n };\n enum FileChooserType {\n FileChooserSingle = FL_FILE_CHOOSER_SINGLE,\n FileChooserMulti = FL_FILE_CHOOSER_MULTI,\n FileChooserCreate = FL_FILE_CHOOSER_CREATE,\n FileChooserDirectory = FL_FILE_CHOOSER_DIRECTORY\n };\n enum ButtonType{\n NormalButtonType = FL_NORMAL_BUTTON,\n ToggleButtonType = FL_TOGGLE_BUTTON,\n RadioButtonType = FL_RADIO_BUTTON,\n HiddenButtonType = FL_HIDDEN_BUTTON\n };\n enum TreeReasonType {\n TreeReasonNone = FL_TREE_REASON_NONE,\n TreeReasonSelected = FL_TREE_REASON_SELECTED,\n TreeReasonDeselected = FL_TREE_REASON_DESELECTED,\n#if FLTK_ABI_VERSION >= 10302\n TreeReasonReselected = FL_TREE_REASON_RESELECTED,\n#endif \/*FLTK_ABI_VERSION*\/\n TreeReasonOpened = FL_TREE_REASON_OPENED,\n TreeReasonClosed = FL_TREE_REASON_CLOSED,\n TreeReasonDragged = FL_TREE_REASON_DRAGGED\n };\n enum MenuItemFlag{\n MenuItemNormal = 0,\n MenuItemInactive = FL_MENU_INACTIVE,\n MenuItemToggle = FL_MENU_TOGGLE,\n MenuItemValue = FL_MENU_VALUE,\n MenuItemRadio = FL_MENU_RADIO,\n MenuItemInvisible = FL_MENU_INVISIBLE,\n SubmenuPointer = FL_SUBMENU_POINTER,\n Submenu = FL_SUBMENU,\n MenuItemDivider = FL_MENU_DIVIDER,\n MenuItemHorizontal = FL_MENU_HORIZONTAL\n };\n enum ScrollbarMode {\n HorizontalScrollBar = HORIZONTAL,\n VerticalScrollBar = VERTICAL,\n BothScrollBar = BOTH,\n AlwaysOnScrollBar = ALWAYS_ON,\n HorizontalAlwaysScrollBar = HORIZONTAL_ALWAYS,\n VerticalAlwaysScrollBar = VERTICAL_ALWAYS,\n BothAlwaysScrollBar = BOTH_ALWAYS\n };\n enum CursorType {\n NormalCursor = NORMAL_CURSOR,\n CaretCursor = CARET_CURSOR,\n DimCursor = DIM_CURSOR,\n BlockCursor = BLOCK_CURSOR,\n HeavyCursor = HEAVY_CURSOR,\n SimpleCursor = SIMPLE_CURSOR\n };\n enum PositionType {\n CursorPos = CURSOR_POS,\n CharacterPos = CHARACTER_POS\n };\n enum DragType {\n DragNone = DRAG_NONE,\n DragStartDnd = DRAG_START_DND,\n DragChar = DRAG_CHAR,\n DragWord = DRAG_WORD,\n DragLine = DRAG_LINE\n };\n enum WrapType {\n WrapNone = WRAP_NONE,\n WrapAtColumn = WRAP_AT_COLUMN,\n WrapAtPixel = WRAP_AT_PIXEL,\n WrapAtBounds = WRAP_AT_BOUNDS\n };\n enum PageFormat {\n A0 = 0,\n A1 = 1,\n A2 = 2,\n A3 = 3,\n A4 = 4,\n A5 = 5,\n A6 = 6,\n A7 = 7,\n A8 = 8,\n A9 = 9,\n B0 = 10,\n B1 = 11,\n B2 = 12,\n B3 = 13,\n B4 = 14,\n B5 = 15,\n B6 = 16,\n B7 = 17,\n B8 = 18,\n B9 = 19,\n B10 = 20,\n C5E = 21,\n DLE = 22,\n Executive = EXECUTIVE,\n Folio = FOLIO,\n Ledger = LEDGER,\n Legal = LEGAL,\n Letter = LETTER,\n Tabloid = TABLOID,\n Envelope = ENVELOPE,\n Media = MEDIA\n };\n enum PageLayout {\n Portrait = PORTRAIT,\n Landscape = LANDSCAPE,\n Reversed = REVERSED,\n Orientation = ORIENTATION\n };\n typedef struct KeyBinding {\n int key;\n int state;\n fl_Key_Func* function;\n } KeyBinding;\n enum TableRowSelectMode {\n SelectNone = SELECT_NONEC,\n SelectSingle = SELECT_SINGLEC,\n SelectMulti = SELECT_MULTIC\n };\n enum TableContext {\n ContextNone = CONTEXT_NONEC,\n ContextStartPage = CONTEXT_STARTPAGEC,\n ContextEndPage = CONTEXT_ENDPAGEC,\n ContextRowHeader = CONTEXT_ROW_HEADERC,\n ContextColHeader = CONTEXT_COL_HEADERC,\n ContextCell = CONTEXT_CELLC,\n ContextTable = CONTEXT_TABLEC,\n ContextRCResize = CONTEXT_RC_RESIZEC\n };\n enum LinePosition {\n LinePositionTop = TOP,\n LinePositionMiddle = MIDDLE,\n LinePositionBottom = BOTTOM\n };\n enum PackType {\n PackVertical = PACK_VERTICAL,\n PackHorizontal = PACK_HORIZONTAL\n };\n typedef FL_SOCKET Fl_Socket;\n\n enum ColorChooserMode {\n RgbMode = 0,\n ByteMode = 1,\n HexMode = 2,\n HsvMode = 3\n };\n#endc\n{#enum SliderType {} deriving (Show, Eq) #}\n{#enum ScrollbarType {} deriving (Show, Eq) #}\n{#enum BrowserType {} deriving (Show, Eq) #}\n{#enum SortType {} deriving (Show, Eq) #}\n{#enum FileBrowserType {} deriving (Show, Eq) #}\n{#enum FileIconType {} deriving (Show, Eq) #}\n{#enum FileIconProps {} deriving (Show, Eq) #}\n{#enum FileChooserType {} deriving (Show, Eq) #}\n{#enum ButtonType {} deriving (Show, Eq) #}\n{#enum TreeReasonType {} deriving (Show, Eq) #}\n{#enum MenuItemFlag {} deriving (Show, Eq, Ord) #}\n{#enum ColorChooserMode {} deriving (Show, Eq, Ord) #}\nnewtype MenuItemFlags = MenuItemFlags [MenuItemFlag] deriving Show\nallMenuItemFlags :: [MenuItemFlag]\nallMenuItemFlags =\n [\n MenuItemInactive,\n MenuItemToggle,\n MenuItemValue,\n MenuItemRadio,\n MenuItemInvisible,\n SubmenuPointer,\n Submenu,\n MenuItemDivider,\n MenuItemHorizontal\n ]\n{#enum CursorType {} deriving (Show, Eq) #}\n{#enum PositionType {} deriving (Show, Eq) #}\n{#enum DragType {} deriving (Show, Eq) #}\n{#enum WrapType {} deriving (Show, Eq) #}\n{#enum PageFormat {} deriving (Show, Eq) #}\n{#enum PageLayout {} deriving (Show, Eq) #}\n{#enum TableRowSelectMode {} deriving (Show, Eq) #}\n{#enum TableContext {} deriving (Show, Eq) #}\n{#enum LinePosition {} deriving (Show, Eq) #}\n{#enum ScrollbarMode {} deriving (Show, Eq) #}\ndata StyleTableEntry = StyleTableEntry (Maybe Color) (Maybe Font) (Maybe FontSize) deriving Show\n\n{#enum PackType{} deriving (Show, Eq, Ord) #}\n\ndata GLUTproc = GLUTproc {#type GLUTproc#} deriving Show\nnewtype GLUTIdleFunction = GLUTIdleFunction (FunPtr (IO ()))\nnewtype GLUTMenuStateFunction = GLUTMenuStateFunction (FunPtr (CInt -> IO()))\nnewtype GLUTMenuStatusFunction = GLUTMenuStatusFunction\n (FunPtr (CInt -> CInt -> CInt -> IO ()))\n{#pointer *Fl_Glut_Bitmap_Font as GlutBitmapFontPtr newtype #}\n{#pointer *Fl_Glut_StrokeVertex as GlutStrokeVertexPtr newtype#}\n{#pointer *Fl_Glut_StrokeStrip as GlutStrokeStripPtr newtype#}\n{#pointer *Fl_Glut_StrokeFont as GlutStrokeFontPtr newtype#}\ntype FlShortcut = {#type Fl_Shortcut #}\ntype FlColor = {#type Fl_Color #}\ntype FlFont = {#type Fl_Font #}\ntype FlAlign = {#type Fl_Align #}\ntype LineDelta = Maybe Int\ntype Delta = Maybe Int\ntype FlIntPtr = {#type fl_intptr_t #}\ntype FlUIntPtr = {#type fl_uintptr_t#}\ntype ID = {#type ID#}\ndata Ref a = Ref !(ForeignPtr (Ptr ())) deriving (Eq, Show)\ndata FunRef = FunRef !(FunPtr ())\n-- * The FLTK widget hierarchy\ndata CBase parent\ntype Base = CBase ()\n\ntype GlobalCallback = IO ()\ntype CallbackWithUserDataPrim = Ptr () -> Ptr () -> IO ()\ntype CallbackPrim = Ptr () -> IO ()\ntype ColorAverageCallbackPrim = Ptr () -> CUInt -> CFloat -> IO ()\ntype ImageDrawCallbackPrim = Ptr () -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()\ntype ImageCopyCallbackPrim = Ptr () -> CInt -> CInt -> IO (Ptr ())\ntype GlobalEventHandlerPrim = CInt -> IO CInt\ntype GlobalEventHandlerF = Event -> IO Int\ntype DrawCallback = String -> Position -> IO ()\ntype DrawCallbackPrim = CString -> CInt -> CInt -> CInt -> IO ()\ntype TextBufferCallback = FunPtr (Ptr () -> IO ())\ntype FileChooserCallback = FunPtr (Ptr () -> Ptr () -> IO())\ntype SharedImageHandler = FunPtr (CString -> CUChar -> CInt -> Ptr ())\ntype BoxDrawF = Rectangle -> Color -> IO ()\ntype BoxDrawFPrim = CInt -> CInt -> CInt -> CInt -> FlColor -> IO ()\ntype TextModifyCb = Int -> Int -> Int -> Int -> String -> IO ()\ntype TextModifyCbPrim = CInt -> CInt -> CInt -> CInt -> Ptr CChar -> Ptr () -> IO ()\ntype TextPredeleteCb = BufferOffset -> Int -> IO ()\ntype TextPredeleteCbPrim = CInt -> CInt -> Ptr () -> IO ()\ntype UnfinishedStyleCb = BufferOffset -> IO ()\ntype UnfinishedStyleCbPrim = CInt -> Ptr () -> IO ()\n\nnewtype Width = Width Int deriving (Eq, Show)\nnewtype Height = Height Int deriving (Eq, Show)\nnewtype Depth = Depth Int deriving Show\nnewtype LineSize = LineSize Int deriving Show\nnewtype X = X Int deriving (Eq, Show)\nnewtype Y = Y Int deriving (Eq, Show)\nnewtype ByX = ByX Double deriving Show\nnewtype ByY = ByY Double deriving Show\nnewtype Angle = Angle CShort deriving Show\ndata Position = Position X Y deriving (Eq,Show)\ndata CountDirection = CountUp | CountDown deriving Show\ndata DPI = DPI Float Float deriving Show\nnewtype TextDisplayStyle = TextDisplayStyle CInt deriving Show\nnewtype BufferOffset = BufferOffset Int deriving Show\ndata BufferRange = BufferRange BufferOffset BufferOffset deriving Show\nstatusToBufferRange :: (Ptr CInt -> Ptr CInt -> IO Int) -> IO (Maybe BufferRange)\nstatusToBufferRange f =\n alloca $ \\start' ->\n alloca $ \\end' ->\n f start' end' >>= \\status' ->\n case status' of\n 0 -> return Nothing\n _ -> do\n start'' <- peekIntConv start'\n end'' <- peekIntConv end'\n return (Just (BufferRange (BufferOffset start'') (BufferOffset end'')))\n\ndata ColorChooserRGB = Decimals (Between0And1, Between0And1, Between0And1) | Words RGB deriving Show\ndata Rectangle = Rectangle Position Size deriving (Eq,Show)\ndata ByXY = ByXY ByX ByY deriving Show\ndata Intersection = Contained | Partial deriving Show\ndata Size = Size Width Height deriving (Eq, Show)\ndata KeyType = SpecialKeyType SpecialKey | NormalKeyType Char deriving (Show, Eq)\ndata ShortcutKeySequence = ShortcutKeySequence [EventState] KeyType deriving Show\ndata Shortcut = KeySequence ShortcutKeySequence | KeyFormat String deriving Show\ndata KeyBindingKeySequence = KeyBindingKeySequence (Maybe [EventState]) KeyType deriving Show\nnewtype Between0And1 = Between0And1 Double deriving Show\nnewtype Between0And6 = Between0And6 Double deriving Show\ndata ScreenLocation = Intersect Rectangle\n | ScreenNumber Int\n | ScreenPosition Position deriving Show\nnewtype FontSize = FontSize CInt deriving Show\nnewtype PixmapHs = PixmapHs [String] deriving Show\ndata BitmapHs = BitmapHs B.ByteString Size deriving Show\ndata Clipboard = InternalClipboard | SharedClipboard deriving Show\ndata UnknownError = UnknownError deriving Show\ndata NotFound = NotFound deriving Show\ndata OutOfRange = OutOfRange deriving Show\nsuccessOrOutOfRange :: a -> Bool -> (a -> IO b) -> IO (Either OutOfRange b)\nsuccessOrOutOfRange a pred' tr = if pred' then return (Left OutOfRange) else tr a >>= return . Right\ndata NoChange = NoChange deriving Show\nsuccessOrNoChange :: Int -> Either NoChange ()\nsuccessOrNoChange status = if (status == 0) then Left NoChange else Right ()\ndata DataProcessingError = NoDataProcessedError | PartialDataProcessedError | UnknownDataError Int\nsuccessOrDataProcessingError :: Int -> Either DataProcessingError ()\nsuccessOrDataProcessingError status = case status of\n 0 -> Right ()\n 1 -> Left NoDataProcessedError\n 2 -> Left PartialDataProcessedError\n x -> Left $ UnknownDataError x\ntoRectangle :: (Int,Int,Int,Int) -> Rectangle\ntoRectangle (x_pos, y_pos, width, height) =\n Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))\n\nfromRectangle :: Rectangle -> (Int,Int,Int,Int)\nfromRectangle (Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n (x_pos, y_pos, width, height)\n\ntoSize :: (Int, Int) -> Size\ntoSize (width', height') = Size (Width width') (Height height')\n\nthrowStackOnError :: IO a -> IO a\nthrowStackOnError f =\n f `catch` throwStack\n where\n throwStack :: SomeException -> IO b\n throwStack e = traceStack (show e) $ error \"\"\n\nwithForeignPtrs :: [ForeignPtr a] -> ([Ptr a] -> IO c) -> IO c\nwithForeignPtrs fptrs io = do\n let ptrs = map Unsafe.unsafeForeignPtrToPtr fptrs\n r <- io ptrs\n mapM_ touchForeignPtr fptrs\n return r\n\n#ifdef CALLSTACK_AVAILABLE\ntoRefPtr :: (?loc :: CallStack) => Ptr (Ptr a) -> IO (Ptr a)\n#else\ntoRefPtr :: Ptr (Ptr a) -> IO (Ptr a)\n#endif\ntoRefPtr ptrToRefPtr = do\n refPtr <- peek ptrToRefPtr\n if (refPtr == nullPtr)\n#ifdef CALLSTACK_AVAILABLE\n then error $ \"Ref does not exist. \" ++ (showCallStack ?loc)\n#else\n then error \"Ref does not exist. \"\n#endif\n else return refPtr\n\n#ifdef CALLSTACK_AVAILABLE\nwithRef :: (?loc :: CallStack) => Ref a -> (Ptr b -> IO c) -> IO c\n#else\nwithRef :: Ref a -> (Ptr b -> IO c) -> IO c\n#endif\nwithRef (Ref fptr) f =\n throwStackOnError $\n withForeignPtr fptr\n (\\ptrToRefPtr -> do\n refPtr <- toRefPtr ptrToRefPtr\n f (castPtr refPtr)\n )\n\nunsafeRefToPtr :: Ref a -> IO (Ptr ())\nunsafeRefToPtr (Ref fptr) =\n throwStackOnError $ do\n refPtr <- toRefPtr $ Unsafe.unsafeForeignPtrToPtr fptr\n return $ castPtr refPtr\n\nwithRefs :: [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\nwithRefs refs f =\n throwStackOnError\n $ withForeignPtrs\n (map (\\(Ref fptr) -> fptr) refs)\n (\\ptrToRefPtrs -> do\n refPtrs <- mapM toRefPtr ptrToRefPtrs\n arrayPtr <- newArray refPtrs\n f (castPtr arrayPtr)\n )\n\nwithMaybeRef :: Maybe (Ref a) -> (Ptr () -> IO c) -> IO c\nwithMaybeRef (Just o) f = withRef o f\nwithMaybeRef Nothing f = f (castPtr nullPtr)\n\nswapRef :: Ref a -> (Ptr b -> IO (Ptr ())) -> IO ()\nswapRef ref@(Ref fptr) f = do\n result <- withRef ref f\n withForeignPtr fptr $ \\p -> poke p result\n\nwrapInRef :: ForeignPtr (Ptr ()) -> Ref a\nwrapInRef = Ref . castForeignPtr\n\ntoFunRef :: FunPtr a -> FunRef\ntoFunRef fptr = FunRef $ castFunPtr fptr\n\nfromFunRef :: FunRef -> (FunPtr ())\nfromFunRef (FunRef f) = castFunPtr f\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"ec2671bcc73c0ae8eadb02e5fe72c8c194aca893","subject":"GLDrawingArea: provide implementation for GObjectClass","message":"GLDrawingArea: provide implementation for GObjectClass\n\nWithout this patch, trying to use a GLDrawingArea results in\n program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject\n\ndarcs-hash:20071031134717-ef904-866f627ea313aadf4321c9d6f0df5396e1e99cf3.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea where\n toGObject (GLDrawingArea gd) = toGObject gd\n unsafeCastGObject = GLDrawingArea . unsafeCastGObject\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"4b1faffa574e76ab77803819d9f1b456c92aeadd","subject":"gnomevfs: use c2hs {#enum#} for FilePermissions instead of hand coding it","message":"gnomevfs: use c2hs {#enum#} for FilePermissions instead of hand coding it\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer","old_file":"gnomevfs\/System\/Gnome\/VFS\/Types.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Types (\n \n Handle(..),\n withHandle,\n \n Result(..),\n Error(..),\n \n OpenMode(..),\n SeekPosition(..),\n \n FileInfo(..),\n FileFlags(..),\n FileInfoFields(..),\n SetFileInfoMask(..),\n FileInfoOptions(..),\n FilePermissions(..),\n FileSize,\n FileOffset,\n FileType(..),\n InodeNumber,\n IDs,\n \n MonitorHandle(..),\n withMonitorHandle,\n MonitorCallback,\n MonitorType,\n MonitorEventType,\n \n URI(..),\n TextURI,\n newURI,\n withURI,\n ToplevelURI(..),\n newToplevelURI,\n withToplevelURI,\n URIHideOptions(..),\n \n DirectoryHandle(..),\n withDirectoryHandle,\n \n MakeURIDirs(..),\n DirectoryVisitOptions(..),\n DirectoryVisitCallback,\n DirectoryVisitResult(..),\n FindDirectoryKind(..),\n \n XferOptions(..),\n XferProgressStatus(..),\n XferOverwriteMode(..),\n XferOverwriteAction(..),\n XferErrorMode(..),\n XferErrorAction(..),\n XferPhase(..),\n XferProgressInfo(..),\n XferProgressCallback,\n XferErrorCallback,\n XferOverwriteCallback,\n XferDuplicateCallback,\n \n Cancellation(..),\n newCancellation,\n withCancellation,\n \n VolumeOpSuccessCallback,\n VolumeOpFailureCallback,\n CVolumeOpCallback,\n VolumeType(..),\n DeviceType(..),\n \n MIMEType,\n \n module System.Gnome.VFS.Hierarchy,\n \n DriveID,\n newDrive,\n withDrive,\n \n VolumeID,\n newVolume,\n withVolume,\n \n wrapVolumeMonitor,\n withVolumeMonitor\n \n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.Reader\nimport Data.ByteString (ByteString)\nimport Data.Typeable\nimport Data.Word (Word64)\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GObject#} (GObject(..),\n GObjectClass,\n toGObject,\n unsafeCastGObject)\n{#import System.Glib.GType#} (GType,\n typeInstanceIsA)\n{#import System.Gnome.VFS.Hierarchy#}\n\nimport System.Posix.Types (DeviceID, EpochTime)\n\n--------------------------------------------------------------------\n\ngTypeCast :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\ngTypeCast gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n--------------------------------------------------------------------\n\n-- | The result of a file operation.\n{# enum GnomeVFSResult as Result {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show, Typeable) #}\n\nnewtype Error = Error Result\n deriving (Show, Typeable)\n\n-- | A handle to an open file\n{# pointer *GnomeVFSHandle as Handle foreign newtype #}\nwithHandle (Handle cHandle) = withForeignPtr cHandle\n\n-- | Specifies the start position for a seek operation.\n{# enum GnomeVFSSeekPosition as SeekPosition {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n{# enum GnomeVFSOpenMode as OpenMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n--------------------------------------------------------------------\n\n-- | A record type containing information about a file.\ndata FileInfo = FileInfo {\n fileInfoName :: Maybe String, -- ^ the name of the file,\n -- without the path\n fileInfoType :: Maybe FileType, -- ^ the type of the file;\n -- i.e. regular, directory,\n -- block-device, etc.\n fileInfoPermissions :: Maybe [FilePermissions], -- ^ the permissions for the\n -- file\n fileInfoFlags :: Maybe [FileFlags], -- ^ flags providing\n -- additional information\n -- about the file\n fileInfoDevice :: Maybe DeviceID, -- ^ the device the file\n -- resides on\n fileInfoInode :: Maybe InodeNumber, -- ^ the inode number of the\n -- file\n fileInfoLinkCount :: Maybe Int, -- ^ the total number of\n -- hard links to the file\n fileInfoIDs :: Maybe IDs, -- ^ the user and group IDs\n -- owning the file\n fileInfoSize :: Maybe FileSize, -- ^ the size of the file in\n -- bytes\n fileInfoBlockCount :: Maybe FileSize, -- ^ the size of the file in\n -- filesystem blocks\n fileInfoIOBlockSize :: Maybe FileSize, -- ^ the optimal buffer size\n -- for reading from and\n -- writing to the file\n fileInfoATime :: Maybe EpochTime, -- ^ the time of last access\n fileInfoMTime :: Maybe EpochTime, -- ^ the time of last modification\n fileInfoCTime :: Maybe EpochTime, -- ^ the time of last attribute modification\n fileInfoSymlinkName :: Maybe String, -- ^ the location this\n -- symlink points to, if\n -- @fileInfoFlags@ contains 'FileFlagsSymlink'\n fileInfoMIMEType :: Maybe MIMEType -- ^ the MIME-type of the\n -- file\n } deriving (Eq, Show)\n\n{# enum GnomeVFSFileInfoFields as FileInfoFields {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Options for reading information from a file.\n{# enum GnomeVFSFileInfoOptions as FileInfoOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying additional information about a file.\n{# enum GnomeVFSFileFlags as FileFlags {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying the attributes of a file that should be changed.\n{# enum GnomeVFSSetFileInfoMask as SetFileInfoMask {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Identifies the type of a file.\n{# enum GnomeVFSFileType as FileType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ninstance Flags FileInfoOptions\ninstance Flags FileInfoFields\ninstance Flags FileFlags\ninstance Flags SetFileInfoMask\n\n-- | An integral type wide enough to hold the size of a file.\ntype FileSize = Word64\n\n-- | An integral type wide enough to hold an offset into a file.\ntype FileOffset = Word64\n\n-- | An integral type wide enough to hold the inode number of a file.\ntype InodeNumber = Word64\n\n-- | A pair holding the user ID and group ID of a file owner.\ntype IDs = (Int, Int)\n\n-- | UNIX-like permissions for a file.\n{# enum GnomeVFSFilePermissions as FilePermissions {\n GNOME_VFS_PERM_SUID as PermSUID,\n GNOME_VFS_PERM_SGID as PermSGID,\n GNOME_VFS_PERM_STICKY as PermSticky,\n GNOME_VFS_PERM_USER_READ as PermUserRead,\n GNOME_VFS_PERM_USER_WRITE as PermUserWrite,\n GNOME_VFS_PERM_USER_EXEC as PermUserExec,\n GNOME_VFS_PERM_USER_ALL as PermUserAll,\n GNOME_VFS_PERM_GROUP_READ as PermGroupRead,\n GNOME_VFS_PERM_GROUP_WRITE as PermGroupWrite,\n GNOME_VFS_PERM_GROUP_EXEC as PermGroupExec,\n GNOME_VFS_PERM_GROUP_ALL as PermGroupAll,\n GNOME_VFS_PERM_OTHER_READ as PermOtherRead,\n GNOME_VFS_PERM_OTHER_WRITE as PermOtherWrite,\n GNOME_VFS_PERM_OTHER_EXEC as PermOtherExec,\n GNOME_VFS_PERM_OTHER_ALL as PermOtherAll,\n GNOME_VFS_PERM_ACCESS_READABLE as PermAccessReadable,\n GNOME_VFS_PERM_ACCESS_WRITABLE as PermAccessWritable,\n GNOME_VFS_PERM_ACCESS_EXECUTABLE as PermAccessExecutable\n } deriving (Eq, Bounded, Show) #}\ninstance Flags FilePermissions\n\n--------------------------------------------------------------------\n\n-- | A 'URI' is a semi-textual representation of a uniform\n-- resource identifier. It contains the information about a resource\n-- location encoded as canononicalized text, but also holds extra\n-- information about the context in which the URI is used.\n{# pointer *GnomeVFSURI as URI foreign newtype #}\n\nnewURI :: Ptr URI\n -> IO URI\nnewURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr cURI cURIFinalizer\nwrapURI :: Ptr URI\n -> IO URI\nwrapURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr_ cURI\nforeign import ccall \"&gnome_vfs_uri_unref\"\n cURIFinalizer :: FunPtr (Ptr URI -> IO ())\n\nwithURI (URI cURI) = withForeignPtr cURI\n\n-- | The toplevel URI element used to access resources stored on a\n-- remote server.\n{# pointer *GnomeVFSToplevelURI as ToplevelURI foreign newtype #}\nwithToplevelURI (ToplevelURI cToplevelURI) = withForeignPtr cToplevelURI\nnewToplevelURI :: Ptr ToplevelURI\n -> IO ToplevelURI\nnewToplevelURI cToplevelURI = liftM ToplevelURI $ newForeignPtr_ cToplevelURI\n\n-- | Flags specifying which fields of a 'URI' should be hidden when\n-- converted to a string using 'uriToString'.\n{# enum GnomeVFSURIHideOptions as URIHideOptions {\n GNOME_VFS_URI_HIDE_NONE as URIHideNone,\n GNOME_VFS_URI_HIDE_USER_NAME as URIHideUserName,\n GNOME_VFS_URI_HIDE_PASSWORD as URIHidePassword,\n GNOME_VFS_URI_HIDE_HOST_NAME as URIHideHostName,\n GNOME_VFS_URI_HIDE_HOST_PORT as URIHideHostPort,\n GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD as URIHideToplevelMethod,\n GNOME_VFS_URI_HIDE_FRAGMENT_IDENTIFIER as URIHideFragmentIdentifier\n } deriving (Eq, Bounded, Show) #}\ninstance Flags URIHideOptions\n\n-- | A string that can be passed to 'uriFromString' to create a valid\n-- 'URI'.\ntype TextURI = String\n\n--------------------------------------------------------------------\n\n-- | A handle to an open directory.\n{# pointer *GnomeVFSDirectoryHandle as DirectoryHandle foreign newtype #}\nwithDirectoryHandle (DirectoryHandle cDirectoryHandle) = withForeignPtr cDirectoryHandle\n\n-- | Options controlling the way in which a directories are visited.\n{# enum GnomeVFSDirectoryVisitOptions as DirectoryVisitOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags DirectoryVisitOptions\n\n-- | A callback that will be called for each entry when passed to\n-- 'directoryVisit', 'directoryVisitURI', 'directoryVisitFiles', or\n-- 'directoryVisitFilesAtURI'.\ntype DirectoryVisitCallback = String -- ^ the path of the visited file, relative to the base directory\n -> FileInfo -- ^ the 'FileInfo' for the visited file\n -> Bool -- ^ 'True' if returning 'DirectoryVisitRecurse' will cause a loop\n -> IO DirectoryVisitResult -- ^ the next action to be taken\n\n-- | An enumerated value that must be returned from a\n-- 'DirectoryVisitCallback'. The 'directoryVisit' and related\n-- functions will perform the action specified.\ndata DirectoryVisitResult = DirectoryVisitStop -- ^ stop visiting files\n | DirectoryVisitContinue -- ^ continue as normal\n | DirectoryVisitRecurse -- ^ recursively visit the current entry\n deriving (Eq, Enum)\n\n-- | Specifies which kind of directory 'findDirectory' should look for.\n{# enum GnomeVFSFindDirectoryKind as FindDirectoryKind {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n-- | Flags that may be passed to 'makeURIFromInputWithDirs'. If the\n-- path passed is non-absolute (i.e., a relative path), the\n-- directories specified will be searched as well.\n{# enum GnomeVFSMakeURIDirs as MakeURIDirs {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags MakeURIDirs\n\n--------------------------------------------------------------------\n\n-- | A handle to a file-system monitor.\nnewtype MonitorHandle = MonitorHandle (ForeignPtr MonitorHandle, {# type GnomeVFSMonitorCallback #})\nwithMonitorHandle (MonitorHandle (monitorHandleForeignPtr, _)) = withForeignPtr monitorHandleForeignPtr\n\n-- | A callback that must be passed to 'monitorAdd'. It will be\n-- called any time a file or directory is changed.\ntype MonitorCallback = MonitorHandle -- ^ the handle to a filesystem monitor\n -> TextURI -- ^ the URI being monitored\n -> TextURI -- ^ the actual file that was modified\n -> MonitorEventType -- ^ the event that occured\n -> IO ()\n\n-- | The type of filesystem object that is to be monitored.\n{# enum GnomeVFSMonitorType as MonitorType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | The type of event that caused a 'MonitorCallback' to be called.\n{# enum GnomeVFSMonitorEventType as MonitorEventType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\nwrapMonitorHandle :: (Ptr MonitorHandle, {# type GnomeVFSMonitorCallback #})\n -> IO MonitorHandle\nwrapMonitorHandle (cMonitorHandle, cMonitorCallback) =\n do monitorHandleForeignPtr <- newForeignPtr_ cMonitorHandle\n return $ MonitorHandle (monitorHandleForeignPtr, cMonitorCallback)\n\n--------------------------------------------------------------------\n\n-- | Options controlling how the 'System.Gnome.VFS.Xfer.xferURI' and related functions behave.\n{# enum GnomeVFSXferOptions as XferOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags XferOptions\n\n{# enum GnomeVFSXferProgressStatus as XferProgressStatus {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteMode as XferOverwriteMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteAction as XferOverwriteAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorMode as XferErrorMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorAction as XferErrorAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferPhase as XferPhase {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ndata XferProgressInfo = XferProgressInfo {\n xferProgressInfoVFSStatus :: Result, -- ^ current VFS status\n xferProgressInfoPhase :: XferPhase, -- ^ phase of the transfer\n xferProgressInfoSourceName :: Maybe String, -- ^ currently transferring source URI\n xferProgressInfoTargetName :: Maybe String, -- ^ currently transferring target URI\n xferProgressInfoFileIndex :: Word, -- ^ index of the file currently being transferred\n xferProgressInfoFilesTotal :: Word, -- ^ total number of files being transferred\n xferProgressInfoBytesTotal :: FileSize, -- ^ total size of all files in bytes\n xferProgressInfoFileSize :: FileSize, -- ^ size of the file currently being transferred\n xferProgressInfoBytesCopied :: FileSize, -- ^ number of bytes already transferred in the current file\n xferProgressInfoTotalBytesCopied :: FileSize, -- ^ total number of bytes already transferred\n xferProgressInfoTopLevelItem :: Bool -- ^ 'True' if the file being transferred is a top-level item;\n -- 'False' if it is inside a directory\n } deriving (Eq)\n\n-- | The type of the first callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI' and related functions. This\n-- callback will be called periodically during transfers that are\n-- progressing normally.\ntype XferProgressCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO Bool -- ^ return 'Prelude.False' to abort the transfer, 'Prelude.True' otherwise.\n\n-- | The type of the second callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- whenever an error occurs.\ntype XferErrorCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferErrorAction -- ^ the action to be performed in response to the error\n\n-- | The type of the third callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a file would be overwritten.\ntype XferOverwriteCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferOverwriteAction -- ^ the action to be performed when the target file already exists\n\n-- | The type of the fourth callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a duplicate filename is found.\ntype XferDuplicateCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> String -- ^ @duplicateName@ - the name of the target file\n -> Int -- ^ @duplicateCount@ - the number of duplicates that exist\n -> IO (Maybe String) -- ^ the new filename that should be used, or 'Prelude.Nothing' to abort.\n\n--------------------------------------------------------------------\n\n-- | An object that can be used for signalling cancellation of an\n-- operation.\n{# pointer *GnomeVFSCancellation as Cancellation foreign newtype #}\n\nnewCancellation :: Ptr Cancellation\n -> IO Cancellation\nnewCancellation cCancellationPtr | cCancellationPtr \/= nullPtr =\n liftM Cancellation $ newForeignPtr cCancellationPtr cancellationFinalizer\nforeign import ccall unsafe \"&gnome_vfs_cancellation_destroy\"\n cancellationFinalizer :: FunPtr (Ptr Cancellation -> IO ())\nwithCancellation (Cancellation cCancellation) = withForeignPtr cCancellation\n\n--------------------------------------------------------------------\n\nwithVolume (Volume cVolume) = withForeignPtr cVolume\nnewVolume :: Ptr Volume\n -> IO Volume\nnewVolume cVolume | cVolume \/= nullPtr =\n liftM Volume $ newForeignPtr cVolume volumeFinalizer\nforeign import ccall unsafe \"&gnome_vfs_volume_unref\"\n volumeFinalizer :: FunPtr (Ptr Volume -> IO ())\n\n-- | An action to be performed when a volume operation completes successfully.\ntype VolumeOpSuccessCallback = IO ()\n-- | An action to be performed when a volume operation fails.\ntype VolumeOpFailureCallback = String\n -> String\n -> IO ()\n\n-- | Identifies the device type of a 'Volume' or 'Drive'.\n{#enum GnomeVFSDeviceType as DeviceType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n-- | Identifies the type of a 'Volume'.\n{#enum GnomeVFSVolumeType as VolumeType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ntype CVolumeOpCallback = {# type gboolean #}\n -> CString\n -> CString\n -> Ptr ()\n -> IO ()\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Drive'\ntype DriveID = {# type gulong #}\n\nwithDrive (Drive cDrive) = withForeignPtr cDrive\nnewDrive :: Ptr Drive\n -> IO Drive\nnewDrive cDrive | cDrive \/= nullPtr =\n liftM Drive $ newForeignPtr cDrive driveFinalizer\nforeign import ccall unsafe \"&gnome_vfs_drive_unref\"\n driveFinalizer :: FunPtr (Ptr Drive -> IO ())\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Volume'.\ntype VolumeID = {# type gulong #}\n\nwithVolumeMonitor (VolumeMonitor cVolumeMonitor) = withForeignPtr cVolumeMonitor\nwrapVolumeMonitor :: Ptr VolumeMonitor\n -> IO VolumeMonitor\nwrapVolumeMonitor cVolumeMonitor | cVolumeMonitor \/= nullPtr =\n liftM VolumeMonitor $ newForeignPtr_ cVolumeMonitor\n\n--------------------------------------------------------------------\n\n-- | A string that will be treated as a MIME-type.\ntype MIMEType = String\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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Types (\n \n Handle(..),\n withHandle,\n \n Result(..),\n Error(..),\n \n OpenMode(..),\n SeekPosition(..),\n \n FileInfo(..),\n FileFlags(..),\n FileInfoFields(..),\n SetFileInfoMask(..),\n FileInfoOptions(..),\n FilePermissions(..),\n FileSize,\n FileOffset,\n FileType(..),\n InodeNumber,\n IDs,\n \n MonitorHandle(..),\n withMonitorHandle,\n MonitorCallback,\n MonitorType,\n MonitorEventType,\n \n URI(..),\n TextURI,\n newURI,\n withURI,\n ToplevelURI(..),\n newToplevelURI,\n withToplevelURI,\n URIHideOptions(..),\n \n DirectoryHandle(..),\n withDirectoryHandle,\n \n MakeURIDirs(..),\n DirectoryVisitOptions(..),\n DirectoryVisitCallback,\n DirectoryVisitResult(..),\n FindDirectoryKind(..),\n \n XferOptions(..),\n XferProgressStatus(..),\n XferOverwriteMode(..),\n XferOverwriteAction(..),\n XferErrorMode(..),\n XferErrorAction(..),\n XferPhase(..),\n XferProgressInfo(..),\n XferProgressCallback,\n XferErrorCallback,\n XferOverwriteCallback,\n XferDuplicateCallback,\n \n Cancellation(..),\n newCancellation,\n withCancellation,\n \n VolumeOpSuccessCallback,\n VolumeOpFailureCallback,\n CVolumeOpCallback,\n VolumeType(..),\n DeviceType(..),\n \n MIMEType,\n \n module System.Gnome.VFS.Hierarchy,\n \n DriveID,\n newDrive,\n withDrive,\n \n VolumeID,\n newVolume,\n withVolume,\n \n wrapVolumeMonitor,\n withVolumeMonitor\n \n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.Reader\nimport Data.ByteString (ByteString)\nimport Data.Typeable\nimport Data.Word (Word64)\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GObject#} (GObject(..),\n GObjectClass,\n toGObject,\n unsafeCastGObject)\n{#import System.Glib.GType#} (GType,\n typeInstanceIsA)\n{#import System.Gnome.VFS.Hierarchy#}\n\nimport System.Posix.Types (DeviceID, EpochTime)\n\n--------------------------------------------------------------------\n\ngTypeCast :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\ngTypeCast gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n--------------------------------------------------------------------\n\n-- | The result of a file operation.\n{# enum GnomeVFSResult as Result {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show, Typeable) #}\n\nnewtype Error = Error Result\n deriving (Show, Typeable)\n\n-- | A handle to an open file\n{# pointer *GnomeVFSHandle as Handle foreign newtype #}\nwithHandle (Handle cHandle) = withForeignPtr cHandle\n\n-- | Specifies the start position for a seek operation.\n{# enum GnomeVFSSeekPosition as SeekPosition {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n{# enum GnomeVFSOpenMode as OpenMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n--------------------------------------------------------------------\n\n-- | A record type containing information about a file.\ndata FileInfo = FileInfo {\n fileInfoName :: Maybe String, -- ^ the name of the file,\n -- without the path\n fileInfoType :: Maybe FileType, -- ^ the type of the file;\n -- i.e. regular, directory,\n -- block-device, etc.\n fileInfoPermissions :: Maybe [FilePermissions], -- ^ the permissions for the\n -- file\n fileInfoFlags :: Maybe [FileFlags], -- ^ flags providing\n -- additional information\n -- about the file\n fileInfoDevice :: Maybe DeviceID, -- ^ the device the file\n -- resides on\n fileInfoInode :: Maybe InodeNumber, -- ^ the inode number of the\n -- file\n fileInfoLinkCount :: Maybe Int, -- ^ the total number of\n -- hard links to the file\n fileInfoIDs :: Maybe IDs, -- ^ the user and group IDs\n -- owning the file\n fileInfoSize :: Maybe FileSize, -- ^ the size of the file in\n -- bytes\n fileInfoBlockCount :: Maybe FileSize, -- ^ the size of the file in\n -- filesystem blocks\n fileInfoIOBlockSize :: Maybe FileSize, -- ^ the optimal buffer size\n -- for reading from and\n -- writing to the file\n fileInfoATime :: Maybe EpochTime, -- ^ the time of last access\n fileInfoMTime :: Maybe EpochTime, -- ^ the time of last modification\n fileInfoCTime :: Maybe EpochTime, -- ^ the time of last attribute modification\n fileInfoSymlinkName :: Maybe String, -- ^ the location this\n -- symlink points to, if\n -- @fileInfoFlags@ contains 'FileFlagsSymlink'\n fileInfoMIMEType :: Maybe MIMEType -- ^ the MIME-type of the\n -- file\n } deriving (Eq, Show)\n\n{# enum GnomeVFSFileInfoFields as FileInfoFields {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Options for reading information from a file.\n{# enum GnomeVFSFileInfoOptions as FileInfoOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying additional information about a file.\n{# enum GnomeVFSFileFlags as FileFlags {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying the attributes of a file that should be changed.\n{# enum GnomeVFSSetFileInfoMask as SetFileInfoMask {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Identifies the type of a file.\n{# enum GnomeVFSFileType as FileType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ninstance Flags FileInfoOptions\ninstance Flags FileInfoFields\ninstance Flags FileFlags\ninstance Flags SetFileInfoMask\n\n-- | An integral type wide enough to hold the size of a file.\ntype FileSize = Word64\n\n-- | An integral type wide enough to hold an offset into a file.\ntype FileOffset = Word64\n\n-- | An integral type wide enough to hold the inode number of a file.\ntype InodeNumber = Word64\n\n-- | A pair holding the user ID and group ID of a file owner.\ntype IDs = (Int, Int)\n\n-- | UNIX-like permissions for a file.\ndata FilePermissions = PermSUID -- ^ the set-user-ID bit\n | PermSGID -- ^ the set-group-ID bit\n | PermSticky -- ^ the \\\"sticky\\\" bit\n | PermUserRead -- ^ owner read permission\n | PermUserWrite -- ^ owner write permission\n | PermUserExec -- ^ owner execute permission\n | PermUserAll -- ^ equivalent to\n -- @['PermUserRead', 'PermUserWrite', 'PermUserExec']@\n | PermGroupRead -- ^ group read permission\n | PermGroupWrite -- ^ group write permission\n | PermGroupExec -- ^ group execute permission\n | PermGroupAll -- ^ equivalent to\n -- @['PermGroupRead', 'PermGroupWrite', 'PermGroupExec']@\n | PermOtherRead -- ^ world read permission\n | PermOtherWrite -- ^ world write permission\n | PermOtherExec -- ^ world execute permission\n | PermOtherAll -- ^ equivalent to\n -- @['PermOtherRead', 'PermOtherWrite', 'PermOtherExec']@\n | PermAccessReadable -- ^ readable by the current process\n | PermAccessWritable -- ^ writable by the current process\n | PermAccessExecutable -- ^ executable by the current process\n deriving (Eq, Bounded, Show)\ninstance Flags FilePermissions\ninstance Enum FilePermissions where\n fromEnum PermSUID = 2048\n fromEnum PermSGID = 1024\n fromEnum PermSticky = 512\n fromEnum PermUserRead = 256\n fromEnum PermUserWrite = 128\n fromEnum PermUserExec = 64\n fromEnum PermUserAll = 448\n fromEnum PermGroupRead = 32\n fromEnum PermGroupWrite = 16\n fromEnum PermGroupExec = 8\n fromEnum PermGroupAll = 56\n fromEnum PermOtherRead = 4\n fromEnum PermOtherWrite = 2\n fromEnum PermOtherExec = 1\n fromEnum PermOtherAll = 7\n fromEnum PermAccessReadable = 65536\n fromEnum PermAccessWritable = 131072\n fromEnum PermAccessExecutable = 262144\n \n toEnum 2048 = PermSUID\n toEnum 1024 = PermSGID\n toEnum 512 = PermSticky\n toEnum 256 = PermUserRead\n toEnum 128 = PermUserWrite\n toEnum 64 = PermUserExec\n toEnum 448 = PermUserAll\n toEnum 32 = PermGroupRead\n toEnum 16 = PermGroupWrite\n toEnum 8 = PermGroupExec\n toEnum 56 = PermGroupAll\n toEnum 4 = PermOtherRead\n toEnum 2 = PermOtherWrite\n toEnum 1 = PermOtherExec\n toEnum 7 = PermOtherAll\n toEnum 65536 = PermAccessReadable\n toEnum 131072 = PermAccessWritable\n toEnum 262144 = PermAccessExecutable\n \n toEnum unmatched = error (\"FilePermissions.toEnum: Cannot match \" ++ show unmatched)\n\n--------------------------------------------------------------------\n\n-- | A 'URI' is a semi-textual representation of a uniform\n-- resource identifier. It contains the information about a resource\n-- location encoded as canononicalized text, but also holds extra\n-- information about the context in which the URI is used.\n{# pointer *GnomeVFSURI as URI foreign newtype #}\n\nnewURI :: Ptr URI\n -> IO URI\nnewURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr cURI cURIFinalizer\nwrapURI :: Ptr URI\n -> IO URI\nwrapURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr_ cURI\nforeign import ccall \"&gnome_vfs_uri_unref\"\n cURIFinalizer :: FunPtr (Ptr URI -> IO ())\n\nwithURI (URI cURI) = withForeignPtr cURI\n\n-- | The toplevel URI element used to access resources stored on a\n-- remote server.\n{# pointer *GnomeVFSToplevelURI as ToplevelURI foreign newtype #}\nwithToplevelURI (ToplevelURI cToplevelURI) = withForeignPtr cToplevelURI\nnewToplevelURI :: Ptr ToplevelURI\n -> IO ToplevelURI\nnewToplevelURI cToplevelURI = liftM ToplevelURI $ newForeignPtr_ cToplevelURI\n\n-- | Flags specifying which fields of a 'URI' should be hidden when\n-- converted to a string using 'uriToString'.\n{# enum GnomeVFSURIHideOptions as URIHideOptions {\n GNOME_VFS_URI_HIDE_NONE as URIHideNone,\n GNOME_VFS_URI_HIDE_USER_NAME as URIHideUserName,\n GNOME_VFS_URI_HIDE_PASSWORD as URIHidePassword,\n GNOME_VFS_URI_HIDE_HOST_NAME as URIHideHostName,\n GNOME_VFS_URI_HIDE_HOST_PORT as URIHideHostPort,\n GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD as URIHideToplevelMethod,\n GNOME_VFS_URI_HIDE_FRAGMENT_IDENTIFIER as URIHideFragmentIdentifier\n } deriving (Eq, Bounded, Show) #}\ninstance Flags URIHideOptions\n\n-- | A string that can be passed to 'uriFromString' to create a valid\n-- 'URI'.\ntype TextURI = String\n\n--------------------------------------------------------------------\n\n-- | A handle to an open directory.\n{# pointer *GnomeVFSDirectoryHandle as DirectoryHandle foreign newtype #}\nwithDirectoryHandle (DirectoryHandle cDirectoryHandle) = withForeignPtr cDirectoryHandle\n\n-- | Options controlling the way in which a directories are visited.\n{# enum GnomeVFSDirectoryVisitOptions as DirectoryVisitOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags DirectoryVisitOptions\n\n-- | A callback that will be called for each entry when passed to\n-- 'directoryVisit', 'directoryVisitURI', 'directoryVisitFiles', or\n-- 'directoryVisitFilesAtURI'.\ntype DirectoryVisitCallback = String -- ^ the path of the visited file, relative to the base directory\n -> FileInfo -- ^ the 'FileInfo' for the visited file\n -> Bool -- ^ 'True' if returning 'DirectoryVisitRecurse' will cause a loop\n -> IO DirectoryVisitResult -- ^ the next action to be taken\n\n-- | An enumerated value that must be returned from a\n-- 'DirectoryVisitCallback'. The 'directoryVisit' and related\n-- functions will perform the action specified.\ndata DirectoryVisitResult = DirectoryVisitStop -- ^ stop visiting files\n | DirectoryVisitContinue -- ^ continue as normal\n | DirectoryVisitRecurse -- ^ recursively visit the current entry\n deriving (Eq, Enum)\n\n-- | Specifies which kind of directory 'findDirectory' should look for.\n{# enum GnomeVFSFindDirectoryKind as FindDirectoryKind {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n-- | Flags that may be passed to 'makeURIFromInputWithDirs'. If the\n-- path passed is non-absolute (i.e., a relative path), the\n-- directories specified will be searched as well.\n{# enum GnomeVFSMakeURIDirs as MakeURIDirs {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags MakeURIDirs\n\n--------------------------------------------------------------------\n\n-- | A handle to a file-system monitor.\nnewtype MonitorHandle = MonitorHandle (ForeignPtr MonitorHandle, {# type GnomeVFSMonitorCallback #})\nwithMonitorHandle (MonitorHandle (monitorHandleForeignPtr, _)) = withForeignPtr monitorHandleForeignPtr\n\n-- | A callback that must be passed to 'monitorAdd'. It will be\n-- called any time a file or directory is changed.\ntype MonitorCallback = MonitorHandle -- ^ the handle to a filesystem monitor\n -> TextURI -- ^ the URI being monitored\n -> TextURI -- ^ the actual file that was modified\n -> MonitorEventType -- ^ the event that occured\n -> IO ()\n\n-- | The type of filesystem object that is to be monitored.\n{# enum GnomeVFSMonitorType as MonitorType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | The type of event that caused a 'MonitorCallback' to be called.\n{# enum GnomeVFSMonitorEventType as MonitorEventType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\nwrapMonitorHandle :: (Ptr MonitorHandle, {# type GnomeVFSMonitorCallback #})\n -> IO MonitorHandle\nwrapMonitorHandle (cMonitorHandle, cMonitorCallback) =\n do monitorHandleForeignPtr <- newForeignPtr_ cMonitorHandle\n return $ MonitorHandle (monitorHandleForeignPtr, cMonitorCallback)\n\n--------------------------------------------------------------------\n\n-- | Options controlling how the 'System.Gnome.VFS.Xfer.xferURI' and related functions behave.\n{# enum GnomeVFSXferOptions as XferOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags XferOptions\n\n{# enum GnomeVFSXferProgressStatus as XferProgressStatus {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteMode as XferOverwriteMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteAction as XferOverwriteAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorMode as XferErrorMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorAction as XferErrorAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferPhase as XferPhase {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ndata XferProgressInfo = XferProgressInfo {\n xferProgressInfoVFSStatus :: Result, -- ^ current VFS status\n xferProgressInfoPhase :: XferPhase, -- ^ phase of the transfer\n xferProgressInfoSourceName :: Maybe String, -- ^ currently transferring source URI\n xferProgressInfoTargetName :: Maybe String, -- ^ currently transferring target URI\n xferProgressInfoFileIndex :: Word, -- ^ index of the file currently being transferred\n xferProgressInfoFilesTotal :: Word, -- ^ total number of files being transferred\n xferProgressInfoBytesTotal :: FileSize, -- ^ total size of all files in bytes\n xferProgressInfoFileSize :: FileSize, -- ^ size of the file currently being transferred\n xferProgressInfoBytesCopied :: FileSize, -- ^ number of bytes already transferred in the current file\n xferProgressInfoTotalBytesCopied :: FileSize, -- ^ total number of bytes already transferred\n xferProgressInfoTopLevelItem :: Bool -- ^ 'True' if the file being transferred is a top-level item;\n -- 'False' if it is inside a directory\n } deriving (Eq)\n\n-- | The type of the first callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI' and related functions. This\n-- callback will be called periodically during transfers that are\n-- progressing normally.\ntype XferProgressCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO Bool -- ^ return 'Prelude.False' to abort the transfer, 'Prelude.True' otherwise.\n\n-- | The type of the second callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- whenever an error occurs.\ntype XferErrorCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferErrorAction -- ^ the action to be performed in response to the error\n\n-- | The type of the third callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a file would be overwritten.\ntype XferOverwriteCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferOverwriteAction -- ^ the action to be performed when the target file already exists\n\n-- | The type of the fourth callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a duplicate filename is found.\ntype XferDuplicateCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> String -- ^ @duplicateName@ - the name of the target file\n -> Int -- ^ @duplicateCount@ - the number of duplicates that exist\n -> IO (Maybe String) -- ^ the new filename that should be used, or 'Prelude.Nothing' to abort.\n\n--------------------------------------------------------------------\n\n-- | An object that can be used for signalling cancellation of an\n-- operation.\n{# pointer *GnomeVFSCancellation as Cancellation foreign newtype #}\n\nnewCancellation :: Ptr Cancellation\n -> IO Cancellation\nnewCancellation cCancellationPtr | cCancellationPtr \/= nullPtr =\n liftM Cancellation $ newForeignPtr cCancellationPtr cancellationFinalizer\nforeign import ccall unsafe \"&gnome_vfs_cancellation_destroy\"\n cancellationFinalizer :: FunPtr (Ptr Cancellation -> IO ())\nwithCancellation (Cancellation cCancellation) = withForeignPtr cCancellation\n\n--------------------------------------------------------------------\n\nwithVolume (Volume cVolume) = withForeignPtr cVolume\nnewVolume :: Ptr Volume\n -> IO Volume\nnewVolume cVolume | cVolume \/= nullPtr =\n liftM Volume $ newForeignPtr cVolume volumeFinalizer\nforeign import ccall unsafe \"&gnome_vfs_volume_unref\"\n volumeFinalizer :: FunPtr (Ptr Volume -> IO ())\n\n-- | An action to be performed when a volume operation completes successfully.\ntype VolumeOpSuccessCallback = IO ()\n-- | An action to be performed when a volume operation fails.\ntype VolumeOpFailureCallback = String\n -> String\n -> IO ()\n\n-- | Identifies the device type of a 'Volume' or 'Drive'.\n{#enum GnomeVFSDeviceType as DeviceType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n-- | Identifies the type of a 'Volume'.\n{#enum GnomeVFSVolumeType as VolumeType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ntype CVolumeOpCallback = {# type gboolean #}\n -> CString\n -> CString\n -> Ptr ()\n -> IO ()\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Drive'\ntype DriveID = {# type gulong #}\n\nwithDrive (Drive cDrive) = withForeignPtr cDrive\nnewDrive :: Ptr Drive\n -> IO Drive\nnewDrive cDrive | cDrive \/= nullPtr =\n liftM Drive $ newForeignPtr cDrive driveFinalizer\nforeign import ccall unsafe \"&gnome_vfs_drive_unref\"\n driveFinalizer :: FunPtr (Ptr Drive -> IO ())\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Volume'.\ntype VolumeID = {# type gulong #}\n\nwithVolumeMonitor (VolumeMonitor cVolumeMonitor) = withForeignPtr cVolumeMonitor\nwrapVolumeMonitor :: Ptr VolumeMonitor\n -> IO VolumeMonitor\nwrapVolumeMonitor cVolumeMonitor | cVolumeMonitor \/= nullPtr =\n liftM VolumeMonitor $ newForeignPtr_ cVolumeMonitor\n\n--------------------------------------------------------------------\n\n-- | A string that will be treated as a MIME-type.\ntype MIMEType = String\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"faf37002297abe6afae7a6e37d25b086ea93f435","subject":"fixed problem with c2hs not finding chi file","message":"fixed problem with c2hs not finding chi file\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/Warper.chs","new_file":"src\/GDAL\/Internal\/Warper.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.Warper (\n ResampleAlg (..)\n , WarpOptions (..)\n , GDALWarpException (..)\n , reprojectImage\n , setTransformer\n , autoCreateWarpedVRT\n , createWarpedVRT\n , def\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (when, void)\nimport Control.Monad.IO.Class (liftIO)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..), bracket)\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable)\nimport Data.Default (Default(..))\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr, castPtr, castFunPtr, nullFunPtr)\nimport Foreign.Marshal.Alloc (alloca, malloc, free)\nimport Foreign.Marshal.Array (mallocArray)\nimport Foreign.Storable (Storable(..))\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.Algorithms\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.CPLString #}\n{#import GDAL.Internal.CPLProgress #}\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.GDAL #}\n\n#include \"gdal.h\"\n#include \"gdalwarper.h\"\n\ndata GDALWarpException\n = WarpStopped\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALWarpException where\n rnf a = a `seq` ()\n\ninstance Exception GDALWarpException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n{# enum GDALResampleAlg as ResampleAlg {upcaseFirstLetter}\n deriving (Eq,Read,Show) #}\n\n\ndata WarpOptions s a b\n = forall t. (Transformer t, Show (t s a b), GDALType a, GDALType b)\n => WarpOptions {\n woResampleAlg :: ResampleAlg\n , woWarpOptions :: OptionList\n , woMemoryLimit :: Double\n , woWorkingDatatype :: Datatype\n , woBands :: [(Int,Int)]\n , woTransfomer :: Maybe (t s a b)\n , woSrcNodata :: Maybe a\n , woDstNodata :: Maybe b\n , woProgressFun :: Maybe ProgressFun\n }\n\nderiving instance Show (WarpOptions s a b)\n\ninstance (GDALType a, GDALType b) => Default (WarpOptions s a b) where\n def = WarpOptions {\n woResampleAlg = GRA_NearestNeighbour\n , woWarpOptions = []\n , woMemoryLimit = 0\n , woWorkingDatatype = GDT_Unknown\n , woBands = []\n , woTransfomer = Just (def :: GenImgProjTransformer s a b)\n , woSrcNodata = Nothing\n , woDstNodata = Nothing\n , woProgressFun = Nothing\n }\n\n-- Avoids \"Record update for insufficiently polymorphic field\" when doigs\n-- opts { woTransfomer = Just ...}\nsetTransformer\n :: forall t s a b. (Transformer t, Show (t s a b), GDALType a, GDALType b)\n => WarpOptions s a b -> t s a b -> WarpOptions s a b\nsetTransformer opts t = WarpOptions {\n woResampleAlg = woResampleAlg opts\n , woWarpOptions = woWarpOptions opts\n , woMemoryLimit = woMemoryLimit opts\n , woWorkingDatatype = woWorkingDatatype opts\n , woBands = woBands opts\n , woTransfomer = Just t\n , woSrcNodata = woSrcNodata opts\n , woDstNodata = woDstNodata opts\n , woProgressFun = woProgressFun opts\n }\n\nwithWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => Ptr (RODataset s a) -> Maybe (WarpOptions s a b)\n -> (Ptr (WarpOptions s a b) -> IO c) -> IO c\nwithWarpOptionsPtr _ Nothing f = f nullPtr\nwithWarpOptionsPtr dsPtr (Just wo) f = do\n ret <- withProgressFun (woProgressFun wo) $ \\pFun -> do\n (p, finalizer) <- mkWarpOptionsPtr dsPtr wo\n {#set GDALWarpOptions.pfnProgress #} p pFun\n bracket (return p) (const finalizer) f\n maybe (throwBindingException WarpStopped) return ret\n\nmkWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => Ptr (RODataset s a) -> WarpOptions s a b\n -> IO (Ptr (WarpOptions s a b), IO ())\nmkWarpOptionsPtr dsPtr WarpOptions{..} = do\n p <- createWarpOptions\n return (p, destroyWarpOptions p)\n where\n createWarpOptions = do\n p <- c_createWarpOptions\n {#set GDALWarpOptions.eResampleAlg #} p (fromEnumC woResampleAlg)\n oListPtr <- toOptionListPtr woWarpOptions\n {#set GDALWarpOptions.papszWarpOptions #} p oListPtr\n {#set GDALWarpOptions.dfWarpMemoryLimit #} p (realToFrac woMemoryLimit)\n {#set GDALWarpOptions.eWorkingDataType #} p (fromEnumC woWorkingDatatype)\n {#set GDALWarpOptions.nBandCount #} p (fromIntegral (length woBands))\n {#set GDALWarpOptions.panSrcBands #} p =<< intListToPtr (map fst woBands)\n {#set GDALWarpOptions.panDstBands #} p =<< intListToPtr (map snd woBands)\n case woTransfomer of\n Just t -> do\n {#set GDALWarpOptions.pfnTransformer #} p\n (castFunPtr (transformerFunc t))\n tArg <- fmap castPtr (createTransformer dsPtr t)\n {#set GDALWarpOptions.pTransformerArg #} p tArg\n Nothing -> do\n {#set GDALWarpOptions.pfnTransformer #} p nullFunPtr\n {#set GDALWarpOptions.pTransformerArg #} p nullPtr\n case woDstNodata of\n Just v -> do\n vPtr <- malloc\n poke vPtr (toNodata v)\n {#set GDALWarpOptions.padfDstNoDataReal #} p vPtr\n {#set GDALWarpOptions.padfDstNoDataImag #} p vPtr\n Nothing -> return ()\n case woSrcNodata of\n Just v -> do\n vPtr <- malloc\n poke vPtr (toNodata v)\n {#set GDALWarpOptions.padfSrcNoDataReal #} p vPtr\n {#set GDALWarpOptions.padfSrcNoDataImag #} p vPtr\n Nothing -> return ()\n return p\n\n destroyWarpOptions p = do\n case woTransfomer of\n Just (_ :: t s a b) -> do\n t <- {#get GDALWarpOptions.pTransformerArg #} p\n destroyTransformer (castPtr t :: Ptr (t s a b))\n Nothing -> return ()\n when (isJust woSrcNodata) $\n ({#get GDALWarpOptions.padfSrcNoDataReal #} p >>= free)\n when (isJust woDstNodata) $\n ({#get GDALWarpOptions.padfDstNoDataReal #} p >>= free)\n c_destroyWarpOptions p\n\n intListToPtr [] = return nullPtr\n intListToPtr l = do\n ptr <- mallocArray (length l)\n mapM_ (\\(i,v) -> pokeElemOff ptr i (fromIntegral v)) (zip [0..] l)\n return ptr\n\nforeign import ccall unsafe \"gdalwarper.h GDALCreateWarpOptions\"\n c_createWarpOptions :: IO (Ptr (WarpOptions s a b))\n\nforeign import ccall unsafe \"gdalwarper.h GDALDestroyWarpOptions\"\n c_destroyWarpOptions :: Ptr (WarpOptions s a b) -> IO ()\n\n\nreprojectImage\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> RWDataset s b\n -> Maybe (WarpOptions s a b)\n -> GDAL s ()\nreprojectImage srcDs dstDs opts =\n liftIO $ void $ throwIfError \"reprojectImage\" $\n withLockedDatasetPtr srcDs $ \\srcPtr ->\n withLockedDatasetPtr dstDs $ \\dstPtr ->\n withWarpOptionsPtr srcPtr opts $\n c_reprojectImage srcPtr nullPtr dstPtr nullPtr 0 0 0 nullFunPtr nullPtr\n\nforeign import ccall safe \"gdalwarper.h GDALReprojectImage\" c_reprojectImage\n :: Ptr (Dataset s t a) -- ^Source dataset\n -> CString -- ^Source proj (WKT)\n -> Ptr (RWDataset s b) -- ^Dest dataset\n -> CString -- ^Dest proj (WKT)\n -> CInt -- ^Resample alg\n -> CDouble -- ^Memory limit\n -> CDouble -- ^Max error\n -> ProgressFunPtr -- ^Progress func\n -> Ptr () -- ^Progress arg (unused)\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO CInt\n\nautoCreateWarpedVRT\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> Maybe SpatialReference\n -> WarpOptions s a b\n -> GDAL s (RODataset s b)\nautoCreateWarpedVRT ds dstSrs options = do\n (opts, finalizeOpts) <- liftIO (mkWarpOptionsPtr dsPtr options)\n registerFinalizer finalizeOpts\n newDsPtr <- liftIO $ withMaybeSRAsCString dstSrs $ \\srs ->\n c_autoCreateWarpedVRT dsPtr nullPtr srs 0 0 opts\n newDerivedDatasetHandle ds newDsPtr\n where dsPtr = unDataset ds\n\n\n\nforeign import ccall safe \"gdalwarper.h GDALAutoCreateWarpedVRT\" c_autoCreateWarpedVRT\n :: Ptr (RODataset s a) -- ^Source dataset\n -> CString -- ^Source proj (WKT)\n -> CString -- ^Dest proj (WKT)\n -> CInt -- ^Resample alg\n -> CDouble -- ^Max error\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO (Ptr (RODataset s b))\n\ncreateWarpedVRT\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> Int\n -> Int\n -> Geotransform\n -> WarpOptions s a b\n -> GDAL s (RODataset s b)\ncreateWarpedVRT srcDs nPixels nLines geotransform options = do\n let dsPtr = unDataset srcDs\n nBands = datasetBandCount srcDs\n options'\n | null (woBands options)\n = options { woBands = map (\\i -> (i,i)) [1..nBands]}\n | otherwise\n = options\n (opts,finalizeOpts) <- liftIO (mkWarpOptionsPtr dsPtr options')\n registerFinalizer finalizeOpts\n newDsPtr <- liftIO $ alloca $ \\gt -> do\n poke (castPtr gt) geotransform\n {#set GDALWarpOptions.hSrcDS #} opts (castPtr dsPtr)\n pArg <- {#get GDALWarpOptions.pTransformerArg #} opts\n when (pArg \/= nullPtr) $\n {#call GDALSetGenImgProjTransformerDstGeoTransform as ^#} pArg gt\n c_createWarpedVRT dsPtr (fromIntegral nPixels) (fromIntegral nLines) gt opts\n newDerivedDatasetHandle srcDs newDsPtr\n\nforeign import ccall safe \"gdalwarper.h GDALCreateWarpedVRT\" c_createWarpedVRT\n :: Ptr (RODataset s a) -- ^Source dataset\n -> CInt -- ^nPixels\n -> CInt -- ^nLines\n -> Ptr CDouble -- ^geotransform\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO (Ptr (RODataset s b))\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.Warper (\n ResampleAlg (..)\n , WarpOptions (..)\n , GDALWarpException (..)\n , reprojectImage\n , setTransformer\n , autoCreateWarpedVRT\n , createWarpedVRT\n , def\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (when, void)\nimport Control.Monad.IO.Class (liftIO)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..), bracket)\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable)\nimport Data.Default (Default(..))\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr, castPtr, castFunPtr, nullFunPtr)\nimport Foreign.Marshal.Alloc (alloca, malloc, free)\nimport Foreign.Marshal.Array (mallocArray)\nimport Foreign.Storable (Storable(..))\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (fromEnumC)\n{#import GDAL.Internal.Algorithms #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.CPLString #}\n{#import GDAL.Internal.CPLProgress #}\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.GDAL #}\n\n#include \"gdal.h\"\n#include \"gdalwarper.h\"\n\ndata GDALWarpException\n = WarpStopped\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALWarpException where\n rnf a = a `seq` ()\n\ninstance Exception GDALWarpException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n{# enum GDALResampleAlg as ResampleAlg {upcaseFirstLetter}\n deriving (Eq,Read,Show) #}\n\n\ndata WarpOptions s a b\n = forall t. (Transformer t, Show (t s a b), GDALType a, GDALType b)\n => WarpOptions {\n woResampleAlg :: ResampleAlg\n , woWarpOptions :: OptionList\n , woMemoryLimit :: Double\n , woWorkingDatatype :: Datatype\n , woBands :: [(Int,Int)]\n , woTransfomer :: Maybe (t s a b)\n , woSrcNodata :: Maybe a\n , woDstNodata :: Maybe b\n , woProgressFun :: Maybe ProgressFun\n }\n\nderiving instance Show (WarpOptions s a b)\n\ninstance (GDALType a, GDALType b) => Default (WarpOptions s a b) where\n def = WarpOptions {\n woResampleAlg = GRA_NearestNeighbour\n , woWarpOptions = []\n , woMemoryLimit = 0\n , woWorkingDatatype = GDT_Unknown\n , woBands = []\n , woTransfomer = Just (def :: GenImgProjTransformer s a b)\n , woSrcNodata = Nothing\n , woDstNodata = Nothing\n , woProgressFun = Nothing\n }\n\n-- Avoids \"Record update for insufficiently polymorphic field\" when doigs\n-- opts { woTransfomer = Just ...}\nsetTransformer\n :: forall t s a b. (Transformer t, Show (t s a b), GDALType a, GDALType b)\n => WarpOptions s a b -> t s a b -> WarpOptions s a b\nsetTransformer opts t = WarpOptions {\n woResampleAlg = woResampleAlg opts\n , woWarpOptions = woWarpOptions opts\n , woMemoryLimit = woMemoryLimit opts\n , woWorkingDatatype = woWorkingDatatype opts\n , woBands = woBands opts\n , woTransfomer = Just t\n , woSrcNodata = woSrcNodata opts\n , woDstNodata = woDstNodata opts\n , woProgressFun = woProgressFun opts\n }\n\nwithWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => Ptr (RODataset s a) -> Maybe (WarpOptions s a b)\n -> (Ptr (WarpOptions s a b) -> IO c) -> IO c\nwithWarpOptionsPtr _ Nothing f = f nullPtr\nwithWarpOptionsPtr dsPtr (Just wo) f = do\n ret <- withProgressFun (woProgressFun wo) $ \\pFun -> do\n (p, finalizer) <- mkWarpOptionsPtr dsPtr wo\n {#set GDALWarpOptions.pfnProgress #} p pFun\n bracket (return p) (const finalizer) f\n maybe (throwBindingException WarpStopped) return ret\n\nmkWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => Ptr (RODataset s a) -> WarpOptions s a b\n -> IO (Ptr (WarpOptions s a b), IO ())\nmkWarpOptionsPtr dsPtr WarpOptions{..} = do\n p <- createWarpOptions\n return (p, destroyWarpOptions p)\n where\n createWarpOptions = do\n p <- c_createWarpOptions\n {#set GDALWarpOptions.eResampleAlg #} p (fromEnumC woResampleAlg)\n oListPtr <- toOptionListPtr woWarpOptions\n {#set GDALWarpOptions.papszWarpOptions #} p oListPtr\n {#set GDALWarpOptions.dfWarpMemoryLimit #} p (realToFrac woMemoryLimit)\n {#set GDALWarpOptions.eWorkingDataType #} p (fromEnumC woWorkingDatatype)\n {#set GDALWarpOptions.nBandCount #} p (fromIntegral (length woBands))\n {#set GDALWarpOptions.panSrcBands #} p =<< intListToPtr (map fst woBands)\n {#set GDALWarpOptions.panDstBands #} p =<< intListToPtr (map snd woBands)\n case woTransfomer of\n Just t -> do\n {#set GDALWarpOptions.pfnTransformer #} p\n (castFunPtr (transformerFunc t))\n tArg <- fmap castPtr (createTransformer dsPtr t)\n {#set GDALWarpOptions.pTransformerArg #} p tArg\n Nothing -> do\n {#set GDALWarpOptions.pfnTransformer #} p nullFunPtr\n {#set GDALWarpOptions.pTransformerArg #} p nullPtr\n case woDstNodata of\n Just v -> do\n vPtr <- malloc\n poke vPtr (toNodata v)\n {#set GDALWarpOptions.padfDstNoDataReal #} p vPtr\n {#set GDALWarpOptions.padfDstNoDataImag #} p vPtr\n Nothing -> return ()\n case woSrcNodata of\n Just v -> do\n vPtr <- malloc\n poke vPtr (toNodata v)\n {#set GDALWarpOptions.padfSrcNoDataReal #} p vPtr\n {#set GDALWarpOptions.padfSrcNoDataImag #} p vPtr\n Nothing -> return ()\n return p\n\n destroyWarpOptions p = do\n case woTransfomer of\n Just (_ :: t s a b) -> do\n t <- {#get GDALWarpOptions.pTransformerArg #} p\n destroyTransformer (castPtr t :: Ptr (t s a b))\n Nothing -> return ()\n when (isJust woSrcNodata) $\n ({#get GDALWarpOptions.padfSrcNoDataReal #} p >>= free)\n when (isJust woDstNodata) $\n ({#get GDALWarpOptions.padfDstNoDataReal #} p >>= free)\n c_destroyWarpOptions p\n\n intListToPtr [] = return nullPtr\n intListToPtr l = do\n ptr <- mallocArray (length l)\n mapM_ (\\(i,v) -> pokeElemOff ptr i (fromIntegral v)) (zip [0..] l)\n return ptr\n\nforeign import ccall unsafe \"gdalwarper.h GDALCreateWarpOptions\"\n c_createWarpOptions :: IO (Ptr (WarpOptions s a b))\n\nforeign import ccall unsafe \"gdalwarper.h GDALDestroyWarpOptions\"\n c_destroyWarpOptions :: Ptr (WarpOptions s a b) -> IO ()\n\n\nreprojectImage\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> RWDataset s b\n -> Maybe (WarpOptions s a b)\n -> GDAL s ()\nreprojectImage srcDs dstDs opts =\n liftIO $ void $ throwIfError \"reprojectImage\" $\n withLockedDatasetPtr srcDs $ \\srcPtr ->\n withLockedDatasetPtr dstDs $ \\dstPtr ->\n withWarpOptionsPtr srcPtr opts $\n c_reprojectImage srcPtr nullPtr dstPtr nullPtr 0 0 0 nullFunPtr nullPtr\n\nforeign import ccall safe \"gdalwarper.h GDALReprojectImage\" c_reprojectImage\n :: Ptr (Dataset s t a) -- ^Source dataset\n -> CString -- ^Source proj (WKT)\n -> Ptr (RWDataset s b) -- ^Dest dataset\n -> CString -- ^Dest proj (WKT)\n -> CInt -- ^Resample alg\n -> CDouble -- ^Memory limit\n -> CDouble -- ^Max error\n -> ProgressFunPtr -- ^Progress func\n -> Ptr () -- ^Progress arg (unused)\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO CInt\n\nautoCreateWarpedVRT\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> Maybe SpatialReference\n -> WarpOptions s a b\n -> GDAL s (RODataset s b)\nautoCreateWarpedVRT ds dstSrs options = do\n (opts, finalizeOpts) <- liftIO (mkWarpOptionsPtr dsPtr options)\n registerFinalizer finalizeOpts\n newDsPtr <- liftIO $ withMaybeSRAsCString dstSrs $ \\srs ->\n c_autoCreateWarpedVRT dsPtr nullPtr srs 0 0 opts\n newDerivedDatasetHandle ds newDsPtr\n where dsPtr = unDataset ds\n\n\n\nforeign import ccall safe \"gdalwarper.h GDALAutoCreateWarpedVRT\" c_autoCreateWarpedVRT\n :: Ptr (RODataset s a) -- ^Source dataset\n -> CString -- ^Source proj (WKT)\n -> CString -- ^Dest proj (WKT)\n -> CInt -- ^Resample alg\n -> CDouble -- ^Max error\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO (Ptr (RODataset s b))\n\ncreateWarpedVRT\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> Int\n -> Int\n -> Geotransform\n -> WarpOptions s a b\n -> GDAL s (RODataset s b)\ncreateWarpedVRT srcDs nPixels nLines geotransform options = do\n let dsPtr = unDataset srcDs\n nBands = datasetBandCount srcDs\n options'\n | null (woBands options)\n = options { woBands = map (\\i -> (i,i)) [1..nBands]}\n | otherwise\n = options\n (opts,finalizeOpts) <- liftIO (mkWarpOptionsPtr dsPtr options')\n registerFinalizer finalizeOpts\n newDsPtr <- liftIO $ alloca $ \\gt -> do\n poke (castPtr gt) geotransform\n {#set GDALWarpOptions.hSrcDS #} opts (castPtr dsPtr)\n pArg <- {#get GDALWarpOptions.pTransformerArg #} opts\n when (pArg \/= nullPtr) $\n {#call GDALSetGenImgProjTransformerDstGeoTransform as ^#} pArg gt\n c_createWarpedVRT dsPtr (fromIntegral nPixels) (fromIntegral nLines) gt opts\n newDerivedDatasetHandle srcDs newDsPtr\n\nforeign import ccall safe \"gdalwarper.h GDALCreateWarpedVRT\" c_createWarpedVRT\n :: Ptr (RODataset s a) -- ^Source dataset\n -> CInt -- ^nPixels\n -> CInt -- ^nLines\n -> Ptr CDouble -- ^geotransform\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO (Ptr (RODataset s b))\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0be1a0730babc8b9cf1a8e4222f474b815192406","subject":"Fix GtkSourceView.chs Enums haddock docs.","message":"Fix GtkSourceView.chs Enums haddock docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceView.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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-- 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.SourceView (\n-- * Types\n SourceView,\n SourceViewClass,\n\n-- * Enums\n SourceSmartHomeEndType(..),\n SourceDrawSpacesFlags(..),\n\n-- * Methods \n castToSourceView,\n sourceViewNew,\n sourceViewNewWithBuffer,\n sourceViewSetAutoIndent,\n sourceViewGetAutoIndent,\n sourceViewSetIndentOnTab,\n sourceViewGetIndentOnTab,\n sourceViewSetIndentWidth,\n sourceViewGetIndentWidth,\n sourceViewSetInsertSpacesInsteadOfTabs,\n sourceViewGetInsertSpacesInsteadOfTabs,\n sourceViewSetSmartHomeEnd,\n sourceViewGetSmartHomeEnd,\n sourceViewSetMarkCategoryPriority,\n sourceViewGetMarkCategoryPriority,\n sourceViewSetMarkCategoryIconFromPixbuf,\n sourceViewSetMarkCategoryIconFromStock,\n sourceViewSetMarkCategoryIconFromIconName,\n sourceViewSetMarkCategoryBackground,\n sourceViewGetMarkCategoryBackground,\n sourceViewSetHighlightCurrentLine,\n sourceViewGetHighlightCurrentLine,\n sourceViewSetShowLineMarks,\n sourceViewGetShowLineMarks,\n sourceViewSetShowLineNumbers,\n sourceViewGetShowLineNumbers,\n sourceViewSetShowRightMargin,\n sourceViewGetShowRightMargin,\n sourceViewSetRightMarginPosition,\n sourceViewGetRightMarginPosition,\n sourceViewSetTabWidth,\n sourceViewGetTabWidth,\n sourceViewSetDrawSpaces,\n sourceViewGetDrawSpaces,\n\n-- * Attributes \n sourceViewAutoIndent,\n sourceViewDrawSpaces,\n sourceViewHighlightCurrentLine,\n sourceViewIndentOnTab,\n sourceViewIndentWidth,\n sourceViewInsertSpacesInsteadOfTabs,\n sourceViewRightMarginPosition,\n sourceViewShowLineNumbers,\n sourceViewShowRightMargin,\n sourceViewSmartHomeEnd,\n sourceViewTabWidth,\n\n-- * Signals\n sourceViewUndo,\n sourceViewRedo,\n sourceViewMoveLines,\n sourceViewShowCompletion,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n sourceViewSetMarkCategoryPixbuf,\n sourceViewGetMarkCategoryPixbuf,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Abstract.Widget (Color)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSmartHomeEndType {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n{# enum SourceDrawSpacesFlags {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n-- | Create a new 'SourceView' widget with a default 'SourceBuffer'.\n--\nsourceViewNew :: IO SourceView\nsourceViewNew = makeNewObject mkSourceView $ liftM castPtr\n {#call unsafe source_view_new#}\n\n-- | Create a new 'SourceView'\n-- widget with the given 'SourceBuffer'.\n--\nsourceViewNewWithBuffer :: SourceBuffer -> IO SourceView\nsourceViewNewWithBuffer sb = makeNewObject mkSourceView $ liftM castPtr $\n {#call source_view_new_with_buffer#} sb\n\n-- | If 'True' auto indentation of text is enabled.\n--\nsourceViewSetAutoIndent :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to enable auto indentation. \n -> IO ()\nsourceViewSetAutoIndent sv enable =\n {#call source_view_set_auto_indent#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether auto indentation of text is enabled.\n--\nsourceViewGetAutoIndent :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if auto indentation is enabled. \nsourceViewGetAutoIndent sv = liftM toBool $\n {#call unsafe source_view_get_auto_indent#} (toSourceView sv)\n\n-- | If 'True', when the tab key is pressed and there is a selection, the selected text is indented of one\n-- level instead of being replaced with the \\t characters. Shift+Tab unindents the selection.\n--\nsourceViewSetIndentOnTab :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to indent a block when tab is pressed. \n -> IO ()\nsourceViewSetIndentOnTab sv enable =\n {#call source_view_set_indent_on_tab#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether when the tab key is pressed the current selection should get indented instead of\n-- replaced with the \\t character.\n--\nsourceViewGetIndentOnTab :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the selection is indented when tab is pressed. \nsourceViewGetIndentOnTab sv = liftM toBool $\n {#call unsafe source_view_get_indent_on_tab#} (toSourceView sv)\n\n-- | Sets the number of spaces to use for each step of indent. If width is -1, the value of the\n-- 'tabWidth' property will be used.\n--\nsourceViewSetIndentWidth :: SourceViewClass sv => sv \n -> Int -- ^ @width@ indent width in characters. \n -> IO ()\nsourceViewSetIndentWidth sv width =\n {#call source_view_set_indent_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the number of spaces to use for each step of indent. See 'sourceViewSetIndentWidth'\n-- for details.\n--\nsourceViewGetIndentWidth :: SourceViewClass sv => sv \n -> IO Int -- ^ returns indent width. \nsourceViewGetIndentWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_indent_width#} (toSourceView sv)\n\n-- | If 'True' any tabulator character inserted is replaced by a group of space characters.\n--\nsourceViewSetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to insert spaces instead of tabs. \n -> IO ()\nsourceViewSetInsertSpacesInsteadOfTabs sv enable =\n {#call source_view_set_insert_spaces_instead_of_tabs#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether when inserting a tabulator character it should be replaced by a group of space\n-- characters.\n--\nsourceViewGetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if spaces are inserted instead of tabs. \nsourceViewGetInsertSpacesInsteadOfTabs sv = liftM toBool $\n {#call unsafe source_view_get_insert_spaces_instead_of_tabs#} (toSourceView sv)\n\n-- | Set the desired movement of the cursor when HOME and END keys are pressed.\n--\nsourceViewSetSmartHomeEnd :: SourceViewClass sv => sv \n -> SourceSmartHomeEndType -- ^ @smartHe@ the desired behavior among 'SourceSmartHomeEndType'. \n -> IO ()\nsourceViewSetSmartHomeEnd sv newVal =\n {#call source_view_set_smart_home_end#} (toSourceView sv) (fromIntegral $ fromEnum newVal)\n \n-- | Returns a 'SourceSmartHomeEndType' end value specifying how the cursor will move when HOME and END\n-- keys are pressed.\n--\nsourceViewGetSmartHomeEnd :: SourceViewClass sv => sv \n -> IO SourceSmartHomeEndType -- ^ returns a 'SourceSmartHomeEndTypeend' value. \nsourceViewGetSmartHomeEnd sv = liftM (toEnum . fromIntegral) $\n {#call unsafe source_view_get_smart_home_end#} (toSourceView sv)\n\n-- | If show is 'True' the current line is highlighted.\n--\nsourceViewSetHighlightCurrentLine :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether to highlight the current line \n -> IO ()\nsourceViewSetHighlightCurrentLine sv newVal =\n {#call source_view_set_highlight_current_line#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether the current line is highlighted\n--\nsourceViewGetHighlightCurrentLine :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the current line is highlighted. \nsourceViewGetHighlightCurrentLine sv = liftM toBool $\n {#call unsafe source_view_get_highlight_current_line#} (toSourceView sv)\n\n-- | If 'True' line marks will be displayed beside the text.\n--\nsourceViewSetShowLineMarks :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether line marks should be displayed. \n -> IO ()\nsourceViewSetShowLineMarks sv newVal =\n {#call source_view_set_show_line_marks#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether line marks are displayed beside the text.\n--\nsourceViewGetShowLineMarks :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the line marks are displayed. \nsourceViewGetShowLineMarks sv = liftM toBool $\n {#call unsafe source_view_get_show_line_marks#} (toSourceView sv)\n\n-- | If 'True' line numbers will be displayed beside the text.\n--\nsourceViewSetShowLineNumbers :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether line numbers should be displayed. \n -> IO ()\nsourceViewSetShowLineNumbers sv newVal =\n {#call source_view_set_show_line_numbers#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether line numbers are displayed beside the text.\n--\nsourceViewGetShowLineNumbers :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the line numbers are displayed. \nsourceViewGetShowLineNumbers sv = liftM toBool $\n {#call unsafe source_view_get_show_line_numbers#} (toSourceView sv)\n\n-- | If 'True' a right margin is displayed\n--\nsourceViewSetShowRightMargin :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether to show a right margin. \n -> IO ()\nsourceViewSetShowRightMargin sv newVal =\n {#call source_view_set_show_right_margin#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether a right margin is displayed.\n--\nsourceViewGetShowRightMargin :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the right margin is shown. \nsourceViewGetShowRightMargin sv = liftM toBool $\n {#call source_view_get_show_right_margin#} (toSourceView sv)\n \n-- | Sets the position of the right margin in the given view.\n--\nsourceViewSetRightMarginPosition :: SourceViewClass sv => sv \n -> Word -- ^ @pos@ the width in characters where to position the right margin. \n -> IO ()\nsourceViewSetRightMarginPosition sv margin =\n {#call source_view_set_right_margin_position#} (toSourceView sv) (fromIntegral margin)\n \n-- | Gets the position of the right margin in the given view.\n--\nsourceViewGetRightMarginPosition :: SourceViewClass sv => sv \n -> IO Int -- ^ returns the position of the right margin. \nsourceViewGetRightMarginPosition sv = liftM fromIntegral $\n {#call unsafe source_view_get_right_margin_position#} (toSourceView sv)\n\n-- | Sets the width of tabulation in characters.\n--\nsourceViewSetTabWidth :: SourceViewClass sv => sv \n -> Int -- ^ @width@ width of tab in characters. \n -> IO ()\nsourceViewSetTabWidth sv width =\n {#call source_view_set_tab_width#} (toSourceView sv) (fromIntegral width)\n \n-- | Returns the width of tabulation in characters.\n--\nsourceViewGetTabWidth :: SourceViewClass sv => sv \n -> IO Int -- ^ returns width of tab. \nsourceViewGetTabWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_tab_width#} (toSourceView sv)\n\n-- | Set if and how the spaces should be visualized. Specifying flags as 0 will disable display of\n-- spaces.\nsourceViewSetDrawSpaces :: SourceViewClass sv => sv\n -> SourceDrawSpacesFlags -- ^ @flags@ 'SourceDrawSpacesFlags' specifing how white spaces should be displayed\n -> IO ()\nsourceViewSetDrawSpaces view flags =\n {#call gtk_source_view_set_draw_spaces #} \n (toSourceView view)\n (fromIntegral $ fromEnum flags)\n\n-- | Returns the 'SourceDrawSpacesFlags' specifying if and how spaces should be displayed for this view.\nsourceViewGetDrawSpaces :: SourceViewClass sv => sv\n -> IO SourceDrawSpacesFlags -- ^ returns the 'SourceDrawSpacesFlags', 0 if no spaces should be drawn. \nsourceViewGetDrawSpaces view = \n liftM (toEnum . fromIntegral) $\n {#call gtk_source_view_get_draw_spaces #}\n (toSourceView view)\n\n-- | Set the priority for the given mark category. When there are multiple marks on the same line, marks\n-- of categories with higher priorities will be drawn on top.\n--\nsourceViewSetMarkCategoryPriority :: SourceViewClass sv => sv \n -> String -- ^ @category@ a mark category. \n -> Int -- ^ @priority@ the priority for the category \n -> IO ()\nsourceViewSetMarkCategoryPriority sv markerType priority = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_priority#} (toSourceView sv) strPtr (fromIntegral priority)\n\n-- | Gets the priority which is associated with the given category.\n--\nsourceViewGetMarkCategoryPriority :: SourceViewClass sv => sv \n -> String -- ^ @category@ a mark category. \n -> IO Int -- ^ returns the priority or if category exists but no priority was set, it defaults to 0.\nsourceViewGetMarkCategoryPriority sv markerType = withCString markerType $ \\strPtr ->\n liftM fromIntegral $\n {#call unsafe source_view_get_mark_category_priority#} (toSourceView sv) strPtr\n\n-- | Sets the icon to be used for category to pixbuf. If pixbuf is 'Nothing', the icon is unset.\nsourceViewSetMarkCategoryIconFromPixbuf :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe Pixbuf -- ^ @pixbuf@ a 'Pixbuf' or 'Nothing'. \n -> IO ()\nsourceViewSetMarkCategoryIconFromPixbuf sv category pixbuf =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_pixbuf #}\n (toSourceView sv)\n categoryPtr\n (fromMaybe (Pixbuf nullForeignPtr) pixbuf)\n\n-- | Sets the icon to be used for category to the stock item @stockId@. If @stockId@ is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromStock :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe String -- ^ @stockId@ the stock id or 'Nothing'. \n -> IO ()\nsourceViewSetMarkCategoryIconFromStock sv category stockId =\n withCString category $ \\categoryPtr ->\n maybeWith withCString stockId $ \\stockIdPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_stock #}\n (toSourceView sv)\n categoryPtr\n stockIdPtr\n\n-- | Sets the icon to be used for category to the named theme item name. If name is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromIconName :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe String -- ^ @name@ the themed icon name or 'Nothing'. \n -> IO ()\nsourceViewSetMarkCategoryIconFromIconName sv category name =\n withCString category $ \\categoryPtr ->\n maybeWith withCString name $ \\namePtr ->\n {#call gtk_source_view_set_mark_category_icon_from_icon_name #}\n (toSourceView sv)\n categoryPtr\n namePtr\n\n-- | Sets given background color for mark category. If color is 'Nothing', the background color is unset.\nsourceViewSetMarkCategoryBackground :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe Color -- ^ @color@ background color or 'Nothing' to unset it. \n -> IO ()\nsourceViewSetMarkCategoryBackground sv category color =\n let withMB :: Storable a => Maybe a -> (Ptr a -> IO b) -> IO b\n withMB Nothing f = f nullPtr\n withMB (Just x) f = with x f\n in withCString category $ \\categoryPtr ->\n withMB color $ \\colorPtr ->\n {#call gtk_source_view_set_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n\n-- | Gets the background color associated with given category.\nsourceViewGetMarkCategoryBackground :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category.\n -> Color -- ^ @dest@ destination 'Color' structure to fill in.\n -> IO Bool -- ^ returns 'True' if background color for category was set and dest is set to a valid color, or 'False' otherwise.\nsourceViewGetMarkCategoryBackground sv category color = \n liftM toBool $\n withCString category $ \\ categoryPtr ->\n with color $ \\ colorPtr ->\n {#call gtk_source_view_get_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n\n-- | Whether to enable auto indentation.\n-- \n-- Default value: 'False'\n--\nsourceViewAutoIndent :: SourceViewClass sv => Attr sv Bool\nsourceViewAutoIndent = newAttrFromBoolProperty \"auto-indent\"\n\n-- | Set if and how the spaces should be visualized.\n--\nsourceViewDrawSpaces :: SourceViewClass sv => Attr sv SourceDrawSpacesFlags\nsourceViewDrawSpaces = newAttrFromEnumProperty \"draw-spaces\" {#call fun gtk_source_draw_spaces_flags_get_type#}\n\n-- | Whether to highlight the current line.\n-- \n-- Default value: 'False'\n--\nsourceViewHighlightCurrentLine :: SourceViewClass sv => Attr sv Bool\nsourceViewHighlightCurrentLine = newAttrFromBoolProperty \"highlight-current-line\"\n\n-- | Whether to indent the selected text when the tab key is pressed.\n-- \n-- Default value: 'True'\n--\nsourceViewIndentOnTab :: SourceViewClass sv => Attr sv Bool\nsourceViewIndentOnTab = newAttrFromBoolProperty \"indent-on-tab\"\n\n-- | Width of an indentation step expressed in number of spaces.\n-- \n-- Allowed values: [GMaxulong,32]\n-- \n-- Default value: -1\n--\nsourceViewIndentWidth :: SourceViewClass sv => Attr sv Int\nsourceViewIndentWidth = newAttrFromIntProperty \"indent-width\"\n\n-- | Whether to insert spaces instead of tabs.\n-- \n-- Default value: 'False'\n--\nsourceViewInsertSpacesInsteadOfTabs :: SourceViewClass sv => Attr sv Bool\nsourceViewInsertSpacesInsteadOfTabs = newAttrFromBoolProperty \"insert-spaces-instead-of-tabs\"\n\n-- | Position of the right margin.\n-- \n-- Allowed values: [1,200]\n-- \n-- Default value: 80\n--\nsourceViewRightMarginPosition :: SourceViewClass sv => Attr sv Int\nsourceViewRightMarginPosition = newAttrFromUIntProperty \"right-margin-position\"\n\n-- | Whether to display line numbers\n-- \n-- Default value: 'False'\n--\nsourceViewShowLineNumbers :: SourceViewClass sv => Attr sv Bool\nsourceViewShowLineNumbers = newAttrFromBoolProperty \"show-line-numbers\"\n\n-- | Whether to display line mark pixbufs\n-- \n-- Default value: 'False'\n--\nsourceViewShowRightMargin :: SourceViewClass sv => Attr sv Bool\nsourceViewShowRightMargin = newAttrFromBoolProperty \"show-right-margin\"\n\n-- | Set the behavior of the HOME and END keys.\n-- \n-- Default value: 'SourceSmartHomeEndDisabled'\n-- \n-- Since 2.0\n--\nsourceViewSmartHomeEnd :: SourceViewClass sv => Attr sv SourceSmartHomeEndType\nsourceViewSmartHomeEnd = newAttrFromEnumProperty \"smart-home-end\" {#call fun gtk_source_smart_home_end_type_get_type#}\n\n-- | Width of an tab character expressed in number of spaces.\n-- \n-- Allowed values: [1,32]\n-- \n-- Default value: 8\n--\nsourceViewTabWidth :: SourceViewClass sv => Attr sv Int\nsourceViewTabWidth = newAttrFromUIntProperty \"tab-width\"\n\n-- |\n--\nsourceViewUndo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewUndo = Signal $ connect_NONE__NONE \"undo\"\n\n-- |\n--\nsourceViewRedo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewRedo = Signal $ connect_NONE__NONE \"redo\"\n\n-- | The 'moveLines' signal is a keybinding which gets emitted when the user initiates moving a\n-- line. The default binding key is Alt+Up\/Down arrow. And moves the currently selected lines, or the\n-- current line by count. For the moment, only count of -1 or 1 is valid.\nsourceViewMoveLines :: SourceViewClass sv => Signal sv (Bool -> Int -> IO ())\nsourceViewMoveLines = Signal $ connect_BOOL_INT__NONE \"move-lines\"\n\n-- | The 'showCompletion' signal is a keybinding signal which gets emitted when the user initiates a\n-- completion in default mode.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the default mode completion activation.\nsourceViewShowCompletion :: SourceViewClass sv => Signal sv (IO ())\nsourceViewShowCompletion = Signal $ connect_NONE__NONE \"show-completion\"\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | 'sourceViewSetMarkCategoryPixbuf' is deprecated and should not be used in newly-written\n-- code. Use 'sourceViewSetMarkCategoryIconFromPixbuf' instead\n--\nsourceViewSetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> Pixbuf -> IO ()\nsourceViewSetMarkCategoryPixbuf sv markerType marker = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_pixbuf#} (toSourceView sv) strPtr marker\n\n-- | 'sourceViewGetMarkCategoryPixbuf' is deprecated and should not be used in newly-written code.\n--\nsourceViewGetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> IO Pixbuf\nsourceViewGetMarkCategoryPixbuf sv markerType = withCString markerType $ \\strPtr ->\n constructNewGObject mkPixbuf $\n {#call unsafe source_view_get_mark_category_pixbuf#} (toSourceView sv) strPtr\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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-- 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.SourceView (\n-- * Types\n SourceView,\n SourceViewClass,\n SourceSmartHomeEndType(..),\n SourceDrawSpacesFlags(..),\n\n-- * Methods \n castToSourceView,\n sourceViewNew,\n sourceViewNewWithBuffer,\n sourceViewSetAutoIndent,\n sourceViewGetAutoIndent,\n sourceViewSetIndentOnTab,\n sourceViewGetIndentOnTab,\n sourceViewSetIndentWidth,\n sourceViewGetIndentWidth,\n sourceViewSetInsertSpacesInsteadOfTabs,\n sourceViewGetInsertSpacesInsteadOfTabs,\n sourceViewSetSmartHomeEnd,\n sourceViewGetSmartHomeEnd,\n sourceViewSetMarkCategoryPriority,\n sourceViewGetMarkCategoryPriority,\n sourceViewSetMarkCategoryIconFromPixbuf,\n sourceViewSetMarkCategoryIconFromStock,\n sourceViewSetMarkCategoryIconFromIconName,\n sourceViewSetMarkCategoryBackground,\n sourceViewGetMarkCategoryBackground,\n sourceViewSetHighlightCurrentLine,\n sourceViewGetHighlightCurrentLine,\n sourceViewSetShowLineMarks,\n sourceViewGetShowLineMarks,\n sourceViewSetShowLineNumbers,\n sourceViewGetShowLineNumbers,\n sourceViewSetShowRightMargin,\n sourceViewGetShowRightMargin,\n sourceViewSetRightMarginPosition,\n sourceViewGetRightMarginPosition,\n sourceViewSetTabWidth,\n sourceViewGetTabWidth,\n sourceViewSetDrawSpaces,\n sourceViewGetDrawSpaces,\n\n-- * Attributes \n sourceViewAutoIndent,\n sourceViewDrawSpaces,\n sourceViewHighlightCurrentLine,\n sourceViewIndentOnTab,\n sourceViewIndentWidth,\n sourceViewInsertSpacesInsteadOfTabs,\n sourceViewRightMarginPosition,\n sourceViewShowLineNumbers,\n sourceViewShowRightMargin,\n sourceViewSmartHomeEnd,\n sourceViewTabWidth,\n\n-- * Signals\n sourceViewUndo,\n sourceViewRedo,\n sourceViewMoveLines,\n sourceViewShowCompletion,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n sourceViewSetMarkCategoryPixbuf,\n sourceViewGetMarkCategoryPixbuf,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Abstract.Widget (Color)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSmartHomeEndType {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n{# enum SourceDrawSpacesFlags {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n-- | Create a new 'SourceView' widget with a default 'SourceBuffer'.\n--\nsourceViewNew :: IO SourceView\nsourceViewNew = makeNewObject mkSourceView $ liftM castPtr\n {#call unsafe source_view_new#}\n\n-- | Create a new 'SourceView'\n-- widget with the given 'SourceBuffer'.\n--\nsourceViewNewWithBuffer :: SourceBuffer -> IO SourceView\nsourceViewNewWithBuffer sb = makeNewObject mkSourceView $ liftM castPtr $\n {#call source_view_new_with_buffer#} sb\n\n-- | If 'True' auto indentation of text is enabled.\n--\nsourceViewSetAutoIndent :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to enable auto indentation. \n -> IO ()\nsourceViewSetAutoIndent sv enable =\n {#call source_view_set_auto_indent#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether auto indentation of text is enabled.\n--\nsourceViewGetAutoIndent :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if auto indentation is enabled. \nsourceViewGetAutoIndent sv = liftM toBool $\n {#call unsafe source_view_get_auto_indent#} (toSourceView sv)\n\n-- | If 'True', when the tab key is pressed and there is a selection, the selected text is indented of one\n-- level instead of being replaced with the \\t characters. Shift+Tab unindents the selection.\n--\nsourceViewSetIndentOnTab :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to indent a block when tab is pressed. \n -> IO ()\nsourceViewSetIndentOnTab sv enable =\n {#call source_view_set_indent_on_tab#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether when the tab key is pressed the current selection should get indented instead of\n-- replaced with the \\t character.\n--\nsourceViewGetIndentOnTab :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the selection is indented when tab is pressed. \nsourceViewGetIndentOnTab sv = liftM toBool $\n {#call unsafe source_view_get_indent_on_tab#} (toSourceView sv)\n\n-- | Sets the number of spaces to use for each step of indent. If width is -1, the value of the\n-- 'tabWidth' property will be used.\n--\nsourceViewSetIndentWidth :: SourceViewClass sv => sv \n -> Int -- ^ @width@ indent width in characters. \n -> IO ()\nsourceViewSetIndentWidth sv width =\n {#call source_view_set_indent_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the number of spaces to use for each step of indent. See 'sourceViewSetIndentWidth'\n-- for details.\n--\nsourceViewGetIndentWidth :: SourceViewClass sv => sv \n -> IO Int -- ^ returns indent width. \nsourceViewGetIndentWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_indent_width#} (toSourceView sv)\n\n-- | If 'True' any tabulator character inserted is replaced by a group of space characters.\n--\nsourceViewSetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to insert spaces instead of tabs. \n -> IO ()\nsourceViewSetInsertSpacesInsteadOfTabs sv enable =\n {#call source_view_set_insert_spaces_instead_of_tabs#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether when inserting a tabulator character it should be replaced by a group of space\n-- characters.\n--\nsourceViewGetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if spaces are inserted instead of tabs. \nsourceViewGetInsertSpacesInsteadOfTabs sv = liftM toBool $\n {#call unsafe source_view_get_insert_spaces_instead_of_tabs#} (toSourceView sv)\n\n-- | Set the desired movement of the cursor when HOME and END keys are pressed.\n--\nsourceViewSetSmartHomeEnd :: SourceViewClass sv => sv \n -> SourceSmartHomeEndType -- ^ @smartHe@ the desired behavior among 'SourceSmartHomeEndType'. \n -> IO ()\nsourceViewSetSmartHomeEnd sv newVal =\n {#call source_view_set_smart_home_end#} (toSourceView sv) (fromIntegral $ fromEnum newVal)\n \n-- | Returns a 'SourceSmartHomeEndType' end value specifying how the cursor will move when HOME and END\n-- keys are pressed.\n--\nsourceViewGetSmartHomeEnd :: SourceViewClass sv => sv \n -> IO SourceSmartHomeEndType -- ^ returns a 'SourceSmartHomeEndTypeend' value. \nsourceViewGetSmartHomeEnd sv = liftM (toEnum . fromIntegral) $\n {#call unsafe source_view_get_smart_home_end#} (toSourceView sv)\n\n-- | If show is 'True' the current line is highlighted.\n--\nsourceViewSetHighlightCurrentLine :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether to highlight the current line \n -> IO ()\nsourceViewSetHighlightCurrentLine sv newVal =\n {#call source_view_set_highlight_current_line#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether the current line is highlighted\n--\nsourceViewGetHighlightCurrentLine :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the current line is highlighted. \nsourceViewGetHighlightCurrentLine sv = liftM toBool $\n {#call unsafe source_view_get_highlight_current_line#} (toSourceView sv)\n\n-- | If 'True' line marks will be displayed beside the text.\n--\nsourceViewSetShowLineMarks :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether line marks should be displayed. \n -> IO ()\nsourceViewSetShowLineMarks sv newVal =\n {#call source_view_set_show_line_marks#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether line marks are displayed beside the text.\n--\nsourceViewGetShowLineMarks :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the line marks are displayed. \nsourceViewGetShowLineMarks sv = liftM toBool $\n {#call unsafe source_view_get_show_line_marks#} (toSourceView sv)\n\n-- | If 'True' line numbers will be displayed beside the text.\n--\nsourceViewSetShowLineNumbers :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether line numbers should be displayed. \n -> IO ()\nsourceViewSetShowLineNumbers sv newVal =\n {#call source_view_set_show_line_numbers#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether line numbers are displayed beside the text.\n--\nsourceViewGetShowLineNumbers :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the line numbers are displayed. \nsourceViewGetShowLineNumbers sv = liftM toBool $\n {#call unsafe source_view_get_show_line_numbers#} (toSourceView sv)\n\n-- | If 'True' a right margin is displayed\n--\nsourceViewSetShowRightMargin :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether to show a right margin. \n -> IO ()\nsourceViewSetShowRightMargin sv newVal =\n {#call source_view_set_show_right_margin#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether a right margin is displayed.\n--\nsourceViewGetShowRightMargin :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the right margin is shown. \nsourceViewGetShowRightMargin sv = liftM toBool $\n {#call source_view_get_show_right_margin#} (toSourceView sv)\n \n-- | Sets the position of the right margin in the given view.\n--\nsourceViewSetRightMarginPosition :: SourceViewClass sv => sv \n -> Word -- ^ @pos@ the width in characters where to position the right margin. \n -> IO ()\nsourceViewSetRightMarginPosition sv margin =\n {#call source_view_set_right_margin_position#} (toSourceView sv) (fromIntegral margin)\n \n-- | Gets the position of the right margin in the given view.\n--\nsourceViewGetRightMarginPosition :: SourceViewClass sv => sv \n -> IO Int -- ^ returns the position of the right margin. \nsourceViewGetRightMarginPosition sv = liftM fromIntegral $\n {#call unsafe source_view_get_right_margin_position#} (toSourceView sv)\n\n-- | Sets the width of tabulation in characters.\n--\nsourceViewSetTabWidth :: SourceViewClass sv => sv \n -> Int -- ^ @width@ width of tab in characters. \n -> IO ()\nsourceViewSetTabWidth sv width =\n {#call source_view_set_tab_width#} (toSourceView sv) (fromIntegral width)\n \n-- | Returns the width of tabulation in characters.\n--\nsourceViewGetTabWidth :: SourceViewClass sv => sv \n -> IO Int -- ^ returns width of tab. \nsourceViewGetTabWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_tab_width#} (toSourceView sv)\n\n-- | Set if and how the spaces should be visualized. Specifying flags as 0 will disable display of\n-- spaces.\nsourceViewSetDrawSpaces :: SourceViewClass sv => sv\n -> SourceDrawSpacesFlags -- ^ @flags@ 'SourceDrawSpacesFlags' specifing how white spaces should be displayed\n -> IO ()\nsourceViewSetDrawSpaces view flags =\n {#call gtk_source_view_set_draw_spaces #} \n (toSourceView view)\n (fromIntegral $ fromEnum flags)\n\n-- | Returns the 'SourceDrawSpacesFlags' specifying if and how spaces should be displayed for this view.\nsourceViewGetDrawSpaces :: SourceViewClass sv => sv\n -> IO SourceDrawSpacesFlags -- ^ returns the 'SourceDrawSpacesFlags', 0 if no spaces should be drawn. \nsourceViewGetDrawSpaces view = \n liftM (toEnum . fromIntegral) $\n {#call gtk_source_view_get_draw_spaces #}\n (toSourceView view)\n\n-- | Set the priority for the given mark category. When there are multiple marks on the same line, marks\n-- of categories with higher priorities will be drawn on top.\n--\nsourceViewSetMarkCategoryPriority :: SourceViewClass sv => sv \n -> String -- ^ @category@ a mark category. \n -> Int -- ^ @priority@ the priority for the category \n -> IO ()\nsourceViewSetMarkCategoryPriority sv markerType priority = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_priority#} (toSourceView sv) strPtr (fromIntegral priority)\n\n-- | Gets the priority which is associated with the given category.\n--\nsourceViewGetMarkCategoryPriority :: SourceViewClass sv => sv \n -> String -- ^ @category@ a mark category. \n -> IO Int -- ^ returns the priority or if category exists but no priority was set, it defaults to 0.\nsourceViewGetMarkCategoryPriority sv markerType = withCString markerType $ \\strPtr ->\n liftM fromIntegral $\n {#call unsafe source_view_get_mark_category_priority#} (toSourceView sv) strPtr\n\n-- | Sets the icon to be used for category to pixbuf. If pixbuf is 'Nothing', the icon is unset.\nsourceViewSetMarkCategoryIconFromPixbuf :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe Pixbuf -- ^ @pixbuf@ a 'Pixbuf' or 'Nothing'. \n -> IO ()\nsourceViewSetMarkCategoryIconFromPixbuf sv category pixbuf =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_pixbuf #}\n (toSourceView sv)\n categoryPtr\n (fromMaybe (Pixbuf nullForeignPtr) pixbuf)\n\n-- | Sets the icon to be used for category to the stock item @stockId@. If @stockId@ is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromStock :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe String -- ^ @stockId@ the stock id or 'Nothing'. \n -> IO ()\nsourceViewSetMarkCategoryIconFromStock sv category stockId =\n withCString category $ \\categoryPtr ->\n maybeWith withCString stockId $ \\stockIdPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_stock #}\n (toSourceView sv)\n categoryPtr\n stockIdPtr\n\n-- | Sets the icon to be used for category to the named theme item name. If name is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromIconName :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe String -- ^ @name@ the themed icon name or 'Nothing'. \n -> IO ()\nsourceViewSetMarkCategoryIconFromIconName sv category name =\n withCString category $ \\categoryPtr ->\n maybeWith withCString name $ \\namePtr ->\n {#call gtk_source_view_set_mark_category_icon_from_icon_name #}\n (toSourceView sv)\n categoryPtr\n namePtr\n\n-- | Sets given background color for mark category. If color is 'Nothing', the background color is unset.\nsourceViewSetMarkCategoryBackground :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category. \n -> Maybe Color -- ^ @color@ background color or 'Nothing' to unset it. \n -> IO ()\nsourceViewSetMarkCategoryBackground sv category color =\n let withMB :: Storable a => Maybe a -> (Ptr a -> IO b) -> IO b\n withMB Nothing f = f nullPtr\n withMB (Just x) f = with x f\n in withCString category $ \\categoryPtr ->\n withMB color $ \\colorPtr ->\n {#call gtk_source_view_set_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n\n-- | Gets the background color associated with given category.\nsourceViewGetMarkCategoryBackground :: SourceViewClass sv => sv\n -> String -- ^ @category@ a mark category.\n -> Color -- ^ @dest@ destination 'Color' structure to fill in.\n -> IO Bool -- ^ returns 'True' if background color for category was set and dest is set to a valid color, or 'False' otherwise.\nsourceViewGetMarkCategoryBackground sv category color = \n liftM toBool $\n withCString category $ \\ categoryPtr ->\n with color $ \\ colorPtr ->\n {#call gtk_source_view_get_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n\n-- | Whether to enable auto indentation.\n-- \n-- Default value: 'False'\n--\nsourceViewAutoIndent :: SourceViewClass sv => Attr sv Bool\nsourceViewAutoIndent = newAttrFromBoolProperty \"auto-indent\"\n\n-- | Set if and how the spaces should be visualized.\n--\nsourceViewDrawSpaces :: SourceViewClass sv => Attr sv SourceDrawSpacesFlags\nsourceViewDrawSpaces = newAttrFromEnumProperty \"draw-spaces\" {#call fun gtk_source_draw_spaces_flags_get_type#}\n\n-- | Whether to highlight the current line.\n-- \n-- Default value: 'False'\n--\nsourceViewHighlightCurrentLine :: SourceViewClass sv => Attr sv Bool\nsourceViewHighlightCurrentLine = newAttrFromBoolProperty \"highlight-current-line\"\n\n-- | Whether to indent the selected text when the tab key is pressed.\n-- \n-- Default value: 'True'\n--\nsourceViewIndentOnTab :: SourceViewClass sv => Attr sv Bool\nsourceViewIndentOnTab = newAttrFromBoolProperty \"indent-on-tab\"\n\n-- | Width of an indentation step expressed in number of spaces.\n-- \n-- Allowed values: [GMaxulong,32]\n-- \n-- Default value: -1\n--\nsourceViewIndentWidth :: SourceViewClass sv => Attr sv Int\nsourceViewIndentWidth = newAttrFromIntProperty \"indent-width\"\n\n-- | Whether to insert spaces instead of tabs.\n-- \n-- Default value: 'False'\n--\nsourceViewInsertSpacesInsteadOfTabs :: SourceViewClass sv => Attr sv Bool\nsourceViewInsertSpacesInsteadOfTabs = newAttrFromBoolProperty \"insert-spaces-instead-of-tabs\"\n\n-- | Position of the right margin.\n-- \n-- Allowed values: [1,200]\n-- \n-- Default value: 80\n--\nsourceViewRightMarginPosition :: SourceViewClass sv => Attr sv Int\nsourceViewRightMarginPosition = newAttrFromUIntProperty \"right-margin-position\"\n\n-- | Whether to display line numbers\n-- \n-- Default value: 'False'\n--\nsourceViewShowLineNumbers :: SourceViewClass sv => Attr sv Bool\nsourceViewShowLineNumbers = newAttrFromBoolProperty \"show-line-numbers\"\n\n-- | Whether to display line mark pixbufs\n-- \n-- Default value: 'False'\n--\nsourceViewShowRightMargin :: SourceViewClass sv => Attr sv Bool\nsourceViewShowRightMargin = newAttrFromBoolProperty \"show-right-margin\"\n\n-- | Set the behavior of the HOME and END keys.\n-- \n-- Default value: 'SourceSmartHomeEndDisabled'\n-- \n-- Since 2.0\n--\nsourceViewSmartHomeEnd :: SourceViewClass sv => Attr sv SourceSmartHomeEndType\nsourceViewSmartHomeEnd = newAttrFromEnumProperty \"smart-home-end\" {#call fun gtk_source_smart_home_end_type_get_type#}\n\n-- | Width of an tab character expressed in number of spaces.\n-- \n-- Allowed values: [1,32]\n-- \n-- Default value: 8\n--\nsourceViewTabWidth :: SourceViewClass sv => Attr sv Int\nsourceViewTabWidth = newAttrFromUIntProperty \"tab-width\"\n\n-- |\n--\nsourceViewUndo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewUndo = Signal $ connect_NONE__NONE \"undo\"\n\n-- |\n--\nsourceViewRedo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewRedo = Signal $ connect_NONE__NONE \"redo\"\n\n-- | The 'moveLines' signal is a keybinding which gets emitted when the user initiates moving a\n-- line. The default binding key is Alt+Up\/Down arrow. And moves the currently selected lines, or the\n-- current line by count. For the moment, only count of -1 or 1 is valid.\nsourceViewMoveLines :: SourceViewClass sv => Signal sv (Bool -> Int -> IO ())\nsourceViewMoveLines = Signal $ connect_BOOL_INT__NONE \"move-lines\"\n\n-- | The 'showCompletion' signal is a keybinding signal which gets emitted when the user initiates a\n-- completion in default mode.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the default mode completion activation.\nsourceViewShowCompletion :: SourceViewClass sv => Signal sv (IO ())\nsourceViewShowCompletion = Signal $ connect_NONE__NONE \"show-completion\"\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | 'sourceViewSetMarkCategoryPixbuf' is deprecated and should not be used in newly-written\n-- code. Use 'sourceViewSetMarkCategoryIconFromPixbuf' instead\n--\nsourceViewSetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> Pixbuf -> IO ()\nsourceViewSetMarkCategoryPixbuf sv markerType marker = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_pixbuf#} (toSourceView sv) strPtr marker\n\n-- | 'sourceViewGetMarkCategoryPixbuf' is deprecated and should not be used in newly-written code.\n--\nsourceViewGetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> IO Pixbuf\nsourceViewGetMarkCategoryPixbuf sv markerType = withCString markerType $ \\strPtr ->\n constructNewGObject mkPixbuf $\n {#call unsafe source_view_get_mark_category_pixbuf#} (toSourceView sv) strPtr\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0405c488f662ba98f328674ab8a2347361c3f0e6","subject":"Remove removed signals in the re-export module.","message":"Remove removed signals in the re-export module.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk.chs","new_file":"gtk\/Graphics\/UI\/Gtk.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n--\n-- Created: 9 April 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-- Everything that is marked as deprecated, vanishing or useless for\n-- applications is not bound.\n--\n-- The following modules are not bound:\n-- DialogMessage : has only one variadic function which cannot be bound.\n--\t\t The same functionality can be simulated with Dialog.\n-- Item :\t The only child of this abstract class is MenuItem. The\n--\t\t three signals Item defines are therefore bound in \n--\t\t MenuItem.\n--\n-- TODO\n--\n-- Every module that is commented out and not mentioned above.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This module gathers all publicly available functions from the Gtk binding.\n--\nmodule Graphics.UI.Gtk (\n -- * General things, initialization\n module Graphics.UI.Gtk.General.General,\n module Graphics.UI.Gtk.General.IconFactory,\n module Graphics.UI.Gtk.General.StockItems,\n module Graphics.UI.Gtk.General.Selection,\n module Graphics.UI.Gtk.General.Drag,\n module Graphics.UI.Gtk.Gdk.Keys,\n module Graphics.UI.Gtk.General.Style,\n module Graphics.UI.Gtk.General.RcStyle,\n module Graphics.UI.Gtk.General.Clipboard,\n\n -- * Drawing and other Low-Level Operations\n module Graphics.UI.Gtk.Gdk.Cursor,\n module Graphics.UI.Gtk.Gdk.Drawable,\n module Graphics.UI.Gtk.Gdk.DrawWindow,\n module Graphics.UI.Gtk.Gdk.Region,\n-- module Graphics.UI.Gtk.Gdk.GC,\n module Graphics.UI.Gtk.Gdk.EventM,\n module Graphics.UI.Gtk.Gdk.Pixbuf,\n module Graphics.UI.Gtk.Gdk.Pixmap,\n module Graphics.UI.Gtk.Gdk.Screen,\n module Graphics.UI.Gtk.Gdk.Display,\n module Graphics.UI.Gtk.Gdk.Gdk,\n -- ** cairo integration\n module Graphics.UI.Gtk.Cairo,\n -- * Windows\n module Graphics.UI.Gtk.Windows.Window,\n module Graphics.UI.Gtk.Windows.Invisible,\n module Graphics.UI.Gtk.Windows.Dialog,\n module Graphics.UI.Gtk.Windows.AboutDialog,\n module Graphics.UI.Gtk.Windows.MessageDialog,\n module Graphics.UI.Gtk.Windows.WindowGroup,\n -- * Display widgets,\n module Graphics.UI.Gtk.Display.AccelLabel,\n module Graphics.UI.Gtk.Display.Image,\n module Graphics.UI.Gtk.Display.Label,\n module Graphics.UI.Gtk.Display.ProgressBar,\n module Graphics.UI.Gtk.Display.Statusbar,\n module Graphics.UI.Gtk.Display.StatusIcon,\n -- * Buttons and toggles\n module Graphics.UI.Gtk.Buttons.Button,\n module Graphics.UI.Gtk.Buttons.CheckButton,\n module Graphics.UI.Gtk.Buttons.RadioButton,\n module Graphics.UI.Gtk.Buttons.ToggleButton,\n -- * Numeric\\\/text data entry\n module Graphics.UI.Gtk.Entry.Editable,\n module Graphics.UI.Gtk.Entry.Entry,\n module Graphics.UI.Gtk.Entry.EntryCompletion,\n module Graphics.UI.Gtk.Entry.HScale,\n module Graphics.UI.Gtk.Entry.VScale,\n module Graphics.UI.Gtk.Entry.SpinButton,\n -- * Multiline text editor\n module Graphics.UI.Gtk.Multiline.TextIter,\n module Graphics.UI.Gtk.Multiline.TextMark,\n module Graphics.UI.Gtk.Multiline.TextBuffer,\n module Graphics.UI.Gtk.Multiline.TextTag,\n module Graphics.UI.Gtk.Multiline.TextTagTable,\n module Graphics.UI.Gtk.Multiline.TextView,\n -- * Tree and list widget\n module Graphics.UI.Gtk.ModelView.CellLayout,\n module Graphics.UI.Gtk.ModelView.CellRenderer,\n module Graphics.UI.Gtk.ModelView.CellRendererCombo,\n module Graphics.UI.Gtk.ModelView.CellRendererPixbuf,\n module Graphics.UI.Gtk.ModelView.CellRendererProgress,\n module Graphics.UI.Gtk.ModelView.CellRendererText,\n module Graphics.UI.Gtk.ModelView.CellRendererToggle,\n module Graphics.UI.Gtk.ModelView.CellView,\n module Graphics.UI.Gtk.ModelView.CustomStore,\n module Graphics.UI.Gtk.ModelView.IconView,\n module Graphics.UI.Gtk.ModelView.ListStore,\n module Graphics.UI.Gtk.ModelView.TreeDrag,\n module Graphics.UI.Gtk.ModelView.TreeModel,\n module Graphics.UI.Gtk.ModelView.TreeModelSort,\n module Graphics.UI.Gtk.ModelView.TreeSortable,\n module Graphics.UI.Gtk.ModelView.TreeModelFilter,\n module Graphics.UI.Gtk.ModelView.TreeRowReference,\n module Graphics.UI.Gtk.ModelView.TreeSelection,\n module Graphics.UI.Gtk.ModelView.TreeStore,\n module Graphics.UI.Gtk.ModelView.TreeView,\n module Graphics.UI.Gtk.ModelView.TreeViewColumn,\n -- * Menus, combo box, toolbar\n module Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Combo,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBox,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry,\n module Graphics.UI.Gtk.MenuComboToolbar.Menu,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuBar,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuShell,\n module Graphics.UI.Gtk.MenuComboToolbar.OptionMenu,\n module Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Toolbar,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolItem,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem,\n-- * Action-based menus and toolbars\n module Graphics.UI.Gtk.ActionMenuToolbar.Action,\n module Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup,\n module Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.RadioAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.UIManager,\n -- * Selectors (file\\\/font\\\/color)\n module Graphics.UI.Gtk.Selectors.ColorSelection,\n module Graphics.UI.Gtk.Selectors.ColorSelectionDialog,\n module Graphics.UI.Gtk.Selectors.ColorButton,\n module Graphics.UI.Gtk.Selectors.FileSelection,\n module Graphics.UI.Gtk.Selectors.FontSelection,\n module Graphics.UI.Gtk.Selectors.FontSelectionDialog,\n module Graphics.UI.Gtk.Selectors.FontButton,\n-- module InputDialog,\n -- ** File chooser\n module Graphics.UI.Gtk.Selectors.FileChooser,\n module Graphics.UI.Gtk.Selectors.FileChooserDialog,\n module Graphics.UI.Gtk.Selectors.FileChooserWidget,\n module Graphics.UI.Gtk.Selectors.FileChooserButton,\n module Graphics.UI.Gtk.Selectors.FileFilter,\n -- * Layout containers\n module Graphics.UI.Gtk.Layout.Alignment,\n module Graphics.UI.Gtk.Layout.AspectFrame,\n module Graphics.UI.Gtk.Layout.HBox,\n module Graphics.UI.Gtk.Layout.HButtonBox,\n module Graphics.UI.Gtk.Layout.Fixed,\n module Graphics.UI.Gtk.Layout.HPaned,\n module Graphics.UI.Gtk.Layout.Layout,\n module Graphics.UI.Gtk.Layout.Notebook,\n module Graphics.UI.Gtk.Layout.Expander,\n module Graphics.UI.Gtk.Layout.Table,\n module Graphics.UI.Gtk.Layout.VBox,\n module Graphics.UI.Gtk.Layout.VButtonBox,\n module Graphics.UI.Gtk.Layout.VPaned,\n -- * Ornaments\n module Graphics.UI.Gtk.Ornaments.Frame,\n module Graphics.UI.Gtk.Ornaments.HSeparator,\n module Graphics.UI.Gtk.Ornaments.VSeparator,\n -- * Scrolling\n module Graphics.UI.Gtk.Scrolling.HScrollbar,\n module Graphics.UI.Gtk.Scrolling.ScrolledWindow,\n module Graphics.UI.Gtk.Scrolling.VScrollbar,\n -- * Miscellaneous\n module Graphics.UI.Gtk.Misc.Adjustment,\n module Graphics.UI.Gtk.Misc.Arrow,\n module Graphics.UI.Gtk.Misc.Calendar,\n module Graphics.UI.Gtk.Misc.DrawingArea,\n module Graphics.UI.Gtk.Misc.EventBox,\n module Graphics.UI.Gtk.Misc.HandleBox,\n module Graphics.UI.Gtk.Misc.IMMulticontext,\n module Graphics.UI.Gtk.Misc.SizeGroup,\n module Graphics.UI.Gtk.Misc.Tooltips,\n module Graphics.UI.Gtk.Misc.Viewport,\n -- * Abstract base classes\n module Graphics.UI.Gtk.Abstract.Box,\n module Graphics.UI.Gtk.Abstract.ButtonBox,\n module Graphics.UI.Gtk.Abstract.Container,\n module Graphics.UI.Gtk.Abstract.Bin,\n module Graphics.UI.Gtk.Abstract.Misc,\n module Graphics.UI.Gtk.Abstract.IMContext,\n module Graphics.UI.Gtk.Abstract.Object,\n module Graphics.UI.Gtk.Abstract.Paned,\n module Graphics.UI.Gtk.Abstract.Range,\n module Graphics.UI.Gtk.Abstract.Scale,\n module Graphics.UI.Gtk.Abstract.Scrollbar,\n module Graphics.UI.Gtk.Abstract.Separator,\n module Graphics.UI.Gtk.Abstract.Widget,\n -- * Cross-process embedding\n module Graphics.UI.Gtk.Embedding.Plug,\n module Graphics.UI.Gtk.Embedding.Socket,\n -- * Non-widgets\n module System.Glib.Signals,\n module System.Glib.Attributes,\n module System.Glib.GObject,\n module Graphics.UI.Gtk.Builder,\n\n -- * Pango text layout modules\n module Graphics.Rendering.Pango.Context,\n module Graphics.Rendering.Pango.Markup,\n module Graphics.Rendering.Pango.Layout,\n module Graphics.Rendering.Pango.Rendering,\n module Graphics.Rendering.Pango.Font,\n module Graphics.Rendering.Pango.Enums\n ) where\n\n-- general things, initialization\nimport Graphics.UI.Gtk.General.General\nimport Graphics.UI.Gtk.General.IconFactory\nimport Graphics.UI.Gtk.General.StockItems\nimport Graphics.UI.Gtk.General.Selection\nimport Graphics.UI.Gtk.General.Drag\nimport Graphics.UI.Gtk.General.Clipboard\n-- drawing\nimport Graphics.UI.Gtk.Gdk.Keys\nimport Graphics.UI.Gtk.General.Style\nimport Graphics.UI.Gtk.General.RcStyle\nimport Graphics.UI.Gtk.Gdk.Cursor\nimport Graphics.UI.Gtk.Gdk.Drawable\nimport Graphics.UI.Gtk.Gdk.DrawWindow\nimport Graphics.UI.Gtk.Gdk.Region\t\thiding (makeNewRegion)\n--import Graphics.UI.Gtk.Gdk.GC\nimport Graphics.UI.Gtk.Gdk.EventM\nimport Graphics.UI.Gtk.Gdk.Pixbuf\nimport Graphics.UI.Gtk.Gdk.Pixmap\nimport Graphics.UI.Gtk.Gdk.Screen\nimport Graphics.UI.Gtk.Gdk.Display\nimport Graphics.UI.Gtk.Gdk.Gdk\n-- cairo integration\nimport Graphics.UI.Gtk.Cairo\n-- windows\nimport Graphics.UI.Gtk.Windows.Dialog\nimport Graphics.UI.Gtk.Windows.Window\nimport Graphics.UI.Gtk.Windows.Invisible\nimport Graphics.UI.Gtk.Windows.AboutDialog\nimport Graphics.UI.Gtk.Windows.MessageDialog\nimport Graphics.UI.Gtk.Windows.WindowGroup\n-- display widgets\nimport Graphics.UI.Gtk.Display.AccelLabel\nimport Graphics.UI.Gtk.Display.Image\nimport Graphics.UI.Gtk.Display.Label\nimport Graphics.UI.Gtk.Display.ProgressBar\nimport Graphics.UI.Gtk.Display.Statusbar\n#if GTK_CHECK_VERSION(2,10,0) && !DISABLE_DEPRECATED\nimport Graphics.UI.Gtk.Display.StatusIcon hiding (onActivate,afterActivate,onPopupMenu,afterPopupMenu)\n#else\nimport Graphics.UI.Gtk.Display.StatusIcon\n#endif\n-- buttons and toggles\nimport Graphics.UI.Gtk.Buttons.Button\nimport Graphics.UI.Gtk.Buttons.CheckButton\nimport Graphics.UI.Gtk.Buttons.RadioButton\nimport Graphics.UI.Gtk.Buttons.ToggleButton\n-- numeric\\\/text data entry\nimport Graphics.UI.Gtk.Entry.Editable\nimport Graphics.UI.Gtk.Entry.Entry\nimport Graphics.UI.Gtk.Entry.EntryCompletion\nimport Graphics.UI.Gtk.Entry.HScale\nimport Graphics.UI.Gtk.Entry.VScale\nimport Graphics.UI.Gtk.Entry.SpinButton\n-- multiline text editor\nimport Graphics.UI.Gtk.Multiline.TextIter\nimport Graphics.UI.Gtk.Multiline.TextMark\nimport Graphics.UI.Gtk.Multiline.TextBuffer\nimport Graphics.UI.Gtk.Multiline.TextTag\nimport Graphics.UI.Gtk.Multiline.TextTagTable\nimport qualified Graphics.UI.Gtk.Multiline.TextView\nimport Graphics.UI.Gtk.Multiline.TextView\n-- tree and list widget\nimport Graphics.UI.Gtk.ModelView.CellLayout\nimport Graphics.UI.Gtk.ModelView.CellRenderer\nimport Graphics.UI.Gtk.ModelView.CellRendererCombo\nimport Graphics.UI.Gtk.ModelView.CellRendererPixbuf\nimport Graphics.UI.Gtk.ModelView.CellRendererProgress\nimport Graphics.UI.Gtk.ModelView.CellRendererText\nimport Graphics.UI.Gtk.ModelView.CellRendererToggle\nimport Graphics.UI.Gtk.ModelView.CellView\nimport Graphics.UI.Gtk.ModelView.CustomStore\nimport Graphics.UI.Gtk.ModelView.IconView\nimport Graphics.UI.Gtk.ModelView.ListStore\nimport Graphics.UI.Gtk.ModelView.TreeDrag\nimport Graphics.UI.Gtk.ModelView.TreeModel\nimport Graphics.UI.Gtk.ModelView.TreeModelSort\nimport Graphics.UI.Gtk.ModelView.TreeSortable\nimport Graphics.UI.Gtk.ModelView.TreeModelFilter\nimport Graphics.UI.Gtk.ModelView.TreeRowReference\nimport Graphics.UI.Gtk.ModelView.TreeSelection\nimport Graphics.UI.Gtk.ModelView.TreeStore\nimport Graphics.UI.Gtk.ModelView.TreeView\nimport Graphics.UI.Gtk.ModelView.TreeViewColumn\n-- menus, combo box, toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.Combo\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBox\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry\n-- import ItemFactory\nimport Graphics.UI.Gtk.MenuComboToolbar.Menu\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuBar\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuShell\nimport Graphics.UI.Gtk.MenuComboToolbar.OptionMenu\nimport Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.Toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolItem\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem\n-- action based menus and toolbars\nimport Graphics.UI.Gtk.ActionMenuToolbar.Action\nimport Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup\nimport Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.RadioAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.UIManager\n-- selectors (file\\\/font\\\/color\\\/input device)\nimport Graphics.UI.Gtk.Selectors.ColorSelection\nimport Graphics.UI.Gtk.Selectors.ColorSelectionDialog\nimport Graphics.UI.Gtk.Selectors.ColorButton\nimport Graphics.UI.Gtk.Selectors.FileSelection\nimport Graphics.UI.Gtk.Selectors.FileChooser\nimport Graphics.UI.Gtk.Selectors.FileChooserDialog\nimport Graphics.UI.Gtk.Selectors.FileChooserWidget\nimport Graphics.UI.Gtk.Selectors.FileChooserButton\nimport Graphics.UI.Gtk.Selectors.FileFilter\nimport Graphics.UI.Gtk.Selectors.FontSelection\nimport Graphics.UI.Gtk.Selectors.FontSelectionDialog\nimport Graphics.UI.Gtk.Selectors.FontButton\n--import InputDialog\n-- layout containers\nimport Graphics.UI.Gtk.Layout.Alignment\nimport Graphics.UI.Gtk.Layout.AspectFrame\nimport Graphics.UI.Gtk.Layout.HBox\nimport Graphics.UI.Gtk.Layout.VBox\nimport Graphics.UI.Gtk.Layout.HButtonBox\nimport Graphics.UI.Gtk.Layout.VButtonBox\nimport Graphics.UI.Gtk.Layout.Fixed\nimport Graphics.UI.Gtk.Layout.HPaned\nimport Graphics.UI.Gtk.Layout.VPaned\nimport Graphics.UI.Gtk.Layout.Layout\nimport Graphics.UI.Gtk.Layout.Notebook\nimport Graphics.UI.Gtk.Layout.Expander\nimport Graphics.UI.Gtk.Layout.Table\n-- ornaments\nimport Graphics.UI.Gtk.Ornaments.Frame\nimport Graphics.UI.Gtk.Ornaments.HSeparator\nimport Graphics.UI.Gtk.Ornaments.VSeparator\n-- scrolling\nimport Graphics.UI.Gtk.Scrolling.HScrollbar\nimport Graphics.UI.Gtk.Scrolling.VScrollbar\nimport Graphics.UI.Gtk.Scrolling.ScrolledWindow\n-- miscellaneous\nimport Graphics.UI.Gtk.Misc.Adjustment\nimport Graphics.UI.Gtk.Misc.Arrow\nimport Graphics.UI.Gtk.Misc.Calendar\nimport Graphics.UI.Gtk.Misc.DrawingArea\nimport Graphics.UI.Gtk.Misc.EventBox\nimport Graphics.UI.Gtk.Misc.HandleBox\nimport Graphics.UI.Gtk.Misc.IMMulticontext\nimport Graphics.UI.Gtk.Misc.SizeGroup\nimport Graphics.UI.Gtk.Misc.Tooltips\nimport Graphics.UI.Gtk.Misc.Viewport\n--import Accessible\n-- abstract base classes\nimport Graphics.UI.Gtk.Abstract.Box\nimport Graphics.UI.Gtk.Abstract.ButtonBox\nimport Graphics.UI.Gtk.Abstract.Container\nimport Graphics.UI.Gtk.Abstract.Bin\nimport Graphics.UI.Gtk.Abstract.Misc\nimport Graphics.UI.Gtk.Abstract.IMContext\nimport Graphics.UI.Gtk.Abstract.Object (\n Object,\n ObjectClass,\n castToObject,\n toObject,\n GWeakNotify,\n objectWeakref,\n objectWeakunref,\n objectDestroy )\nimport Graphics.UI.Gtk.Abstract.Paned\nimport Graphics.UI.Gtk.Abstract.Range\nimport Graphics.UI.Gtk.Abstract.Scale\nimport Graphics.UI.Gtk.Abstract.Scrollbar\nimport Graphics.UI.Gtk.Abstract.Separator\nimport Graphics.UI.Gtk.Abstract.Widget\n-- cross-process embedding\nimport Graphics.UI.Gtk.Embedding.Plug\nimport Graphics.UI.Gtk.Embedding.Socket\n\n-- non widgets\nimport System.Glib.Signals\n{- do eport 'on' and 'after'\n\t\t(ConnectId, disconnect,\n\t\t\t\t\t signalDisconnect,\n\t\t\t\t\t signalBlock,\n\t\t\t\t\t signalUnblock)\n-}\nimport System.Glib.Attributes\nimport System.Glib.GObject (\n GObject,\n GObjectClass,\n toGObject,\n castToGObject,\n quarkFromString,\n objectCreateAttribute,\n objectSetAttribute,\n objectGetAttributeUnsafe,\n isA\n )\nimport Graphics.UI.Gtk.Builder\n \n-- pango modules\nimport Graphics.Rendering.Pango.Context\nimport Graphics.Rendering.Pango.Markup\nimport Graphics.Rendering.Pango.Layout\nimport Graphics.Rendering.Pango.Rendering\nimport Graphics.Rendering.Pango.Font\nimport Graphics.Rendering.Pango.Enums\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n--\n-- Created: 9 April 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-- Everything that is marked as deprecated, vanishing or useless for\n-- applications is not bound.\n--\n-- The following modules are not bound:\n-- DialogMessage : has only one variadic function which cannot be bound.\n--\t\t The same functionality can be simulated with Dialog.\n-- Item :\t The only child of this abstract class is MenuItem. The\n--\t\t three signals Item defines are therefore bound in \n--\t\t MenuItem.\n--\n-- TODO\n--\n-- Every module that is commented out and not mentioned above.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This module gathers all publicly available functions from the Gtk binding.\n--\nmodule Graphics.UI.Gtk (\n -- * General things, initialization\n module Graphics.UI.Gtk.General.General,\n module Graphics.UI.Gtk.General.IconFactory,\n module Graphics.UI.Gtk.General.StockItems,\n module Graphics.UI.Gtk.General.Selection,\n module Graphics.UI.Gtk.General.Drag,\n module Graphics.UI.Gtk.Gdk.Keys,\n module Graphics.UI.Gtk.General.Style,\n module Graphics.UI.Gtk.General.RcStyle,\n module Graphics.UI.Gtk.General.Clipboard,\n\n -- * Drawing and other Low-Level Operations\n module Graphics.UI.Gtk.Gdk.Cursor,\n module Graphics.UI.Gtk.Gdk.Drawable,\n module Graphics.UI.Gtk.Gdk.DrawWindow,\n module Graphics.UI.Gtk.Gdk.Region,\n-- module Graphics.UI.Gtk.Gdk.GC,\n module Graphics.UI.Gtk.Gdk.EventM,\n module Graphics.UI.Gtk.Gdk.Pixbuf,\n module Graphics.UI.Gtk.Gdk.Pixmap,\n module Graphics.UI.Gtk.Gdk.Screen,\n module Graphics.UI.Gtk.Gdk.Display,\n module Graphics.UI.Gtk.Gdk.Gdk,\n -- ** cairo integration\n module Graphics.UI.Gtk.Cairo,\n -- * Windows\n module Graphics.UI.Gtk.Windows.Window,\n module Graphics.UI.Gtk.Windows.Invisible,\n module Graphics.UI.Gtk.Windows.Dialog,\n module Graphics.UI.Gtk.Windows.AboutDialog,\n module Graphics.UI.Gtk.Windows.MessageDialog,\n module Graphics.UI.Gtk.Windows.WindowGroup,\n -- * Display widgets,\n module Graphics.UI.Gtk.Display.AccelLabel,\n module Graphics.UI.Gtk.Display.Image,\n module Graphics.UI.Gtk.Display.Label,\n module Graphics.UI.Gtk.Display.ProgressBar,\n module Graphics.UI.Gtk.Display.Statusbar,\n module Graphics.UI.Gtk.Display.StatusIcon,\n -- * Buttons and toggles\n module Graphics.UI.Gtk.Buttons.Button,\n module Graphics.UI.Gtk.Buttons.CheckButton,\n module Graphics.UI.Gtk.Buttons.RadioButton,\n module Graphics.UI.Gtk.Buttons.ToggleButton,\n -- * Numeric\\\/text data entry\n module Graphics.UI.Gtk.Entry.Editable,\n module Graphics.UI.Gtk.Entry.Entry,\n module Graphics.UI.Gtk.Entry.EntryCompletion,\n module Graphics.UI.Gtk.Entry.HScale,\n module Graphics.UI.Gtk.Entry.VScale,\n module Graphics.UI.Gtk.Entry.SpinButton,\n -- * Multiline text editor\n module Graphics.UI.Gtk.Multiline.TextIter,\n module Graphics.UI.Gtk.Multiline.TextMark,\n module Graphics.UI.Gtk.Multiline.TextBuffer,\n module Graphics.UI.Gtk.Multiline.TextTag,\n module Graphics.UI.Gtk.Multiline.TextTagTable,\n module Graphics.UI.Gtk.Multiline.TextView,\n -- * Tree and list widget\n module Graphics.UI.Gtk.ModelView.CellLayout,\n module Graphics.UI.Gtk.ModelView.CellRenderer,\n module Graphics.UI.Gtk.ModelView.CellRendererCombo,\n module Graphics.UI.Gtk.ModelView.CellRendererPixbuf,\n module Graphics.UI.Gtk.ModelView.CellRendererProgress,\n module Graphics.UI.Gtk.ModelView.CellRendererText,\n module Graphics.UI.Gtk.ModelView.CellRendererToggle,\n module Graphics.UI.Gtk.ModelView.CellView,\n module Graphics.UI.Gtk.ModelView.CustomStore,\n module Graphics.UI.Gtk.ModelView.IconView,\n module Graphics.UI.Gtk.ModelView.ListStore,\n module Graphics.UI.Gtk.ModelView.TreeDrag,\n module Graphics.UI.Gtk.ModelView.TreeModel,\n module Graphics.UI.Gtk.ModelView.TreeModelSort,\n module Graphics.UI.Gtk.ModelView.TreeSortable,\n module Graphics.UI.Gtk.ModelView.TreeModelFilter,\n module Graphics.UI.Gtk.ModelView.TreeRowReference,\n module Graphics.UI.Gtk.ModelView.TreeSelection,\n module Graphics.UI.Gtk.ModelView.TreeStore,\n module Graphics.UI.Gtk.ModelView.TreeView,\n module Graphics.UI.Gtk.ModelView.TreeViewColumn,\n -- * Menus, combo box, toolbar\n module Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Combo,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBox,\n module Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry,\n module Graphics.UI.Gtk.MenuComboToolbar.Menu,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuBar,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuShell,\n module Graphics.UI.Gtk.MenuComboToolbar.OptionMenu,\n module Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.Toolbar,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolItem,\n module Graphics.UI.Gtk.MenuComboToolbar.ToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem,\n module Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem,\n-- * Action-based menus and toolbars\n module Graphics.UI.Gtk.ActionMenuToolbar.Action,\n module Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup,\n module Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.RadioAction,\n module Graphics.UI.Gtk.ActionMenuToolbar.UIManager,\n -- * Selectors (file\\\/font\\\/color)\n module Graphics.UI.Gtk.Selectors.ColorSelection,\n module Graphics.UI.Gtk.Selectors.ColorSelectionDialog,\n module Graphics.UI.Gtk.Selectors.ColorButton,\n module Graphics.UI.Gtk.Selectors.FileSelection,\n module Graphics.UI.Gtk.Selectors.FontSelection,\n module Graphics.UI.Gtk.Selectors.FontSelectionDialog,\n module Graphics.UI.Gtk.Selectors.FontButton,\n-- module InputDialog,\n -- ** File chooser\n module Graphics.UI.Gtk.Selectors.FileChooser,\n module Graphics.UI.Gtk.Selectors.FileChooserDialog,\n module Graphics.UI.Gtk.Selectors.FileChooserWidget,\n module Graphics.UI.Gtk.Selectors.FileChooserButton,\n module Graphics.UI.Gtk.Selectors.FileFilter,\n -- * Layout containers\n module Graphics.UI.Gtk.Layout.Alignment,\n module Graphics.UI.Gtk.Layout.AspectFrame,\n module Graphics.UI.Gtk.Layout.HBox,\n module Graphics.UI.Gtk.Layout.HButtonBox,\n module Graphics.UI.Gtk.Layout.Fixed,\n module Graphics.UI.Gtk.Layout.HPaned,\n module Graphics.UI.Gtk.Layout.Layout,\n module Graphics.UI.Gtk.Layout.Notebook,\n module Graphics.UI.Gtk.Layout.Expander,\n module Graphics.UI.Gtk.Layout.Table,\n module Graphics.UI.Gtk.Layout.VBox,\n module Graphics.UI.Gtk.Layout.VButtonBox,\n module Graphics.UI.Gtk.Layout.VPaned,\n -- * Ornaments\n module Graphics.UI.Gtk.Ornaments.Frame,\n module Graphics.UI.Gtk.Ornaments.HSeparator,\n module Graphics.UI.Gtk.Ornaments.VSeparator,\n -- * Scrolling\n module Graphics.UI.Gtk.Scrolling.HScrollbar,\n module Graphics.UI.Gtk.Scrolling.ScrolledWindow,\n module Graphics.UI.Gtk.Scrolling.VScrollbar,\n -- * Miscellaneous\n module Graphics.UI.Gtk.Misc.Adjustment,\n module Graphics.UI.Gtk.Misc.Arrow,\n module Graphics.UI.Gtk.Misc.Calendar,\n module Graphics.UI.Gtk.Misc.DrawingArea,\n module Graphics.UI.Gtk.Misc.EventBox,\n module Graphics.UI.Gtk.Misc.HandleBox,\n module Graphics.UI.Gtk.Misc.IMMulticontext,\n module Graphics.UI.Gtk.Misc.SizeGroup,\n module Graphics.UI.Gtk.Misc.Tooltips,\n module Graphics.UI.Gtk.Misc.Viewport,\n -- * Abstract base classes\n module Graphics.UI.Gtk.Abstract.Box,\n module Graphics.UI.Gtk.Abstract.ButtonBox,\n module Graphics.UI.Gtk.Abstract.Container,\n module Graphics.UI.Gtk.Abstract.Bin,\n module Graphics.UI.Gtk.Abstract.Misc,\n module Graphics.UI.Gtk.Abstract.IMContext,\n module Graphics.UI.Gtk.Abstract.Object,\n module Graphics.UI.Gtk.Abstract.Paned,\n module Graphics.UI.Gtk.Abstract.Range,\n module Graphics.UI.Gtk.Abstract.Scale,\n module Graphics.UI.Gtk.Abstract.Scrollbar,\n module Graphics.UI.Gtk.Abstract.Separator,\n module Graphics.UI.Gtk.Abstract.Widget,\n -- * Cross-process embedding\n module Graphics.UI.Gtk.Embedding.Plug,\n module Graphics.UI.Gtk.Embedding.Socket,\n -- * Non-widgets\n module System.Glib.Signals,\n module System.Glib.Attributes,\n module System.Glib.GObject,\n module Graphics.UI.Gtk.Builder,\n\n -- * Pango text layout modules\n module Graphics.Rendering.Pango.Context,\n module Graphics.Rendering.Pango.Markup,\n module Graphics.Rendering.Pango.Layout,\n module Graphics.Rendering.Pango.Rendering,\n module Graphics.Rendering.Pango.Font,\n module Graphics.Rendering.Pango.Enums\n ) where\n\n-- general things, initialization\nimport Graphics.UI.Gtk.General.General\nimport Graphics.UI.Gtk.General.IconFactory\nimport Graphics.UI.Gtk.General.StockItems\nimport Graphics.UI.Gtk.General.Selection\nimport Graphics.UI.Gtk.General.Drag\nimport Graphics.UI.Gtk.General.Clipboard\n-- drawing\nimport Graphics.UI.Gtk.Gdk.Keys\nimport Graphics.UI.Gtk.General.Style\nimport Graphics.UI.Gtk.General.RcStyle\nimport Graphics.UI.Gtk.Gdk.Cursor\nimport Graphics.UI.Gtk.Gdk.Drawable\nimport Graphics.UI.Gtk.Gdk.DrawWindow\nimport Graphics.UI.Gtk.Gdk.Region\t\thiding (makeNewRegion)\n--import Graphics.UI.Gtk.Gdk.GC\nimport Graphics.UI.Gtk.Gdk.EventM\nimport Graphics.UI.Gtk.Gdk.Pixbuf\nimport Graphics.UI.Gtk.Gdk.Pixmap\nimport Graphics.UI.Gtk.Gdk.Screen\nimport Graphics.UI.Gtk.Gdk.Display\nimport Graphics.UI.Gtk.Gdk.Gdk\n-- cairo integration\nimport Graphics.UI.Gtk.Cairo\n-- windows\nimport Graphics.UI.Gtk.Windows.Dialog\nimport Graphics.UI.Gtk.Windows.Window\nimport Graphics.UI.Gtk.Windows.Invisible\nimport Graphics.UI.Gtk.Windows.AboutDialog\nimport Graphics.UI.Gtk.Windows.MessageDialog\nimport Graphics.UI.Gtk.Windows.WindowGroup\n-- display widgets\nimport Graphics.UI.Gtk.Display.AccelLabel\nimport Graphics.UI.Gtk.Display.Image\nimport Graphics.UI.Gtk.Display.Label\nimport Graphics.UI.Gtk.Display.ProgressBar\nimport Graphics.UI.Gtk.Display.Statusbar\n#if GTK_CHECK_VERSION(2,10,0) && !DISABLE_DEPRECATED\nimport Graphics.UI.Gtk.Display.StatusIcon hiding (onActivate,afterActivate,onPopupMenu,afterPopupMenu)\n#else\nimport Graphics.UI.Gtk.Display.StatusIcon\n#endif\n-- buttons and toggles\nimport Graphics.UI.Gtk.Buttons.Button\nimport Graphics.UI.Gtk.Buttons.CheckButton\nimport Graphics.UI.Gtk.Buttons.RadioButton\nimport Graphics.UI.Gtk.Buttons.ToggleButton\n-- numeric\\\/text data entry\nimport Graphics.UI.Gtk.Entry.Editable\nimport Graphics.UI.Gtk.Entry.Entry\nimport Graphics.UI.Gtk.Entry.EntryCompletion\nimport Graphics.UI.Gtk.Entry.HScale\nimport Graphics.UI.Gtk.Entry.VScale\nimport Graphics.UI.Gtk.Entry.SpinButton\n-- multiline text editor\nimport Graphics.UI.Gtk.Multiline.TextIter\nimport Graphics.UI.Gtk.Multiline.TextMark\nimport Graphics.UI.Gtk.Multiline.TextBuffer\nimport Graphics.UI.Gtk.Multiline.TextTag\nimport Graphics.UI.Gtk.Multiline.TextTagTable\nimport qualified Graphics.UI.Gtk.Multiline.TextView\nimport Graphics.UI.Gtk.Multiline.TextView\n#ifndef DISABLE_DEPRECATED\n hiding (afterSetScrollAdjustments,\n\t\tonSetScrollAdjustments, afterCopyClipboard, onCopyClipboard,\n\t\tafterCutClipboard, onCutClipboard, afterInsertAtCursor,\n\t\tonInsertAtCursor, afterPasteClipboard, onPasteClipboard,\n\t\tafterToggleOverwrite, onToggleOverwrite, setScrollAdjustments)\n#endif\n-- tree and list widget\nimport Graphics.UI.Gtk.ModelView.CellLayout\nimport Graphics.UI.Gtk.ModelView.CellRenderer\nimport Graphics.UI.Gtk.ModelView.CellRendererCombo\nimport Graphics.UI.Gtk.ModelView.CellRendererPixbuf\nimport Graphics.UI.Gtk.ModelView.CellRendererProgress\nimport Graphics.UI.Gtk.ModelView.CellRendererText\nimport Graphics.UI.Gtk.ModelView.CellRendererToggle\nimport Graphics.UI.Gtk.ModelView.CellView\nimport Graphics.UI.Gtk.ModelView.CustomStore\nimport Graphics.UI.Gtk.ModelView.IconView\nimport Graphics.UI.Gtk.ModelView.ListStore\nimport Graphics.UI.Gtk.ModelView.TreeDrag\nimport Graphics.UI.Gtk.ModelView.TreeModel\nimport Graphics.UI.Gtk.ModelView.TreeModelSort\nimport Graphics.UI.Gtk.ModelView.TreeSortable\nimport Graphics.UI.Gtk.ModelView.TreeModelFilter\nimport Graphics.UI.Gtk.ModelView.TreeRowReference\nimport Graphics.UI.Gtk.ModelView.TreeSelection\nimport Graphics.UI.Gtk.ModelView.TreeStore\nimport Graphics.UI.Gtk.ModelView.TreeView\nimport Graphics.UI.Gtk.ModelView.TreeViewColumn\n-- menus, combo box, toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.Combo\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBox\nimport Graphics.UI.Gtk.MenuComboToolbar.ComboBoxEntry\n-- import ItemFactory\nimport Graphics.UI.Gtk.MenuComboToolbar.Menu\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuBar\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuShell\nimport Graphics.UI.Gtk.MenuComboToolbar.OptionMenu\nimport Graphics.UI.Gtk.MenuComboToolbar.ImageMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.CheckMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.TearoffMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.Toolbar\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolItem\nimport Graphics.UI.Gtk.MenuComboToolbar.ToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.MenuToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.ToggleToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.RadioToolButton\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorMenuItem\nimport Graphics.UI.Gtk.MenuComboToolbar.SeparatorToolItem\n-- action based menus and toolbars\nimport Graphics.UI.Gtk.ActionMenuToolbar.Action\nimport Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup\nimport Graphics.UI.Gtk.ActionMenuToolbar.ToggleAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.RadioAction\nimport Graphics.UI.Gtk.ActionMenuToolbar.UIManager\n-- selectors (file\\\/font\\\/color\\\/input device)\nimport Graphics.UI.Gtk.Selectors.ColorSelection\nimport Graphics.UI.Gtk.Selectors.ColorSelectionDialog\nimport Graphics.UI.Gtk.Selectors.ColorButton\nimport Graphics.UI.Gtk.Selectors.FileSelection\nimport Graphics.UI.Gtk.Selectors.FileChooser\nimport Graphics.UI.Gtk.Selectors.FileChooserDialog\nimport Graphics.UI.Gtk.Selectors.FileChooserWidget\nimport Graphics.UI.Gtk.Selectors.FileChooserButton\nimport Graphics.UI.Gtk.Selectors.FileFilter\nimport Graphics.UI.Gtk.Selectors.FontSelection\nimport Graphics.UI.Gtk.Selectors.FontSelectionDialog\nimport Graphics.UI.Gtk.Selectors.FontButton\n--import InputDialog\n-- layout containers\nimport Graphics.UI.Gtk.Layout.Alignment\nimport Graphics.UI.Gtk.Layout.AspectFrame\nimport Graphics.UI.Gtk.Layout.HBox\nimport Graphics.UI.Gtk.Layout.VBox\nimport Graphics.UI.Gtk.Layout.HButtonBox\nimport Graphics.UI.Gtk.Layout.VButtonBox\nimport Graphics.UI.Gtk.Layout.Fixed\nimport Graphics.UI.Gtk.Layout.HPaned\nimport Graphics.UI.Gtk.Layout.VPaned\nimport Graphics.UI.Gtk.Layout.Layout\nimport Graphics.UI.Gtk.Layout.Notebook\nimport Graphics.UI.Gtk.Layout.Expander\nimport Graphics.UI.Gtk.Layout.Table\n-- ornaments\nimport Graphics.UI.Gtk.Ornaments.Frame\nimport Graphics.UI.Gtk.Ornaments.HSeparator\nimport Graphics.UI.Gtk.Ornaments.VSeparator\n-- scrolling\nimport Graphics.UI.Gtk.Scrolling.HScrollbar\nimport Graphics.UI.Gtk.Scrolling.VScrollbar\nimport Graphics.UI.Gtk.Scrolling.ScrolledWindow\n-- miscellaneous\nimport Graphics.UI.Gtk.Misc.Adjustment\nimport Graphics.UI.Gtk.Misc.Arrow\nimport Graphics.UI.Gtk.Misc.Calendar\nimport Graphics.UI.Gtk.Misc.DrawingArea\nimport Graphics.UI.Gtk.Misc.EventBox\nimport Graphics.UI.Gtk.Misc.HandleBox\nimport Graphics.UI.Gtk.Misc.IMMulticontext\nimport Graphics.UI.Gtk.Misc.SizeGroup\nimport Graphics.UI.Gtk.Misc.Tooltips\nimport Graphics.UI.Gtk.Misc.Viewport\n--import Accessible\n-- abstract base classes\nimport Graphics.UI.Gtk.Abstract.Box\nimport Graphics.UI.Gtk.Abstract.ButtonBox\nimport Graphics.UI.Gtk.Abstract.Container\nimport Graphics.UI.Gtk.Abstract.Bin\nimport Graphics.UI.Gtk.Abstract.Misc\nimport Graphics.UI.Gtk.Abstract.IMContext\nimport Graphics.UI.Gtk.Abstract.Object (\n Object,\n ObjectClass,\n castToObject,\n toObject,\n GWeakNotify,\n objectWeakref,\n objectWeakunref,\n objectDestroy )\nimport Graphics.UI.Gtk.Abstract.Paned\nimport Graphics.UI.Gtk.Abstract.Range\nimport Graphics.UI.Gtk.Abstract.Scale\nimport Graphics.UI.Gtk.Abstract.Scrollbar\nimport Graphics.UI.Gtk.Abstract.Separator\nimport Graphics.UI.Gtk.Abstract.Widget\n-- cross-process embedding\nimport Graphics.UI.Gtk.Embedding.Plug\nimport Graphics.UI.Gtk.Embedding.Socket\n\n-- non widgets\nimport System.Glib.Signals\n{- do eport 'on' and 'after'\n\t\t(ConnectId, disconnect,\n\t\t\t\t\t signalDisconnect,\n\t\t\t\t\t signalBlock,\n\t\t\t\t\t signalUnblock)\n-}\nimport System.Glib.Attributes\nimport System.Glib.GObject (\n GObject,\n GObjectClass,\n toGObject,\n castToGObject,\n quarkFromString,\n objectCreateAttribute,\n objectSetAttribute,\n objectGetAttributeUnsafe,\n isA\n )\nimport Graphics.UI.Gtk.Builder\n \n-- pango modules\nimport Graphics.Rendering.Pango.Context\nimport Graphics.Rendering.Pango.Markup\nimport Graphics.Rendering.Pango.Layout\nimport Graphics.Rendering.Pango.Rendering\nimport Graphics.Rendering.Pango.Font\nimport Graphics.Rendering.Pango.Enums\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"015728e02163473cada0b445ec2f9aeb3a549b44","subject":"missing import for 7.8.4","message":"missing import for 7.8.4\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , createFeature\n , getFeature\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Int (Int64)\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..), CLLong(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException MultipleGeomFieldsNotSupported\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncreateFeature :: RWLayer s a -> Feature -> GDAL s ()\ncreateFeature layer feature = liftIO $ throwIfError \"createFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n void $ featureToHandle pFd feature ({#call OGR_L_CreateFeature as ^#} pL)\n\n\ngetFeature :: Layer s t a -> Int64 -> GDAL s Feature\ngetFeature layer fid = liftIO $ throwIfError \"getFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n featureFromHandle pFd ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n <*> pure True\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , createFeature\n , getFeature\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Int (Int64)\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..), CLLong(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException MultipleGeomFieldsNotSupported\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncreateFeature :: RWLayer s a -> Feature -> GDAL s ()\ncreateFeature layer feature = liftIO $ throwIfError \"createFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n void $ featureToHandle pFd feature ({#call OGR_L_CreateFeature as ^#} pL)\n\n\ngetFeature :: Layer s t a -> Int64 -> GDAL s Feature\ngetFeature layer fid = liftIO $ throwIfError \"getFeature\" $\n withLockedLayerPtr layer $ \\pL -> do\n pFd <- {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n featureFromHandle pFd ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n <*> pure True\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2801bb31aac9cc63a199da4e50f4ec09c9c38a1a","subject":"Fix shutdown crash when log\/error callback is set","message":"Fix shutdown crash when log\/error callback is set\n\nThe rd_kafka_destroy method may call back into Haskell to perform some logging. This is not allowed when attaching the finalizer\nusing Foreign.ForeignPtr. Hence we switch to Foreign.Concurrent, which allows RdKafka to call back into Haskell. We also disable\nclosing the consumer automatically in the finalizer, this should be done by the application by calling `closeConsumer` explicitly.\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 qualified Foreign.Concurrent as Concurrent\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\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 -- Issue #151\n -- rd_kafka_destroy_flags may call back into Haskell if an\n -- error or log callback is set, so we must use a concurrent\n -- finalizer\n Concurrent.addForeignPtrFinalizer ret $ do\n -- do not call 'rd_kafka_close_consumer' on destroying all Kafka.\n -- when needed, applications should do it explicitly.\n -- RD_KAFKA_DESTROY_F_NO_CONSUMER_CLOSE = 0x8\n {# call rd_kafka_destroy_flags #} realPtr 0x8\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 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","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"6fd61c5e19c12865e92a10d9d2d842be487235e5","subject":"swap argument order, possible use for partial application","message":"swap argument order, possible use for partial application\n\nIgnore-this: 9c04577ccf279a1c419cb4f80acfea8b\n\ndarcs-hash:20090722051841-115f9-d27ced64e61ceaa64100f7ee67eb3ca48748a3de.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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\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-- 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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream =\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":"ca4482ce0e6f16dd0bbf1fbe2cdb40a31ceb733c","subject":"synchronise after benchmarking","message":"synchronise after benchmarking\n\nIgnore-this: e6c678cf3f3ffa2b7ba25e6aea294520\n\ndarcs-hash:20100107000224-dcabc-f43a6298c842fbc48cda7ff326485eb7c806a93f.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"examples\/src\/scan\/Scan.chs","new_file":"examples\/src\/scan\/Scan.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n--\n-- Module : Scan\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Apply a binary operator to an array similar to 'fold', but return a\n-- successive list of values reduced from the left (or right).\n--\n--------------------------------------------------------------------------------\n\nmodule Main where\n\n#include \"scan.h\"\n\n-- Friends\nimport C2HS hiding (newArray)\nimport Time\nimport RandomVector\n\n-- System\nimport Control.Monad\nimport Control.Exception\nimport qualified Foreign.CUDA as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Reference\n--------------------------------------------------------------------------------\n\nscanList :: (Num e, Storable e) => Vector e -> IO (Vector e)\nscanList xs = do\n bnds <- getBounds xs\n xs' <- getElems xs\n (t,zs') <- benchmark 100 (return (scanl1 (+) xs')) (return ())\n putStrLn $ \"List: \" ++ shows (fromInteger (timeIn millisecond t`div`100)::Float) \" ms\"\n newListArray bnds zs'\n\n\nscanArr :: (Num e, Storable e) => Vector e -> IO (Vector e)\nscanArr xs = do\n bnds <- getBounds xs\n zs <- newArray_ bnds\n let idx = range bnds\n (t,_) <- benchmark 100 (foldM_ (k zs) 0 idx) (return ())\n putStrLn $ \"Array: \" ++ shows (fromInteger (timeIn millisecond t)\/100::Float) \" ms\"\n return zs\n where\n k zs a i = do\n x <- readArray xs i\n let z = x+a\n writeArray zs i z\n return z\n\n\n--------------------------------------------------------------------------------\n-- CUDA\n--------------------------------------------------------------------------------\n\n--\n-- Include the time to copy the data to\/from the storable array (significantly\n-- faster than from a Haskell list)\n--\nscanCUDA :: Vector Float -> IO (Vector Float)\nscanCUDA xs = do\n bnds <- getBounds xs\n zs <- newArray_ bnds\n let len = rangeSize bnds\n CUDA.allocaArray len $ \\d_xs -> do\n CUDA.allocaArray len $ \\d_zs -> do\n (t,_) <- flip (benchmark 100) CUDA.sync $ do\n withVector xs $ \\p -> CUDA.pokeArray len p d_xs\n scanl1_plusf d_xs d_zs len\n withVector zs $ \\p -> CUDA.peekArray len d_zs p\n putStrLn $ \"CUDA: \" ++ shows (fromInteger (timeIn millisecond t)\/100::Float) \" ms (with copy)\"\n\n (t',_) <- benchmark 100 (scanl1_plusf d_xs d_zs len) CUDA.sync\n putStrLn $ \"CUDA: \" ++ shows (fromInteger (timeIn millisecond t')\/100::Float) \" ms (compute only)\"\n\n return zs\n\n{# fun unsafe scanl1_plusf\n { withDP* `CUDA.DevicePtr Float'\n , withDP* `CUDA.DevicePtr Float'\n , `Int'\n } -> `()' #}\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 arr <- randomArr (1,100000) :: IO (Vector Float)\n ref <- scanList arr\n ref' <- scanArr arr\n cuda <- scanCUDA arr\n\n return ()\n\n putStr \"== Validating: \"\n verify ref ref' >>= \\rv -> assert rv (return ())\n verify ref cuda >>= \\rv -> putStrLn $ if rv then \"Ok!\" else \"INVALID!\"\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n--\n-- Module : Scan\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Apply a binary operator to an array similar to 'fold', but return a\n-- successive list of values reduced from the left (or right).\n--\n--------------------------------------------------------------------------------\n\nmodule Main where\n\n#include \"scan.h\"\n\n-- Friends\nimport C2HS hiding (newArray)\nimport Time\nimport RandomVector\n\n-- System\nimport Control.Monad\nimport Control.Exception\nimport qualified Foreign.CUDA as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Reference\n--------------------------------------------------------------------------------\n\nscanList :: (Num e, Storable e) => Vector e -> IO (Vector e)\nscanList xs = do\n bnds <- getBounds xs\n xs' <- getElems xs\n (t,zs') <- benchmark 100 (return (scanl1 (+) xs')) (return ())\n putStrLn $ \"List: \" ++ shows (fromInteger (timeIn millisecond t`div`100)::Float) \" ms\"\n newListArray bnds zs'\n\n\nscanArr :: (Num e, Storable e) => Vector e -> IO (Vector e)\nscanArr xs = do\n bnds <- getBounds xs\n zs <- newArray_ bnds\n let idx = range bnds\n (t,_) <- benchmark 100 (foldM_ (k zs) 0 idx) (return ())\n putStrLn $ \"Array: \" ++ shows (fromInteger (timeIn millisecond t)\/100::Float) \" ms\"\n return zs\n where\n k zs a i = do\n x <- readArray xs i\n let z = x+a\n writeArray zs i z\n return z\n\n\n--------------------------------------------------------------------------------\n-- CUDA\n--------------------------------------------------------------------------------\n\n--\n-- Include the time to copy the data to\/from the storable array (significantly\n-- faster than from a Haskell list)\n--\nscanCUDA :: Vector Float -> IO (Vector Float)\nscanCUDA xs = do\n bnds <- getBounds xs\n zs <- newArray_ bnds\n let len = rangeSize bnds\n CUDA.allocaArray len $ \\d_xs -> do\n CUDA.allocaArray len $ \\d_zs -> do\n (t,_) <- flip (benchmark 100) (return ()) $ do\n withVector xs $ \\p -> CUDA.pokeArray len p d_xs\n scanl1_plusf d_xs d_zs len\n withVector zs $ \\p -> CUDA.peekArray len d_zs p\n putStrLn $ \"CUDA: \" ++ shows (fromInteger (timeIn millisecond t)\/100::Float) \" ms (with copy)\"\n\n (t',_) <- benchmark 100 (scanl1_plusf d_xs d_zs len) (return ())\n putStrLn $ \"CUDA: \" ++ shows (fromInteger (timeIn millisecond t')\/100::Float) \" ms (compute only)\"\n\n return zs\n\n{# fun unsafe scanl1_plusf\n { withDP* `CUDA.DevicePtr Float'\n , withDP* `CUDA.DevicePtr Float'\n , `Int'\n } -> `()' #}\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 arr <- randomArr (1,100000) :: IO (Vector Float)\n ref <- scanList arr\n ref' <- scanArr arr\n cuda <- scanCUDA arr\n\n return ()\n\n putStr \"== Validating: \"\n verify ref ref' >>= \\rv -> assert rv (return ())\n verify ref cuda >>= \\rv -> putStrLn $ if rv then \"Ok!\" else \"INVALID!\"\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"df48b215b746e8cbcc7578a80355c37517c29167","subject":"using a frozen vector was slower","message":"using a frozen vector was slower\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\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 , bandTypedAs\n , bandCoercedTo\n {-\n , reifyBandDataType\n , reifyDataType\n -}\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\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 , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\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.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, void, (>=>))\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 Data.Maybe (fromMaybe)\nimport Data.Proxy (Proxy(..))\nimport Data.String (IsString)\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport Data.Vector.Unboxed.Mutable (unsafeRead)\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr)\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.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 | InvalidDataType !DataType\n | InvalidDriverOptions\n | UnknownRasterDataType\n | UnsupportedRasterDataType !DataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\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 (t::AccessMode) =\n Dataset (ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s t -> m ()\ncloseDataset (Dataset (rk,_)) = release rk\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) =\n Band { unBand :: RasterBandH }\n\nbandTypedAs :: Band s a t -> a -> Band s a t\nbandTypedAs = const . id\n\nbandCoercedTo :: Band s a t -> b -> Band s b t\nbandCoercedTo = const . coerce\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\n{-\nreifyBandDataType\n :: Band s t -> (forall a. GDALType a => Proxy a -> b) -> b\nreifyBandDataType b = reifyDataType (bandDataType b)\n-}\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 -> OptionList\n -> GDAL s (Dataset s ReadWrite)\ncreate _ _ _ _ GDT_Unknown _ =\n throwBindingException UnknownRasterDataType\ncreate drv path (XY 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 -> 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 :: GDALAccess -> String -> GDAL s (Dataset s t)\nopenWithMode m path =\n newDatasetHandle $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\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 =\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 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 -> OptionList -> GDAL s (Dataset s ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: forall s. RWDataset s -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s 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 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\ndatasetFileList :: Dataset s t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjection :: Dataset s t -> GDAL s (Maybe SpatialReference)\ndatasetProjection =\n liftIO . ({#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString)\n\n\nsetDatasetProjection :: RWDataset s -> SpatialReference -> GDAL s ()\nsetDatasetProjection ds srs =\n liftIO $ checkCPLError \"SetProjection\" $\n unsafeUseAsCString (srsToWkt srs)\n ({#call unsafe SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: RWDataset s -> [GroundControlPoint] -> Maybe SpatialReference -> GDAL s ()\nsetDatasetGCPs ds gcps mSrs =\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 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 -> 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 = px (envelopeMin envelope)\n , gtXDelta = px (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = py (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (py (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 -> XY Double -> XY Double\napplyGeotransform Geotransform{..} (XY x y) =\n XY (gtXOff + gtXDelta*x + gtXRot * y)\n (gtYOff + gtYRot *x + gtYDelta * y)\n{-# INLINE applyGeotransform #-}\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> XY Double -> XY 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\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 == CE_None\n then liftM Just (peek p)\n else return Nothing\n\n\nsetDatasetGeotransform :: RWDataset s -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . 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 a t)\ngetBand b ds =\n liftIO $\n liftM Band $\n checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\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 => RWDataset s -> OptionList -> GDAL s (RWBand s a)\naddBand ds options = 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 = dataType (Proxy :: Proxy a)\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\n\nbandDataType :: Band s a t -> DataType\nbandDataType = toEnumC . {#call pure unsafe GetRasterDataType as ^#} . unBand\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 XY (peek xPtr) (peek yPtr))\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(XY x y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> 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 t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> XY 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\ncheckType\n :: forall s a t. GDALType a => Band s a t -> GDAL s ()\ncheckType b\n | rt == bt = return ()\n | otherwise = throwBindingException (InvalidDataType bt)\n where rt = dataType (Proxy :: Proxy a)\n bt = bandDataType b\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{-# INLINE bandNodataValue #-}\n\n\nsetBandNodataValue :: GDALType a => RWBand s a -> a -> GDAL s ()\nsetBandNodataValue b v =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: RWBand s a -> MaskType -> GDAL s ()\ncreateBandMask band maskType = 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 (Vector (Value a))\nreadBand band win (XY bx by) = readMasked band read_ read_\n where\n XY sx sy = envelopeSize win\n XY xoff yoff = envelopeMin win\n read_ :: forall a'. GDALType a' => Band s a' t -> GDAL s (St.Vector a')\n read_ b = liftIO $ do\n vec <- Stm.new (bx*by)\n let dtype = fromEnumC (dataType (Proxy :: Proxy a'))\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 dtype\n (castPtr 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 dtype\n 0\n 0\n St.unsafeFreeze vec\n{-# INLINE readBand #-}\n\nreadMasked\n :: GDALType a\n => Band s a t\n -> (Band s a t -> GDAL s (St.Vector a))\n -> (Band s Word8 t -> GDAL s (St.Vector Word8))\n -> GDAL s (Vector (Value a))\nreadMasked band reader maskReader =\n bandMaskType band >>= \\case\n MaskNoData ->\n liftM2 mkValueUVector (noDataOrFail band) (reader band)\n MaskAllValid ->\n liftM mkAllValidValueUVector (reader band)\n _ ->\n liftM2 mkMaskedValueUVector (maskReader =<< bandMask band) (reader band)\n{-# INLINE readMasked #-}\n\nwriteMasked\n :: GDALType a\n => RWBand s a\n -> (RWBand s a -> St.Vector a -> GDAL s ())\n -> (RWBand s Word8 -> St.Vector Word8 -> GDAL s ())\n -> Vector (Value a)\n -> GDAL s ()\nwriteMasked band writer maskWriter uvec =\n bandMaskType band >>= \\case\n MaskNoData ->\n noDataOrFail band >>= writer band . flip toStVecWithNodata uvec\n MaskAllValid ->\n maybe (throwBindingException BandDoesNotAllowNoData)\n (writer band)\n (toStVec uvec)\n _ ->\n let (mask, vec) = toStVecWithMask uvec\n in writer band vec >> bandMask band >>= flip maskWriter mask\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 = liftIO . liftM Band . {#call GetMaskBand as ^#} . 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\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz@(XY bx by) = writeMasked band write write\n where\n write :: forall a'. GDALType a' => RWBand s a' -> St.Vector a' -> GDAL s ()\n write band' vec = do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n nElems = bx * by\n XY sx sy = envelopeSize win\n XY xoff yoff = envelopeMin win\n if nElems \/= len\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n withForeignPtr fp $ \\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 (dataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE writeBand #-}\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\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a 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 a 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 -> GDAL s b) -> b -> Band s a 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 -> GDAL s b) -> b -> Band s a t -> GDAL s b\nifoldlM' f initialAcc band = do\n checkType band\n v <- liftIO $ Stm.new (bandBlockLen band)\n vm <- liftIO $ Stm.new (bandBlockLen band)\n let blockLoader i j = void $ unsafeLoadBandBlock v vm band (XY i j)\n bandMaskType band >>= \\case\n MaskAllValid ->\n ifoldlM_loop blockLoader (mkAllValidValueUMVector v)\n MaskNoData -> do\n noData <- noDataOrFail band\n ifoldlM_loop blockLoader (mkValueUMVector noData v)\n _ -> do\n ifoldlM_loop blockLoader (mkMaskedValueUMVector vm v)\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_loop #-}\n ifoldlM_loop loadBlock vec = goB SPEC 0 0 initialAcc\n where\n goB !sPEC !iB !jB !acc\n | iB < nx = do loadBlock iB jB\n go sPEC 0 0 acc >>= goB sPEC (iB+1) jB\n | jB+1 < ny = goB sPEC 0 (jB+1) acc\n | otherwise = return acc\n where\n go !sPEC2 !i !j !acc'\n | i < stopx = applyTo i j acc' >>= go sPEC2 (i+1) j\n | j+1 < stopy = go sPEC2 0 (j+1) acc'\n | otherwise = return acc'\n applyTo i j a = liftIO (unsafeRead vec (j*sx+i)) >>= f a ix\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{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec = do\n checkType band\n when (bandBlockLen band \/= len) $\n throwBindingException (InvalidBlockSize len)\n writeMasked band write writeMask uvec\n where\n len = G.length uvec\n bi = fmap fromIntegral blockIx\n\n write band' vec =\n liftIO $\n checkCPLError \"WriteBlock\" $\n St.unsafeWith vec $ \\pVec ->\n {#call WriteBlock as ^#} (unBand band') (px bi) (py bi) (castPtr pVec)\n\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n off = bi * bs\n win = liftA2 min bs (rs - off)\n lineSpace = px bs * fromIntegral (sizeOf (undefined :: Word8))\n\n writeMask band' vec =\n liftIO $\n checkCPLError \"WriteBlock\" $\n St.unsafeWith vec $ \\pVec ->\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (px off)\n (py off)\n (px win)\n (py win)\n (castPtr pVec)\n (px win)\n (py win)\n (fromEnumC GDT_Byte)\n 0\n (fromIntegral lineSpace)\n{-# INLINE writeBandBlock #-}\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (Vector (Value a))\nreadBandBlock band blockIx = do\n checkType band\n let len = bandBlockLen band\n buf <- liftIO $ Stm.new len\n maskBuf <- liftIO $ Stm.replicate len 0\n unsafeLoadBandBlock buf maskBuf band blockIx\n{-# INLINE readBandBlock #-}\n\nunsafeLoadBandBlock\n :: forall s t a. GDALType a\n => Stm.IOVector a\n -> Stm.IOVector Word8\n -> Band s a t\n -> BlockIx\n -> GDAL s (Vector (Value a))\nunsafeLoadBandBlock buf maskBuf band blockIx =\n readMasked band reader maskReader\n where\n bi = fmap fromIntegral blockIx\n\n reader band' = liftIO $ do\n Stm.unsafeWith buf $ \\pVec ->\n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#} (unBand band') (px bi) (py bi) (castPtr pVec)\n St.unsafeFreeze buf\n\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n off = bi * bs\n win = liftA2 min bs (rs - off)\n lineSpace = px bs * fromIntegral (sizeOf (undefined :: Word8))\n\n maskReader band' = liftIO $ do\n Stm.unsafeWith maskBuf $ \\pVec ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Read)\n (px off)\n (py off)\n (px win)\n (py win)\n (castPtr pVec)\n (px win)\n (py win)\n (fromEnumC GDT_Byte)\n 0\n (fromIntegral lineSpace)\n St.unsafeFreeze maskBuf\n{-# INLINE unsafeLoadBandBlock #-}\n\n\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\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\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand v band =\n mapM_ (flip (writeBandBlock band) vec) [XY i j | j<-[0..ny-1], i<-[0..nx-1]]\n where\n XY nx ny = bandBlockCount band\n vec = G.replicate (bandBlockLen band) v\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\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 , bandTypedAs\n , bandCoercedTo\n {-\n , reifyBandDataType\n , reifyDataType\n -}\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\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 , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\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.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>))\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 Data.Maybe (fromMaybe)\nimport Data.Proxy (Proxy(..))\nimport Data.String (IsString)\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport Data.Vector.Unboxed.Mutable (unsafeRead)\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr)\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.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 | InvalidDataType !DataType\n | InvalidDriverOptions\n | UnknownRasterDataType\n | UnsupportedRasterDataType !DataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\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 (t::AccessMode) =\n Dataset (ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s t -> m ()\ncloseDataset (Dataset (rk,_)) = release rk\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) =\n Band { unBand :: RasterBandH }\n\nbandTypedAs :: Band s a t -> a -> Band s a t\nbandTypedAs = const . id\n\nbandCoercedTo :: Band s a t -> b -> Band s b t\nbandCoercedTo = const . coerce\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\n{-\nreifyBandDataType\n :: Band s t -> (forall a. GDALType a => Proxy a -> b) -> b\nreifyBandDataType b = reifyDataType (bandDataType b)\n-}\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 -> OptionList\n -> GDAL s (Dataset s ReadWrite)\ncreate _ _ _ _ GDT_Unknown _ =\n throwBindingException UnknownRasterDataType\ncreate drv path (XY 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 -> 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 :: GDALAccess -> String -> GDAL s (Dataset s t)\nopenWithMode m path =\n newDatasetHandle $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\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 =\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 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 -> OptionList -> GDAL s (Dataset s ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: forall s. RWDataset s -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s 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 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\ndatasetFileList :: Dataset s t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjection :: Dataset s t -> GDAL s (Maybe SpatialReference)\ndatasetProjection =\n liftIO . ({#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString)\n\n\nsetDatasetProjection :: RWDataset s -> SpatialReference -> GDAL s ()\nsetDatasetProjection ds srs =\n liftIO $ checkCPLError \"SetProjection\" $\n unsafeUseAsCString (srsToWkt srs)\n ({#call unsafe SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: RWDataset s -> [GroundControlPoint] -> Maybe SpatialReference -> GDAL s ()\nsetDatasetGCPs ds gcps mSrs =\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 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 -> 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 = px (envelopeMin envelope)\n , gtXDelta = px (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = py (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (py (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 -> XY Double -> XY Double\napplyGeotransform Geotransform{..} (XY x y) =\n XY (gtXOff + gtXDelta*x + gtXRot * y)\n (gtYOff + gtYRot *x + gtYDelta * y)\n{-# INLINE applyGeotransform #-}\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> XY Double -> XY 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\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 == CE_None\n then liftM Just (peek p)\n else return Nothing\n\n\nsetDatasetGeotransform :: RWDataset s -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . 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 a t)\ngetBand b ds =\n liftIO $\n liftM Band $\n checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\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 => RWDataset s -> OptionList -> GDAL s (RWBand s a)\naddBand ds options = 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 = dataType (Proxy :: Proxy a)\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\n\nbandDataType :: Band s a t -> DataType\nbandDataType = toEnumC . {#call pure unsafe GetRasterDataType as ^#} . unBand\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 XY (peek xPtr) (peek yPtr))\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(XY x y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> 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 t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> XY 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\ncheckType\n :: forall s a t. GDALType a => Band s a t -> GDAL s ()\ncheckType b\n | rt == bt = return ()\n | otherwise = throwBindingException (InvalidDataType bt)\n where rt = dataType (Proxy :: Proxy a)\n bt = bandDataType b\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{-# INLINE bandNodataValue #-}\n\n\nsetBandNodataValue :: GDALType a => RWBand s a -> a -> GDAL s ()\nsetBandNodataValue b v =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: RWBand s a -> MaskType -> GDAL s ()\ncreateBandMask band maskType = 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 (Vector (Value a))\nreadBand band win (XY bx by) = readMasked band read_ read_\n where\n XY sx sy = envelopeSize win\n XY xoff yoff = envelopeMin win\n read_ :: forall a'. GDALType a' => Band s a' t -> GDAL s (St.Vector a')\n read_ b = liftIO $ do\n vec <- Stm.new (bx*by)\n let dtype = fromEnumC (dataType (Proxy :: Proxy a'))\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 dtype\n (castPtr 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 dtype\n 0\n 0\n St.unsafeFreeze vec\n{-# INLINE readBand #-}\n\nreadMasked\n :: GDALType a\n => Band s a t\n -> (Band s a t -> GDAL s (St.Vector a))\n -> (Band s Word8 t -> GDAL s (St.Vector Word8))\n -> GDAL s (Vector (Value a))\nreadMasked band reader maskReader =\n bandMaskType band >>= \\case\n MaskNoData ->\n liftM2 mkValueUVector (noDataOrFail band) (reader band)\n MaskAllValid ->\n liftM mkAllValidValueUVector (reader band)\n _ ->\n liftM2 mkMaskedValueUVector (maskReader =<< bandMask band) (reader band)\n{-# INLINE readMasked #-}\n\nwriteMasked\n :: GDALType a\n => RWBand s a\n -> (RWBand s a -> St.Vector a -> GDAL s ())\n -> (RWBand s Word8 -> St.Vector Word8 -> GDAL s ())\n -> Vector (Value a)\n -> GDAL s ()\nwriteMasked band writer maskWriter uvec =\n bandMaskType band >>= \\case\n MaskNoData ->\n noDataOrFail band >>= writer band . flip toStVecWithNodata uvec\n MaskAllValid ->\n maybe (throwBindingException BandDoesNotAllowNoData)\n (writer band)\n (toStVec uvec)\n _ ->\n let (mask, vec) = toStVecWithMask uvec\n in writer band vec >> bandMask band >>= flip maskWriter mask\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 = liftIO . liftM Band . {#call GetMaskBand as ^#} . 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\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz@(XY bx by) = writeMasked band write write\n where\n write :: forall a'. GDALType a' => RWBand s a' -> St.Vector a' -> GDAL s ()\n write band' vec = do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n nElems = bx * by\n XY sx sy = envelopeSize win\n XY xoff yoff = envelopeMin win\n if nElems \/= len\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n withForeignPtr fp $ \\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 (dataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE writeBand #-}\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\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a 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 a 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 -> GDAL s b) -> b -> Band s a 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 -> GDAL s b) -> b -> Band s a t -> GDAL s b\nifoldlM' f initialAcc band = do\n v <- liftIO $ Stm.new (bandBlockLen band)\n vm <- liftIO $ Stm.new (bandBlockLen band)\n let blockLoader i j = unsafeLoadBandBlock v vm band (XY i j)\n ifoldlM_loop blockLoader\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_loop #-}\n ifoldlM_loop loadBlock = goB SPEC 0 0 initialAcc\n where\n goB !sPEC !iB !jB !acc\n | iB < nx = do vec <- loadBlock iB jB\n go sPEC vec 0 0 acc >>= goB sPEC (iB+1) jB\n | jB+1 < ny = goB sPEC 0 (jB+1) acc\n | otherwise = return acc\n where\n go !sPEC2 vec !i !j !acc'\n | i < stopx = do\n let ix = XY (iB*sx+i) (jB*sy+j)\n v <- vec `G.unsafeIndexM` (j*sx+i)\n f acc' ix v >>= go sPEC2 vec (i+1) j\n | j+1 < stopy = go sPEC2 vec 0 (j+1) acc'\n | otherwise = return 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 ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec = do\n checkType band\n when (bandBlockLen band \/= len) $\n throwBindingException (InvalidBlockSize len)\n writeMasked band write writeMask uvec\n where\n len = G.length uvec\n bi = fmap fromIntegral blockIx\n\n write band' vec =\n liftIO $\n checkCPLError \"WriteBlock\" $\n St.unsafeWith vec $ \\pVec ->\n {#call WriteBlock as ^#} (unBand band') (px bi) (py bi) (castPtr pVec)\n\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n off = bi * bs\n win = liftA2 min bs (rs - off)\n lineSpace = px bs * fromIntegral (sizeOf (undefined :: Word8))\n\n writeMask band' vec =\n liftIO $\n checkCPLError \"WriteBlock\" $\n St.unsafeWith vec $ \\pVec ->\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (px off)\n (py off)\n (px win)\n (py win)\n (castPtr pVec)\n (px win)\n (py win)\n (fromEnumC GDT_Byte)\n 0\n (fromIntegral lineSpace)\n{-# INLINE writeBandBlock #-}\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (Vector (Value a))\nreadBandBlock band blockIx = do\n checkType band\n let len = bandBlockLen band\n buf <- liftIO $ Stm.new len\n maskBuf <- liftIO $ Stm.replicate len 0\n unsafeLoadBandBlock buf maskBuf band blockIx\n{-# INLINE readBandBlock #-}\n\nunsafeLoadBandBlock\n :: forall s t a. GDALType a\n => Stm.IOVector a\n -> Stm.IOVector Word8\n -> Band s a t\n -> BlockIx\n -> GDAL s (Vector (Value a))\nunsafeLoadBandBlock buf maskBuf band blockIx =\n readMasked band reader maskReader\n where\n bi = fmap fromIntegral blockIx\n\n reader band' = liftIO $ do\n Stm.unsafeWith buf $ \\pVec ->\n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#} (unBand band') (px bi) (py bi) (castPtr pVec)\n St.unsafeFreeze buf\n\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n off = bi * bs\n win = liftA2 min bs (rs - off)\n lineSpace = px bs * fromIntegral (sizeOf (undefined :: Word8))\n\n maskReader band' = liftIO $ do\n Stm.unsafeWith maskBuf $ \\pVec ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Read)\n (px off)\n (py off)\n (px win)\n (py win)\n (castPtr pVec)\n (px win)\n (py win)\n (fromEnumC GDT_Byte)\n 0\n (fromIntegral lineSpace)\n St.unsafeFreeze maskBuf\n{-# INLINE unsafeLoadBandBlock #-}\n\n\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\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\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand v band =\n mapM_ (flip (writeBandBlock band) vec) [XY i j | j<-[0..ny-1], i<-[0..nx-1]]\n where\n XY nx ny = bandBlockCount band\n vec = G.replicate (bandBlockLen band) v\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1a04740190dc984fb935af0e023d6816c2982af9","subject":"[project @ 2004-12-18 20:45:50 by duncan_coutts] tidy up module header","message":"[project @ 2004-12-18 20:45:50 by duncan_coutts]\ntidy up module header\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte","old_file":"mozembed\/Graphics\/UI\/Gtk\/MozEmbed.chs","new_file":"mozembed\/Graphics\/UI\/Gtk\/MozEmbed.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget embedding the Mozilla browser engine (Gecko)\n--\n-- Author : Jonas Svensson\n--\n-- Created: 26 February 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2004\/12\/18 20:45:50 $\n--\n-- Copyright (c) 2002 Jonas Svensson\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-- Modified 2004 by Scott West for basic use in gtk2hs\n--\n-- Further modified 2004 by Wolfram Kahl:\n-- * ported to gtk2hs\/c2hs\n-- * added additional interface functions\n-- * circumvented render_data problem\n--\n-- | This widgets embeds Mozilla's browser engine (Gecko) into a GTK+ widget.\n-- See for an API reference.\n--\nmodule Graphics.UI.Gtk.MozEmbed (\n MozEmbed, MozEmbedClass,\n\n mozEmbedNew, mozEmbedSetCompPath,\n\n mozEmbedRenderData,\n mozEmbedOpenStream, mozEmbedAppendData, mozEmbedCloseStream,\n\n onOpenURI,\n\n mozEmbedLoadUrl,\n\n -- the functions below are untested.\n\n onKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut,\n\n mozEmbedSetProfilePath,\n mozEmbedStopLoad, mozEmbedGoBack, mozEmbedGoForward, mozEmbedGetLinkMessage,\n mozEmbedGetJsStatus, mozEmbedGetTitle, mozEmbedGetLocation,\n mozEmbedCanGoBack, mozEmbedCanGoForward, mozEmbedPushStartup,\n mozEmbedPopStartup\n) where\n\nimport Monad\t\t(liftM)\nimport FFI\nimport ForeignPtr\nimport Foreign.Marshal.Utils (toBool)\n\n{#import Object#} (makeNewObject)\n{#import Signal#} (ConnectId, connect_STRING__BOOL, connect_PTR__INT)\n{#import Graphics.UI.Gtk.MozEmbedType #}\nimport Widget (Widget)\n\n{#context lib=\"gtkembedmoz\" prefix =\"gtk\"#}\n\n-- operations\n-- ----------\n\n-- | Create a new MozEmbed\n--\nmozEmbedNew :: IO MozEmbed\nmozEmbedNew = makeNewObject mkMozEmbed $ liftM castPtr {#call moz_embed_new#}\n\nmozEmbedSetCompPath :: String -> IO ()\nmozEmbedSetCompPath str =\n withCString str $ \\strPtr ->\n {#call moz_embed_set_comp_path#}\n strPtr\n\nmozEmbedSetProfilePath :: String -> String -> IO ()\nmozEmbedSetProfilePath dir name =\n withCString dir $ \\dirPtr ->\n withCString name $ \\namePtr ->\n {#call moz_embed_set_profile_path#} dirPtr namePtr\n \nmozEmbedLoadUrl :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedLoadUrl m url =\n withCString url $ \\urlPtr ->\n {#call moz_embed_load_url#}\n (toMozEmbed m)\n urlPtr\n\nmozEmbedStopLoad :: MozEmbedClass m => m -> IO ()\nmozEmbedStopLoad m = \n {#call moz_embed_stop_load#} (toMozEmbed m)\n\nmozEmbedGoBack :: MozEmbedClass m => m -> IO ()\nmozEmbedGoBack m =\n {#call moz_embed_go_back#} (toMozEmbed m)\n\nmozEmbedGoForward :: MozEmbedClass m => m -> IO ()\nmozEmbedGoForward m =\n {#call moz_embed_go_forward#} (toMozEmbed m)\n\nmozEmbedGetLinkMessage :: MozEmbedClass m => m -> IO String\nmozEmbedGetLinkMessage m = \n do\n str <- {#call moz_embed_get_link_message#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetJsStatus :: MozEmbedClass m => m -> IO String\nmozEmbedGetJsStatus m =\n do\n str <- {#call moz_embed_get_js_status#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetTitle :: MozEmbedClass m => m -> IO String\nmozEmbedGetTitle m = \n do\n str <- {#call moz_embed_get_title#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetLocation :: MozEmbedClass m => m -> IO String\nmozEmbedGetLocation m = \n do\n str <- {#call moz_embed_get_location#} (toMozEmbed m)\n peekCString str\n\nmozEmbedCanGoBack :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoBack m =\n liftM toBool $ \n {#call moz_embed_can_go_back#} (toMozEmbed m)\n\nmozEmbedCanGoForward :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoForward m =\n liftM toBool $ \n {#call moz_embed_can_go_forward#} (toMozEmbed m)\n\nmozEmbedPushStartup :: IO ()\nmozEmbedPushStartup =\n {#call moz_embed_push_startup#}\n\nmozEmbedPopStartup :: IO ()\nmozEmbedPopStartup =\n {#call moz_embed_pop_startup#}\n\n{-\nvoid gtk_moz_embed_open_stream (GtkMozEmbed *embed,\n\t\t\t\t\t const char *base_uri,\n\t\t\t\t\t const char *mime_type);\nvoid gtk_moz_embed_append_data (GtkMozEmbed *embed,\n\t\t\t\t\t const char *data, guint32 len);\nvoid gtk_moz_embed_close_stream (GtkMozEmbed *embed);\n-}\n\nmozEmbedOpenStream :: MozEmbedClass m => m -> String -> String -> IO ()\nmozEmbedOpenStream m baseURI mimeType =\n withCString baseURI $ \\ basePtr ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_open_stream#} (toMozEmbed m) basePtr mtPtr\n\nmozEmbedAppendDataInternal :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendDataInternal m contents =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged?\n let len' = fromIntegral len in\n {#call gtk_moz_embed_append_data#} (toMozEmbed m) dataPtr len'\n-- >> free dataPtr\n\nmozEmbedCloseStream :: MozEmbedClass m => m -> IO ()\nmozEmbedCloseStream m =\n {#call gtk_moz_embed_close_stream#} (toMozEmbed m)\n\nmozEmbedAppendData :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendData m contents =\n mapM_ (mozEmbedAppendDataInternal m) (chunks 32768 contents)\n\nmozEmbedRenderData :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderData m contents baseURI mimeType = do\n mozEmbedOpenStream m baseURI mimeType\n mozEmbedAppendData m contents\n mozEmbedCloseStream m\n\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = let (ys, zs) = splitAt n xs in ys : chunks n zs\n\n{-\nvoid gtk_moz_embed_render_data (GtkMozEmbed *embed, \n const char *data,\n guint32 len,\n const char *base_uri, \n const char *mime_type)\n-}\n-- -- mozEmbedRenderDataInternal does not work for len' > 2^16\nmozEmbedRenderDataInternal :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderDataInternal m contents baseURI mimeType =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged\n let len' = fromIntegral len in\n-- hPutStrLn stderr (\"mozEmbedRenderData: \" ++ shows len' \" bytes\") >>= \\ _ ->\n withCString baseURI $ \\ basePrt ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_render_data#} (toMozEmbed m) dataPtr len' basePrt mtPtr\n-- >> free dataPtr\n\n{-\nstruct _GtkMozEmbedClass\n{\n [...]\n gint (* open_uri) (GtkMozEmbed *embed, const char *aURI);\n [...]\n}\n-}\n\nonOpenURI :: MozEmbedClass m => m -> (String -> IO Bool) -> IO (ConnectId m)\nonOpenURI = connect_STRING__BOOL \"open_uri\" after\n where\n-- Specify if the handler is to run before (False) or after (True) the\n-- default handler.\n after = False\n\n\n{-\nMore signals to investigate:\n\n gint (* dom_key_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_press) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_dbl_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_over) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_out) (GtkMozEmbed *embed, gpointer dom_event);\n\nUnfortunateley these are not documented on\n\nhttp:\/\/www.mozilla.org\/unix\/gtk-embedding.html\n\n-}\n\nonKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut\n :: (Num n, Integral n, MozEmbedClass m)\n => m -> (Ptr a -> IO n) -> IO (ConnectId m)\nonKeyDown = connect_PTR__INT \"dom_key_down\" False\nonKeyPress = connect_PTR__INT \"dom_key_press\" False\nonKeyUp = connect_PTR__INT \"dom_key_up\" False\nonMouseDown = connect_PTR__INT \"dom_mouse_down\" False\nonMouseUp = connect_PTR__INT \"dom_mouse_up\" False\nonMouseClick = connect_PTR__INT \"dom_mouse_click\" False\nonMouseDoubleClick = connect_PTR__INT \"dom_mouse_dbl_click\" False\nonMouseOver = connect_PTR__INT \"dom_mouse_over\" False\nonMouseOut = connect_PTR__INT \"dom_mouse_out\" False\n\n","old_contents":"-- |GIMP Toolkit (GTK) Binding for Haskell: widget embedding the -*-haskell-*-\n-- Mozilla browser engine (Gecko)\n--\n-- Author : Jonas Svensson\n-- Created: 26 February 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2004\/12\/17 21:21:44 $\n--\n-- Copyright (c) 2002 Jonas Svensson\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--\n-- Modified 2004 by Scott West for basic use in gtk2hs\n--\n-- Further modified 2004 by Wolfram Kahl:\n-- * ported to gtk2hs\/c2hs\n-- * added additional interface functions\n-- * circumvented render_data problem\n--\n--\n--- DESCRIPTION ---------------------------------------------------------------\n--\n-- This widgets embeds Mozilla's browser engine (Gecko) into a GTK+ widget.\n--\n--- DOCU ----------------------------------------------------------------------\n--\n-- Language: Haskell 98 Binding Module\n--\n--- TODO ----------------------------------------------------------------------\n--\n\nmodule Graphics.UI.Gtk.MozEmbed (\n MozEmbed, MozEmbedClass,\n\n mozEmbedNew, mozEmbedSetCompPath,\n\n mozEmbedRenderData,\n mozEmbedOpenStream, mozEmbedAppendData, mozEmbedCloseStream,\n\n onOpenURI,\n\n mozEmbedLoadUrl,\n\n -- the functions below are untested.\n\n onKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut,\n\n mozEmbedSetProfilePath,\n mozEmbedStopLoad, mozEmbedGoBack, mozEmbedGoForward, mozEmbedGetLinkMessage,\n mozEmbedGetJsStatus, mozEmbedGetTitle, mozEmbedGetLocation,\n mozEmbedCanGoBack, mozEmbedCanGoForward, mozEmbedPushStartup,\n mozEmbedPopStartup\n) where\n\nimport Monad\t\t(liftM)\nimport FFI\nimport ForeignPtr\nimport Foreign.Marshal.Utils (toBool)\n\n{#import Object#} (makeNewObject)\n{#import Signal#} (ConnectId, connect_STRING__BOOL, connect_PTR__INT)\n{#import Graphics.UI.Gtk.MozEmbedType #}\nimport Widget (Widget)\n\n{#context lib=\"gtkembedmoz\" prefix =\"gtk\"#}\n\n-- operations\n-- ----------\n\n-- | Create a new MozEmbed\n--\nmozEmbedNew :: IO MozEmbed\nmozEmbedNew = makeNewObject mkMozEmbed $ liftM castPtr {#call moz_embed_new#}\n\nmozEmbedSetCompPath :: String -> IO ()\nmozEmbedSetCompPath str =\n withCString str $ \\strPtr ->\n {#call moz_embed_set_comp_path#}\n strPtr\n\nmozEmbedSetProfilePath :: String -> String -> IO ()\nmozEmbedSetProfilePath dir name =\n withCString dir $ \\dirPtr ->\n withCString name $ \\namePtr ->\n {#call moz_embed_set_profile_path#} dirPtr namePtr\n \nmozEmbedLoadUrl :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedLoadUrl m url =\n withCString url $ \\urlPtr ->\n {#call moz_embed_load_url#}\n (toMozEmbed m)\n urlPtr\n\nmozEmbedStopLoad :: MozEmbedClass m => m -> IO ()\nmozEmbedStopLoad m = \n {#call moz_embed_stop_load#} (toMozEmbed m)\n\nmozEmbedGoBack :: MozEmbedClass m => m -> IO ()\nmozEmbedGoBack m =\n {#call moz_embed_go_back#} (toMozEmbed m)\n\nmozEmbedGoForward :: MozEmbedClass m => m -> IO ()\nmozEmbedGoForward m =\n {#call moz_embed_go_forward#} (toMozEmbed m)\n\nmozEmbedGetLinkMessage :: MozEmbedClass m => m -> IO String\nmozEmbedGetLinkMessage m = \n do\n str <- {#call moz_embed_get_link_message#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetJsStatus :: MozEmbedClass m => m -> IO String\nmozEmbedGetJsStatus m =\n do\n str <- {#call moz_embed_get_js_status#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetTitle :: MozEmbedClass m => m -> IO String\nmozEmbedGetTitle m = \n do\n str <- {#call moz_embed_get_title#} (toMozEmbed m)\n peekCString str\n\nmozEmbedGetLocation :: MozEmbedClass m => m -> IO String\nmozEmbedGetLocation m = \n do\n str <- {#call moz_embed_get_location#} (toMozEmbed m)\n peekCString str\n\nmozEmbedCanGoBack :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoBack m =\n liftM toBool $ \n {#call moz_embed_can_go_back#} (toMozEmbed m)\n\nmozEmbedCanGoForward :: MozEmbedClass m => m -> IO Bool\nmozEmbedCanGoForward m =\n liftM toBool $ \n {#call moz_embed_can_go_forward#} (toMozEmbed m)\n\nmozEmbedPushStartup :: IO ()\nmozEmbedPushStartup =\n {#call moz_embed_push_startup#}\n\nmozEmbedPopStartup :: IO ()\nmozEmbedPopStartup =\n {#call moz_embed_pop_startup#}\n\n{-\nvoid gtk_moz_embed_open_stream (GtkMozEmbed *embed,\n\t\t\t\t\t const char *base_uri,\n\t\t\t\t\t const char *mime_type);\nvoid gtk_moz_embed_append_data (GtkMozEmbed *embed,\n\t\t\t\t\t const char *data, guint32 len);\nvoid gtk_moz_embed_close_stream (GtkMozEmbed *embed);\n-}\n\nmozEmbedOpenStream :: MozEmbedClass m => m -> String -> String -> IO ()\nmozEmbedOpenStream m baseURI mimeType =\n withCString baseURI $ \\ basePtr ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_open_stream#} (toMozEmbed m) basePtr mtPtr\n\nmozEmbedAppendDataInternal :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendDataInternal m contents =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged?\n let len' = fromIntegral len in\n {#call gtk_moz_embed_append_data#} (toMozEmbed m) dataPtr len'\n-- >> free dataPtr\n\nmozEmbedCloseStream :: MozEmbedClass m => m -> IO ()\nmozEmbedCloseStream m =\n {#call gtk_moz_embed_close_stream#} (toMozEmbed m)\n\nmozEmbedAppendData :: MozEmbedClass m => m -> String -> IO ()\nmozEmbedAppendData m contents =\n mapM_ (mozEmbedAppendDataInternal m) (chunks 32768 contents)\n\nmozEmbedRenderData :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderData m contents baseURI mimeType = do\n mozEmbedOpenStream m baseURI mimeType\n mozEmbedAppendData m contents\n mozEmbedCloseStream m\n\n\nchunks :: Int -> [a] -> [[a]]\nchunks n [] = []\nchunks n xs = let (ys, zs) = splitAt n xs in ys : chunks n zs\n\n{-\nvoid gtk_moz_embed_render_data (GtkMozEmbed *embed, \n const char *data,\n guint32 len,\n const char *base_uri, \n const char *mime_type)\n-}\n-- -- mozEmbedRenderDataInternal does not work for len' > 2^16\nmozEmbedRenderDataInternal :: MozEmbedClass m => m -> String -> String -> String -> IO ()\nmozEmbedRenderDataInternal m contents baseURI mimeType =\n-- newCStringLen (toUTF contents) >>= \\ (dataPtr,len) ->\n withUTFStringLen contents $ \\ (dataPtr,len) -> -- alloca discouraged\n let len' = fromIntegral len in\n-- hPutStrLn stderr (\"mozEmbedRenderData: \" ++ shows len' \" bytes\") >>= \\ _ ->\n withCString baseURI $ \\ basePrt ->\n withCString mimeType $ \\ mtPtr ->\n {#call gtk_moz_embed_render_data#} (toMozEmbed m) dataPtr len' basePrt mtPtr\n-- >> free dataPtr\n\n{-\nstruct _GtkMozEmbedClass\n{\n [...]\n gint (* open_uri) (GtkMozEmbed *embed, const char *aURI);\n [...]\n}\n-}\n\nonOpenURI :: MozEmbedClass m => m -> (String -> IO Bool) -> IO (ConnectId m)\nonOpenURI = connect_STRING__BOOL \"open_uri\" after\n where\n-- Specify if the handler is to run before (False) or after (True) the\n-- default handler.\n after = False\n\n\n{-\nMore signals to investigate:\n\n gint (* dom_key_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_press) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_key_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_down) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_up) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_dbl_click) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_over) (GtkMozEmbed *embed, gpointer dom_event);\n gint (* dom_mouse_out) (GtkMozEmbed *embed, gpointer dom_event);\n\nUnfortunateley these are not documented on\n\nhttp:\/\/www.mozilla.org\/unix\/gtk-embedding.html\n\n-}\n\nonKeyDown, onKeyPress, onKeyUp,\n onMouseDown, onMouseUp, onMouseClick, onMouseDoubleClick,\n onMouseOver, onMouseOut\n :: (Num n, Integral n, MozEmbedClass m)\n => m -> (Ptr a -> IO n) -> IO (ConnectId m)\nonKeyDown = connect_PTR__INT \"dom_key_down\" False\nonKeyPress = connect_PTR__INT \"dom_key_press\" False\nonKeyUp = connect_PTR__INT \"dom_key_up\" False\nonMouseDown = connect_PTR__INT \"dom_mouse_down\" False\nonMouseUp = connect_PTR__INT \"dom_mouse_up\" False\nonMouseClick = connect_PTR__INT \"dom_mouse_click\" False\nonMouseDoubleClick = connect_PTR__INT \"dom_mouse_dbl_click\" False\nonMouseOver = connect_PTR__INT \"dom_mouse_over\" False\nonMouseOut = connect_PTR__INT \"dom_mouse_out\" False\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"8bb6d8882f215b3e2c2252bb7f8fc5cdabb15d26","subject":"gstreamer: M.S.G.Core.Caps: document everything; code cleanups, remove capsMerge and capsAppend; add capsCopyNth","message":"gstreamer: M.S.G.Core.Caps: document everything; code cleanups, remove capsMerge and capsAppend; add capsCopyNth\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/vte","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-- | 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","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.Caps (\n \n Caps,\n capsNone,\n capsAny,\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 CapsM,\n capsCreate,\n capsModify,\n capsAppend,\n capsMerge,\n capsAppendStructure,\n capsMergeStructure,\n capsRemoveStructure,\n capsTruncate\n \n ) where\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import Media.Streaming.GStreamer.Core.Types#}\n\ncapsNone :: Caps\ncapsNone =\n unsafePerformIO $ {# call caps_new_empty #} >>= takeCaps\n\ncapsAny :: Caps\ncapsAny =\n unsafePerformIO $ {# call caps_new_any #} >>= takeCaps\n\ncapsSize :: Caps\n -> Word\ncapsSize caps =\n fromIntegral $ unsafePerformIO $ {# call caps_get_size #} caps\n\ncapsGetStructure :: Caps\n -> Word\n -> Maybe Structure\ncapsGetStructure caps index =\n unsafePerformIO $\n {# call caps_get_structure #} caps (fromIntegral index) >>=\n maybePeek peekStructure\n\ncapsIsEmpty :: Caps\n -> Bool\ncapsIsEmpty caps =\n toBool $ unsafePerformIO $\n {# call caps_is_empty #} caps\n\ncapsIsFixed :: Caps\n -> Bool\ncapsIsFixed caps =\n toBool $ unsafePerformIO $\n {# call caps_is_fixed #} caps\n\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\ncapsIsEqualFixed :: Caps\n -> Caps\n -> Bool\ncapsIsEqualFixed caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_equal_fixed #} caps1 caps2\n\ncapsIsAlwaysCompatible :: Caps\n -> Caps\n -> Bool\ncapsIsAlwaysCompatible caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_always_compatible #} caps1 caps2\n\ncapsIsSubset :: Caps\n -> Caps\n -> Bool\ncapsIsSubset caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_subset #} caps1 caps2\n\ncapsIntersect :: Caps\n -> Caps\n -> Caps\ncapsIntersect caps1 caps2 =\n unsafePerformIO $\n {# call caps_intersect #} caps1 caps2 >>=\n takeCaps\n\ncapsUnion :: Caps\n -> Caps\n -> Caps\ncapsUnion caps1 caps2 =\n unsafePerformIO $\n {# call caps_union #} caps1 caps2 >>=\n takeCaps\n\ncapsSubtract :: Caps\n -> Caps\n -> Caps\ncapsSubtract caps1 caps2 =\n unsafePerformIO $\n {# call caps_subtract #} caps1 caps2 >>=\n takeCaps\n\ncapsNormalize :: Caps\n -> Caps\ncapsNormalize caps =\n unsafePerformIO $\n {# call caps_normalize #} caps >>= takeCaps\n\ncapsToString :: Caps\n -> String\ncapsToString caps =\n unsafePerformIO $\n {# call caps_to_string #} caps >>= readUTFString\n\ncapsFromString :: String\n -> Caps\ncapsFromString string =\n unsafePerformIO $\n withUTFString string {# call caps_from_string #} >>=\n takeCaps\n\nnewtype CapsM a = CapsM (CapsMRep a)\ntype CapsMRep a = (Caps -> IO a)\n\ninstance Monad CapsM where\n (CapsM aM) >>= fbM =\n CapsM $ \\caps ->\n do a <- aM caps\n let CapsM bM = fbM a\n bM caps\n return a = CapsM $ const $ return a\n\nmarshalCapsModify :: IO (Ptr Caps)\n -> CapsM a\n -> (Caps, a)\nmarshalCapsModify mkCaps (CapsM action) =\n unsafePerformIO $\n do ptr <- mkCaps\n caps <- liftM Caps $ newForeignPtr_ ptr\n result <- action caps\n caps' <- takeCaps ptr\n return (caps', result)\n\ncapsCreate :: CapsM a\n -> (Caps, a)\ncapsCreate action =\n marshalCapsModify\n {# call caps_new_empty #}\n action\n\ncapsModify :: Caps\n -> CapsM a\n -> (Caps, a)\ncapsModify caps action =\n marshalCapsModify\n ({# call caps_copy #} caps)\n action\n\ncapsAppend :: Caps\n -> CapsM ()\ncapsAppend caps2 =\n CapsM $ \\caps1 ->\n {# call caps_copy #} caps2 >>= takeCaps >>=\n {# call caps_append #} caps1\n\ncapsMerge :: Caps\n -> CapsM ()\ncapsMerge caps2 =\n CapsM $ \\caps1 ->\n {# call caps_copy #} caps2 >>= takeCaps >>=\n {# call caps_merge #} caps1\n\ncapsAppendStructure :: Structure\n -> CapsM ()\ncapsAppendStructure structure =\n CapsM $ \\caps ->\n giveStructure structure $\n {# call caps_append_structure #} caps\n\ncapsMergeStructure :: Structure\n -> CapsM ()\ncapsMergeStructure structure =\n CapsM $ \\caps ->\n giveStructure structure $\n {# call caps_merge_structure #} caps\n\ncapsRemoveStructure :: Word\n -> CapsM ()\ncapsRemoveStructure idx =\n CapsM $ \\caps ->\n {# call caps_remove_structure #} caps $ fromIntegral idx\n\ncapsTruncate :: CapsM ()\ncapsTruncate =\n CapsM {# call caps_truncate #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9fa6ee0cb7979df70b666419cd2b8982d665e522","subject":"return Maybe Int from bandBestOverviewLevel","message":"return Maybe Int from bandBestOverviewLevel\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 , 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\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 , unsafeToReadOnly\n , createCopy\n , createOverviewDataset\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetDriverName\n , datasetSize\n , datasetFileList\n , datasetProjection\n , setDatasetProjection\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{#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 (liftM, liftM2, when, (>=>), (<=<), forever)\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.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)\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#include \"overviews.h\"\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\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\ndriverCreationOptionList :: DriverName -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverHByName 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 :: 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\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\ncreateOverviewDataset\n :: Dataset s a t -> Int -> Bool -> GDAL s (Dataset s a t)\ncreateOverviewDataset ds ovLevel thisLevelOnly = newDatasetHandle $\n {#call hs_gdal_create_overview_dataset#}\n (unDataset ds) (fromIntegral ovLevel) (fromEnumC thisLevelOnly)\n\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\ndatasetDriverName :: Dataset s a t -> DriverName\ndatasetDriverName ds = unsafePerformIO $\n DriverName <$> (packCString =<< {#call unsafe GetDriverShortName as ^#} d)\n where Driver d = datasetDriver 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 :: MonadIO m => Dataset s a t -> m (Maybe SpatialReference)\ndatasetProjection\n = liftIO\n . (maybeSpatialReferenceFromCString <=< {#call unsafe GetProjectionRef as ^#})\n . unDataset\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 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 <- 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\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 <$> 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:: 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 liftM 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 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 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 liftM (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 . 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\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{-# INLINEABLE 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\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{-# INLINEABLE 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\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 :: 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 = 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 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 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 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{-# INLINEABLE fmapBand #-}\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 <- liftM (L.foldl' (G.zipWith fun) acc)\n (lift (mapM (flip readBandBlock bix) bs))\n yield (bix, r)\n{-# INLINEABLE foldBands #-}\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{-# 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 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{-# 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\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 >=> 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 :: (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\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 , 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\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 , unsafeToReadOnly\n , createCopy\n , createOverviewDataset\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetDriverName\n , datasetSize\n , datasetFileList\n , datasetProjection\n , setDatasetProjection\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{#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 (liftM, liftM2, when, (>=>), (<=<), forever)\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.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)\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#include \"overviews.h\"\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\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\ndriverCreationOptionList :: DriverName -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverHByName 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 :: 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\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\ncreateOverviewDataset\n :: Dataset s a t -> Int -> Bool -> GDAL s (Dataset s a t)\ncreateOverviewDataset ds ovLevel thisLevelOnly = newDatasetHandle $\n {#call hs_gdal_create_overview_dataset#}\n (unDataset ds) (fromIntegral ovLevel) (fromEnumC thisLevelOnly)\n\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\ndatasetDriverName :: Dataset s a t -> DriverName\ndatasetDriverName ds = unsafePerformIO $\n DriverName <$> (packCString =<< {#call unsafe GetDriverShortName as ^#} d)\n where Driver d = datasetDriver 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 :: MonadIO m => Dataset s a t -> m (Maybe SpatialReference)\ndatasetProjection\n = liftIO\n . (maybeSpatialReferenceFromCString <=< {#call unsafe GetProjectionRef as ^#})\n . unDataset\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 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 <- 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\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 <$> 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:: 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 liftM 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 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 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 liftM (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 :: MonadIO m => Band s a t -> Envelope Int -> Size -> m Int\nbandBestOverviewLevel band (Envelope (x0 :+: y0) (x1 :+: y1)) (nx :+: ny) =\n liftIO $\n fromIntegral <$> {#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\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\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{-# INLINEABLE 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\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{-# INLINEABLE 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\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 :: 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 = 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 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 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 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{-# INLINEABLE fmapBand #-}\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 <- liftM (L.foldl' (G.zipWith fun) acc)\n (lift (mapM (flip readBandBlock bix) bs))\n yield (bix, r)\n{-# INLINEABLE foldBands #-}\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{-# 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 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{-# 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\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 >=> 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 :: (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\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":"61fc4e7c73d9e98e1db65c918958d8828fe96df8","subject":"Tighten up temporary name assignment.","message":"Tighten up temporary name assignment.\n\nThings with names were consuming ids. Not a problem, but annoying\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 ( 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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 ref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState ref)\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 put s { typeMap = M.insert ip t (typeMap s) }\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 (_, TYPE_NAMED) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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\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 { 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","old_contents":"{-# 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 )\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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 ref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState ref)\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 put s { typeMap = M.insert ip t (typeMap s) }\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 (_, TYPE_NAMED) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\n s <- get\n let cdepth = constantTranslationDepth s\n idCtr = localId s\n realName <- case 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 = Nothing\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\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 { 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"4b7c0ef3ea386e9de2206d6c7813b5d377fcdbfb","subject":"Add a helper needed on i386","message":"Add a helper needed on i386\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 #-}\nmodule LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems, unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\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\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\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\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\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 :: 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#}\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 = dw_tag <$> {#get CMeta->tag#} p\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 ByteString\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 ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\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 ByteString\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 ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\n-- cMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeCompileUnit = 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#}\ncMetaUnknownRepr :: InternString m => MetaPtr -> m ByteString\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 :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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\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 #-}\nmodule LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems, unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\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\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\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\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\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 :: 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#}\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 = dw_tag <$> {#get CMeta->tag#} p\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 ByteString\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 ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\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 ByteString\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 ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\n-- cMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeCompileUnit = 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#}\ncMetaUnknownRepr :: InternString m => MetaPtr -> m ByteString\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 :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c8254a483c1512ddcc8ddb67a3a33d50835e0630","subject":"GPU data for compute 2.1, 3.0, and 3.5 devices","message":"GPU data for compute 2.1, 3.0, and 3.5 devices\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2011] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute, ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n resources\n )\n where\n\n#include \n\nimport Data.Int\nimport Data.Maybe\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability\n--\ntype Compute = Double\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device. If\n-- an exact match is not found, choose a sensible default.\n--\nresources :: DeviceProperties -> DeviceResources\nresources dev = fromMaybe def (lookup compute gpuData)\n where\n compute = computeCapability dev\n def | compute < 1.0 = snd $ head gpuData\n | otherwise = snd $ last gpuData\n\n gpuData =\n [(1.0, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.1, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.2, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(1.3, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(2.0, DeviceResources 32 1536 8 48 49152 128 32768 64 2 Warp)\n ,(2.1, DeviceResources 32 1536 8 48 49152 128 32768 64 2 Warp)\n ,(3.0, DeviceResources 32 2048 16 64 49152 256 65536 256 4 Warp)\n ,(3.5, DeviceResources 32 2048 16 64 49152 256 65536 256 4 Warp)\n ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2011] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute, ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n resources\n )\n where\n\n#include \n\nimport Data.Int\nimport Data.Maybe\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability\n--\ntype Compute = Double\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device. If\n-- an exact match is not found, choose a sensible default.\n--\nresources :: DeviceProperties -> DeviceResources\nresources dev = fromMaybe def (lookup compute gpuData)\n where\n compute = computeCapability dev\n def | compute < 1.0 = snd $ head gpuData\n | otherwise = snd $ last gpuData\n\n gpuData =\n [(1.0, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.1, DeviceResources 32 768 8 24 16384 512 8192 256 2 Block)\n ,(1.2, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(1.3, DeviceResources 32 1024 8 32 16384 512 16384 512 2 Block)\n ,(2.0, DeviceResources 32 1536 8 48 49152 128 32768 64 1 Warp)\n ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"882f5fb1643cc3b4b4707b256474c28fe5277193","subject":"Fix SourceLanguageManager.chs docs.","message":"Fix SourceLanguageManager.chs docs.\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 :: 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","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceLanguageManager (\n SourceLanguageManager,\n SourceLanguageManagerClass,\n castToSourceLanguageManager,\n sourceLanguageManagerNew,\n sourceLanguageManagerGetDefault,\n sourceLanguageManagerSetSearchPath,\n sourceLanguageManagerGetSearchPath,\n sourceLanguageManagerGetLanguageIds,\n sourceLanguageManagerGetLanguage,\n sourceLanguageManagerGuessLanguage\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-- |\n--\nsourceLanguageManagerNew :: IO SourceLanguageManager\nsourceLanguageManagerNew = constructNewGObject mkSourceLanguageManager $ liftM castPtr\n {#call unsafe source_language_manager_new#}\n\n-- |\n--\nsourceLanguageManagerGetDefault :: IO SourceLanguageManager\nsourceLanguageManagerGetDefault = makeNewGObject mkSourceLanguageManager $ liftM castPtr\n {#call unsafe source_language_manager_new#}\n\n-- |\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-- |\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-- |\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-- |\n--\nsourceLanguageManagerGetLanguage :: SourceLanguageManager -> String -> IO (Maybe SourceLanguage)\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-- |\n--\nsourceLanguageManagerGuessLanguage :: SourceLanguageManager -> Maybe String -> Maybe String -> IO (Maybe SourceLanguage)\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-- |\n--\nsourceLanguageManagerLanguageIds :: ReadAttr SourceLanguageManager [String]\nsourceLanguageManagerLanguageIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"language-ids\" {#call pure g_strv_get_type#}\n\n-- |\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":"8da12038b4c152f12f44c4cdeb1a0c4e63a161ef","subject":"Fix treeView.chs docs.","message":"Fix treeView.chs docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"7f09a362b509a200b8f0698fe7528b36e2f662c5","subject":"changed createCopy signature","message":"changed createCopy signature\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 , 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 , 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.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 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 (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 unsafeUseAsCString (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 -> BlockIx -> 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\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\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 , 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 , 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.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 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 unsafeUseAsCString (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 -> BlockIx -> 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\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\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":"0e7cd47089ce6ccf762bc070b99e12f48237948f","subject":"Add a few top level types.","message":"Add a few top level types.\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, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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 -> 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\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\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.\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\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-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\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 :: (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) = 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 return r\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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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 = withUniPtr withImage\nwithMutableImage (Mutable i) o = withGenImage i o\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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 -> 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\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\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\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\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 = 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 = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\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 :: (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) = 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 return r\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":"9cad94eafc260cac6400ac2a29c465708262fb4e","subject":"Fixed typo.","message":"Fixed typo.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content. The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\nwebDataSourceGetData :: WebDataSourceClass self => self\n -> IO (Maybe String)\nwebDataSourceGetData ds = do\n gstr <- {#call webkit_web_data_source_get_data #}\n (toWebDataSource ds)\n readGString gstr\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content.The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\nwebDataSourceGetData :: WebDataSourceClass self => self\n -> IO (Maybe String)\nwebDataSourceGetData ds = do\n gstr <- {#call webkit_web_data_source_get_data #}\n (toWebDataSource ds)\n readGString gstr\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d373b31dfe43cc0d9bbcb009f01d052fa130593b","subject":"gnomevfs: add function S.G.V.Volume.volumeUnmount","message":"gnomevfs: add function S.G.V.Volume.volumeUnmount\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"f80ab8a86498f379ac8f5428e40b424fe486c316","subject":"add image format data","message":"add image format data\n","repos":"Delan90\/opencl,IFCA\/opencl,Delan90\/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 -- * 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.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, getEnumCL, bitmaskFromFlags, \n 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\n--foreign import CALLCONV \"clCreateImage2D\" raw_clCreateImage2D :: \n-- CLContext -> CLMemFlags_ -> CLImageFormat_p -> CSize -> CSize -> CSize \n-- -> Ptr () -> Ptr CLint -> IO CLMem\n--foreign 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\n--foreign 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#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} #}\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} #}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\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(..),\n -- * Memory Functions\n clCreateBuffer, clRetainMemObject, clReleaseMemObject, clGetMemType, \n clGetMemFlags, clGetMemSize, clGetMemHostPtr, clGetMemMapCount, \n clGetMemReferenceCount, clGetMemContext,\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.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, getEnumCL, bitmaskFromFlags, \n 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\n--foreign import CALLCONV \"clCreateImage2D\" raw_clCreateImage2D :: \n-- CLContext -> CLMemFlags_ -> CLImageFormat_p -> CSize -> CSize -> CSize \n-- -> Ptr () -> Ptr CLint -> IO CLMem\n--foreign 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\n--foreign 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#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":"f2c1dcee3f8e6ad95a5bd8afec9008ca68414044","subject":"Use nocode c2hs option.","message":"Use nocode c2hs option.\n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Admin.chs","new_file":"src\/Database\/HyperDex\/Internal\/Admin.chs","new_contents":"{-# LANGUAGE TypeFamilies, FlexibleInstances, TypeSynonymInstances #-}\n\n-- |\n-- Module \t: Database.HyperDex.Internal.Admin\n-- Copyright \t: (c) Aaron Friel 2013-2014\n-- \t (c) Niklas Hamb\u00fcchen 2013-2014 \n-- License \t: BSD-style\n-- Maintainer \t: mayreply@aaronfriel.com\n-- Stability \t: unstable\n-- Portability\t: portable\n--\nmodule Database.HyperDex.Internal.Admin\n ( Admin\n , AdminConnection\n , ReturnCode (..)\n , adminConnect\n , peekReturnCode\n , adminDeferred\n , adminImmediate\n )\n where\n\nimport Database.HyperDex.Internal.Core\nimport Database.HyperDex.Internal.Handle\nimport Database.HyperDex.Internal.Options\nimport Database.HyperDex.Internal.Util\n\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Resource\nimport Foreign\nimport Foreign.C\n\n#include \"hyperdex\/admin.h\"\n\ndata OpaqueAdmin\n{#pointer *hyperdex_admin as Admin -> OpaqueAdmin #}\n\ntype AdminConnection = HyperDexConnection Admin\n\npeekReturnCode :: MonadIO m \n => Ptr CInt\n -> m (ReturnCode Admin)\npeekReturnCode = liftIO . fmap (toEnum . fromIntegral) . peek\n\ninstance HyperDex Admin where\n data ReturnCode Admin = AdminSuccess\n | AdminNomem\n | AdminNonepending\n | AdminPollfailed\n | AdminTimeout\n | AdminInterrupted\n | AdminServererror\n | AdminCoordfail\n | AdminBadspace\n | AdminDuplicate\n | AdminNotfound\n | AdminInternal\n | AdminException\n | AdminGarbage\n deriving (Eq,Show)\n\n failureCode = AdminGarbage\n\n isTransient AdminInterrupted = True\n isTransient AdminTimeout = True\n isTransient _ = False \n \n isGlobalError AdminInternal = True\n isGlobalError AdminException = True\n isGlobalError AdminGarbage = True\n isGlobalError _ = False \n\n isNonePending AdminNonepending = True\n isNonePending _ = False\n\n create host port =\n wrapHyperCall $ {# call hyperdex_admin_create #} host port\n\n destroy ptr =\n wrapHyperCall $ {# call hyperdex_admin_destroy #} ptr\n\n loop ptr timeout =\n alloca $ \\returnCodePtr -> do\n handle <- wrapHyperCall $ {# call hyperdex_admin_loop #} ptr timeout returnCodePtr\n returnCode <- peekReturnCode returnCodePtr\n return (mkHandle handle, returnCode)\n\n{# enum hyperdex_admin_returncode as `ReturnCode Admin`\n nocode#}\n\n-- instance Enum (ReturnCode Admin) where\n-- fromEnum AdminSuccess = 8704\n-- fromEnum AdminNomem = 8768\n-- fromEnum AdminNonepending = 8769\n-- fromEnum AdminPollfailed = 8770\n-- fromEnum AdminTimeout = 8771\n-- fromEnum AdminInterrupted = 8772\n-- fromEnum AdminServererror = 8773\n-- fromEnum AdminCoordfail = 8774\n-- fromEnum AdminBadspace = 8775\n-- fromEnum AdminDuplicate = 8776\n-- fromEnum AdminNotfound = 8777\n-- fromEnum AdminInternal = 8829\n-- fromEnum AdminException = 8830\n-- fromEnum AdminGarbage = 8831\n\n-- toEnum 8704 = AdminSuccess\n-- toEnum 8768 = AdminNomem\n-- toEnum 8769 = AdminNonepending\n-- toEnum 8770 = AdminPollfailed\n-- toEnum 8771 = AdminTimeout\n-- toEnum 8772 = AdminInterrupted\n-- toEnum 8773 = AdminServererror\n-- toEnum 8774 = AdminCoordfail\n-- toEnum 8775 = AdminBadspace\n-- toEnum 8776 = AdminDuplicate\n-- toEnum 8777 = AdminNotfound\n-- toEnum 8829 = AdminInternal\n-- toEnum 8830 = AdminException\n-- toEnum 8831 = AdminGarbage\n-- toEnum unmatched = error (\"AdminReturnCode.toEnum: Cannot match \" ++ show unmatched)\n\nadminConnect :: ConnectInfo -> IO (AdminConnection)\nadminConnect = connect\n\nadminDeferred :: ResIO (AsyncCall Admin a) \n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminDeferred = wrapDeferred (AdminSuccess==)\n\nadminImmediate :: ResIO (SyncCall Admin a)\n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminImmediate = wrapImmediate\n\n-- adminDisconnect :: (AdminConnection) -> IO ()\n-- adminDisconnect = disconnect\n","old_contents":"{-# LANGUAGE TypeFamilies, FlexibleInstances, TypeSynonymInstances #-}\n\n-- |\n-- Module \t: Database.HyperDex.Internal.Admin\n-- Copyright \t: (c) Aaron Friel 2013-2014\n-- \t (c) Niklas Hamb\u00fcchen 2013-2014 \n-- License \t: BSD-style\n-- Maintainer \t: mayreply@aaronfriel.com\n-- Stability \t: unstable\n-- Portability\t: portable\n--\nmodule Database.HyperDex.Internal.Admin\n ( Admin\n , AdminConnection\n , ReturnCode (..)\n , adminConnect\n , peekReturnCode\n , adminDeferred\n , adminImmediate\n )\n where\n\nimport Database.HyperDex.Internal.Core\nimport Database.HyperDex.Internal.Handle\nimport Database.HyperDex.Internal.Options\nimport Database.HyperDex.Internal.Util\n\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Resource\nimport Foreign\nimport Foreign.C\n\n#include \"hyperdex\/admin.h\"\n\ndata OpaqueAdmin\n{#pointer *hyperdex_admin as Admin -> OpaqueAdmin #}\n\ntype AdminConnection = HyperDexConnection Admin\n\npeekReturnCode :: MonadIO m \n => Ptr CInt\n -> m (ReturnCode Admin)\npeekReturnCode = liftIO . fmap (toEnum . fromIntegral) . peek\n\ninstance HyperDex Admin where\n data ReturnCode Admin = AdminSuccess\n | AdminNomem\n | AdminNonepending\n | AdminPollfailed\n | AdminTimeout\n | AdminInterrupted\n | AdminServererror\n | AdminCoordfail\n | AdminBadspace\n | AdminDuplicate\n | AdminNotfound\n | AdminInternal\n | AdminException\n | AdminGarbage\n deriving (Eq,Show)\n\n failureCode = AdminGarbage\n\n isTransient AdminInterrupted = True\n isTransient AdminTimeout = True\n isTransient _ = False \n \n isGlobalError AdminInternal = True\n isGlobalError AdminException = True\n isGlobalError AdminGarbage = True\n isGlobalError _ = False \n\n isNonePending AdminNonepending = True\n isNonePending _ = False\n\n create host port =\n wrapHyperCall $ {# call hyperdex_admin_create #} host port\n\n destroy ptr =\n wrapHyperCall $ {# call hyperdex_admin_destroy #} ptr\n\n loop ptr timeout =\n alloca $ \\returnCodePtr -> do\n handle <- wrapHyperCall $ {# call hyperdex_admin_loop #} ptr timeout returnCodePtr\n returnCode <- peekReturnCode returnCodePtr\n return (mkHandle handle, returnCode)\n\ninstance Enum (ReturnCode Admin) where\n fromEnum AdminSuccess = 8704\n fromEnum AdminNomem = 8768\n fromEnum AdminNonepending = 8769\n fromEnum AdminPollfailed = 8770\n fromEnum AdminTimeout = 8771\n fromEnum AdminInterrupted = 8772\n fromEnum AdminServererror = 8773\n fromEnum AdminCoordfail = 8774\n fromEnum AdminBadspace = 8775\n fromEnum AdminDuplicate = 8776\n fromEnum AdminNotfound = 8777\n fromEnum AdminInternal = 8829\n fromEnum AdminException = 8830\n fromEnum AdminGarbage = 8831\n\n toEnum 8704 = AdminSuccess\n toEnum 8768 = AdminNomem\n toEnum 8769 = AdminNonepending\n toEnum 8770 = AdminPollfailed\n toEnum 8771 = AdminTimeout\n toEnum 8772 = AdminInterrupted\n toEnum 8773 = AdminServererror\n toEnum 8774 = AdminCoordfail\n toEnum 8775 = AdminBadspace\n toEnum 8776 = AdminDuplicate\n toEnum 8777 = AdminNotfound\n toEnum 8829 = AdminInternal\n toEnum 8830 = AdminException\n toEnum 8831 = AdminGarbage\n toEnum unmatched = error (\"AdminReturnCode.toEnum: Cannot match \" ++ show unmatched)\n\nadminConnect :: ConnectInfo -> IO (AdminConnection)\nadminConnect = connect\n\nadminDeferred :: ResIO (AsyncCall Admin a) \n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminDeferred = wrapDeferred (AdminSuccess==)\n\nadminImmediate :: ResIO (SyncCall Admin a)\n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminImmediate = wrapImmediate\n\n-- adminDisconnect :: (AdminConnection) -> IO ()\n-- adminDisconnect = disconnect\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9577ba9c1813d43226b588ff71d6fee15d081645","subject":"Finish PopplerAction module","message":"Finish PopplerAction module\n","repos":"gtk2hs\/poppler,wavewave\/poppler","old_file":"Graphics\/UI\/Gtk\/Poppler\/Enums.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Enums.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Enums (\n-- * Enums\n Error(..),\n Orientation(..),\n SelectionStyle(..),\n PageTransitionType(..),\n PageTransitionAlignment(..),\n PageTransitionDirection(..),\n Backend(..),\n PageLayout(..),\n PageMode(..),\n FontType(..),\n ViewerPreferences(..),\n Permissions(..),\n ActionType(..),\n DestType(..),\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.UTFString\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n{# enum PopplerError as Error {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerOrientation as Orientation {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerSelectionStyle as SelectionStyle {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageTransitionType as PageTransitionType {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageTransitionAlignment as PageTransitionAlignment {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageTransitionDirection as PageTransitionDirection {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerBackend as Backend {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\n{# enum PopplerPageLayout as PageLayout {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageMode as PageMode {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerFontType as FontType {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerViewerPreferences as ViewerPreferences {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPermissions as Permissions {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerActionType as ActionType {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerDestType as DestType {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Enums (\n-- * Enums\n Error(..),\n Orientation(..),\n SelectionStyle(..),\n PageTransitionType(..),\n PageTransitionAlignment(..),\n PageTransitionDirection(..),\n Backend(..),\n PageLayout(..),\n PageMode(..),\n FontType(..),\n ViewerPreferences(..),\n Permissions(..),\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.UTFString\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n{# enum PopplerError as Error {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerOrientation as Orientation {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerSelectionStyle as SelectionStyle {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageTransitionType as PageTransitionType {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageTransitionAlignment as PageTransitionAlignment {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageTransitionDirection as PageTransitionDirection {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerBackend as Backend {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\n{# enum PopplerPageLayout as PageLayout {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPageMode as PageMode {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerFontType as FontType {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerViewerPreferences as ViewerPreferences {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n{# enum PopplerPermissions as Permissions {underscoreToCase} with prefix = \"Poppler\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1b7f0ba5e9905c56ce6e36f6419e4f1cd4f7572d","subject":"Fix build failure, unused variable rc.","message":"Fix build failure, unused variable rc.\n\nSigned-off-by: Aaron Friel \n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Admin.chs","new_file":"src\/Database\/HyperDex\/Internal\/Admin.chs","new_contents":"{-# LANGUAGE TypeFamilies, FlexibleInstances, TypeSynonymInstances #-}\n\n-- |\n-- Module \t: Database.HyperDex.Internal.Admin\n-- Copyright \t: (c) Aaron Friel 2013-2014\n-- \t (c) Niklas Hamb\u00fcchen 2013-2014 \n-- License \t: BSD-style\n-- Maintainer \t: mayreply@aaronfriel.com\n-- Stability \t: unstable\n-- Portability\t: portable\n--\nmodule Database.HyperDex.Internal.Admin\n ( Admin\n , AdminConnection\n , ReturnCode (..)\n , adminConnect\n , peekReturnCode\n , adminDeferred\n , adminImmediate\n )\n where\n\nimport Database.HyperDex.Internal.Core\nimport Database.HyperDex.Internal.Handle\nimport Database.HyperDex.Internal.Options\nimport Database.HyperDex.Internal.Util\n\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Resource\nimport Foreign\nimport Foreign.C\n\n#include \"hyperdex\/admin.h\"\n\ndata OpaqueAdmin\n{#pointer *hyperdex_admin as Admin -> OpaqueAdmin #}\n\ntype AdminConnection = HyperDexConnection Admin\n\npeekReturnCode :: MonadIO m \n => Ptr CInt\n -> m (ReturnCode Admin)\npeekReturnCode = liftIO . fmap (toEnum . fromIntegral) . peek\n\ninstance HyperDex Admin where\n data ReturnCode Admin = AdminSuccess\n | AdminNomem\n | AdminNonepending\n | AdminPollfailed\n | AdminTimeout\n | AdminInterrupted\n | AdminServererror\n | AdminCoordfail\n | AdminBadspace\n | AdminDuplicate\n | AdminNotfound\n | AdminInternal\n | AdminException\n | AdminGarbage\n deriving (Eq,Show)\n\n failureCode = AdminGarbage\n\n isTransient AdminInterrupted = True\n isTransient AdminTimeout = True\n isTransient _ = False \n \n isGlobalError AdminInternal = True\n isGlobalError AdminException = True\n isGlobalError AdminGarbage = True\n isGlobalError _ = False \n\n isNonePending AdminNonepending = True\n isNonePending _ = False\n\n create host port =\n wrapHyperCall $ {# call hyperdex_admin_create #} host port\n\n destroy ptr =\n wrapHyperCall $ {# call hyperdex_admin_destroy #} ptr\n\n loop ptr timeout =\n alloca $ \\returnCodePtr -> do\n handle <- wrapHyperCall $ {# call hyperdex_admin_loop #} ptr timeout returnCodePtr\n returnCode <- peekReturnCode returnCodePtr\n return (mkHandle handle, returnCode)\n\ninstance Enum (ReturnCode Admin) where\n fromEnum AdminSuccess = 8704\n fromEnum AdminNomem = 8768\n fromEnum AdminNonepending = 8769\n fromEnum AdminPollfailed = 8770\n fromEnum AdminTimeout = 8771\n fromEnum AdminInterrupted = 8772\n fromEnum AdminServererror = 8773\n fromEnum AdminCoordfail = 8774\n fromEnum AdminBadspace = 8775\n fromEnum AdminDuplicate = 8776\n fromEnum AdminNotfound = 8777\n fromEnum AdminInternal = 8829\n fromEnum AdminException = 8830\n fromEnum AdminGarbage = 8831\n\n toEnum 8704 = AdminSuccess\n toEnum 8768 = AdminNomem\n toEnum 8769 = AdminNonepending\n toEnum 8770 = AdminPollfailed\n toEnum 8771 = AdminTimeout\n toEnum 8772 = AdminInterrupted\n toEnum 8773 = AdminServererror\n toEnum 8774 = AdminCoordfail\n toEnum 8775 = AdminBadspace\n toEnum 8776 = AdminDuplicate\n toEnum 8777 = AdminNotfound\n toEnum 8829 = AdminInternal\n toEnum 8830 = AdminException\n toEnum 8831 = AdminGarbage\n toEnum unmatched = error (\"AdminReturnCode.toEnum: Cannot match \" ++ show unmatched)\n\nadminConnect :: ConnectInfo -> IO (AdminConnection)\nadminConnect = connect\n\nadminDeferred :: ResIO (AsyncCall Admin a) \n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminDeferred = wrapDeferred (AdminSuccess==)\n\nadminImmediate :: ResIO (SyncCall Admin a)\n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminImmediate = wrapImmediate\n\n-- adminDisconnect :: (AdminConnection) -> IO ()\n-- adminDisconnect = disconnect\n","old_contents":"{-# LANGUAGE TypeFamilies, FlexibleInstances, TypeSynonymInstances #-}\n\n-- |\n-- Module \t: Database.HyperDex.Internal.Admin\n-- Copyright \t: (c) Aaron Friel 2013-2014\n-- \t (c) Niklas Hamb\u00fcchen 2013-2014 \n-- License \t: BSD-style\n-- Maintainer \t: mayreply@aaronfriel.com\n-- Stability \t: unstable\n-- Portability\t: portable\n--\nmodule Database.HyperDex.Internal.Admin\n ( Admin\n , AdminConnection\n , ReturnCode (..)\n , adminConnect\n , peekReturnCode\n , adminDeferred\n , adminImmediate\n )\n where\n\nimport Database.HyperDex.Internal.Core\nimport Database.HyperDex.Internal.Handle\nimport Database.HyperDex.Internal.Options\nimport Database.HyperDex.Internal.Util\n\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Resource\nimport Foreign\nimport Foreign.C\n\n#include \"hyperdex\/admin.h\"\n\ndata OpaqueAdmin\n{#pointer *hyperdex_admin as Admin -> OpaqueAdmin #}\n\ntype AdminConnection = HyperDexConnection Admin\n\npeekReturnCode :: MonadIO m \n => Ptr CInt\n -> m (ReturnCode Admin)\npeekReturnCode = liftIO . fmap (toEnum . fromIntegral) . peek\n\ninstance HyperDex Admin where\n data ReturnCode Admin = AdminSuccess\n | AdminNomem\n | AdminNonepending\n | AdminPollfailed\n | AdminTimeout\n | AdminInterrupted\n | AdminServererror\n | AdminCoordfail\n | AdminBadspace\n | AdminDuplicate\n | AdminNotfound\n | AdminInternal\n | AdminException\n | AdminGarbage\n deriving (Eq,Show)\n\n failureCode = AdminGarbage\n\n isTransient AdminInterrupted = True\n isTransient AdminTimeout = True\n isTransient rc = False \n \n isGlobalError AdminInternal = True\n isGlobalError AdminException = True\n isGlobalError AdminGarbage = True\n isGlobalError _ = False \n\n isNonePending AdminNonepending = True\n isNonePending _ = False\n\n create host port =\n wrapHyperCall $ {# call hyperdex_admin_create #} host port\n\n destroy ptr =\n wrapHyperCall $ {# call hyperdex_admin_destroy #} ptr\n\n loop ptr timeout =\n alloca $ \\returnCodePtr -> do\n handle <- wrapHyperCall $ {# call hyperdex_admin_loop #} ptr timeout returnCodePtr\n returnCode <- peekReturnCode returnCodePtr\n return (mkHandle handle, returnCode)\n\ninstance Enum (ReturnCode Admin) where\n fromEnum AdminSuccess = 8704\n fromEnum AdminNomem = 8768\n fromEnum AdminNonepending = 8769\n fromEnum AdminPollfailed = 8770\n fromEnum AdminTimeout = 8771\n fromEnum AdminInterrupted = 8772\n fromEnum AdminServererror = 8773\n fromEnum AdminCoordfail = 8774\n fromEnum AdminBadspace = 8775\n fromEnum AdminDuplicate = 8776\n fromEnum AdminNotfound = 8777\n fromEnum AdminInternal = 8829\n fromEnum AdminException = 8830\n fromEnum AdminGarbage = 8831\n\n toEnum 8704 = AdminSuccess\n toEnum 8768 = AdminNomem\n toEnum 8769 = AdminNonepending\n toEnum 8770 = AdminPollfailed\n toEnum 8771 = AdminTimeout\n toEnum 8772 = AdminInterrupted\n toEnum 8773 = AdminServererror\n toEnum 8774 = AdminCoordfail\n toEnum 8775 = AdminBadspace\n toEnum 8776 = AdminDuplicate\n toEnum 8777 = AdminNotfound\n toEnum 8829 = AdminInternal\n toEnum 8830 = AdminException\n toEnum 8831 = AdminGarbage\n toEnum unmatched = error (\"AdminReturnCode.toEnum: Cannot match \" ++ show unmatched)\n\nadminConnect :: ConnectInfo -> IO (AdminConnection)\nadminConnect = connect\n\nadminDeferred :: ResIO (AsyncCall Admin a) \n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminDeferred = wrapDeferred (AdminSuccess==)\n\nadminImmediate :: ResIO (SyncCall Admin a)\n -> AdminConnection\n -> IO (AsyncResult Admin a)\nadminImmediate = wrapImmediate\n\n-- adminDisconnect :: (AdminConnection) -> IO ()\n-- adminDisconnect = disconnect\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c05a7750c53d59b3a41d9c167a47eb8d13ac0b77","subject":"Stop exporting maxErrorString and maxProcessorName - it is not needed outside of Internal.chs","message":"Stop exporting maxErrorString and maxProcessorName - it is not needed outside of Internal.chs\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(..),\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{-\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\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\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-- | 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, 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 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 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 '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#if 0\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{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\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 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\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, errorsThrowExceptions :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n-- This is a more meaningful name than errorsReturn\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 #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A 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{-\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 :: 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{-\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\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 -- ** Predefined constants.\n maxProcessorName, maxErrorString,\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{-\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. 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\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-- | 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, 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 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 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 '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#if 0\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{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\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 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\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, errorsThrowExceptions :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n-- This is a more meaningful name than errorsReturn\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 #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A 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{-\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 :: 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{-\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\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":"5f4aed2194ece6161e8f5bfe4a7295bbae0e7305","subject":"remove redundant import","message":"remove redundant import\n\nIgnore-this: 95ef2ca2921f3e662e47b640fe570848\n\ndarcs-hash:20100116020805-dcabc-14953569c945c1cb40180a581adaa67f1a6be36d.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 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","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 Data.Maybe\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":"9dac8e99a309235bcf6ee6fa9b722aff242a212a","subject":"Update on\/afterEdited to use new TreeIter","message":"Update on\/afterEdited to use new TreeIter\n\nand to use connect_STRING_STRING__NONE rather than\nconnect_PTR_STRING__NONE. This is a different implementation than the\none in ModelView since the latter has a different type too. So this is\njust an intrim implementation.\n\ndarcs-hash:20061208205259-b4c10-9bcbb4dd2c5335ab88cce8de4a1449650d96eec5.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CellRendererText.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CellRendererText.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CellRendererText TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.7 $ 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-- A 'CellRenderer' which displays a single-line text.\n--\nmodule Graphics.UI.Gtk.TreeList.CellRendererText (\n-- * Detail\n-- \n-- | This widget derives from 'CellRenderer'. It provides the \n-- possibility to display some text by setting the 'Attribute' \n-- 'cellText' to the column of a 'TreeModel' by means of \n-- 'treeViewAddAttribute' from 'TreeModelColumn'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'CellRenderer'\n-- | +----CellRendererText\n-- | +----'CellRendererCombo'\n-- @\n\n-- * Types\n CellRendererText,\n CellRendererTextClass,\n castToCellRendererText,\n toCellRendererText,\n\n-- * Constructors\n cellRendererTextNew,\n\n-- * Attributes\n cellText,\n cellMarkup,\n cellBackground,\n cellForeground,\n cellEditable,\n\n-- * Signals\n onEdited,\n afterEdited\n ) where\n\nimport Maybe\t(fromMaybe)\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\nimport Graphics.UI.Gtk.General.Structs\t\t(treeIterSize)\nimport Graphics.UI.Gtk.TreeList.CellRenderer\t(Attribute(..))\nimport System.Glib.StoreValue\t\t\t(GenericValue(..), TMType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new CellRendererText object.\n--\ncellRendererTextNew :: IO CellRendererText\ncellRendererTextNew =\n makeNewObject mkCellRendererText $\n liftM (castPtr :: Ptr CellRenderer -> Ptr CellRendererText) $\n {# call unsafe cell_renderer_text_new #}\n\n-- helper function\n--\nstrAttr :: [String] -> Attribute CellRendererText String\nstrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring . Just)\n\t\t(\\[GVstring str] -> return (fromMaybe \"\" str))\n\nmStrAttr :: [String] -> Attribute CellRendererText (Maybe String)\nmStrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring)\n\t\t(\\[GVstring str] -> return str)\n\n--------------------\n-- Properties\n\n-- | Define the attribute that specifies the text to be\n-- rendered.\n--\ncellText :: Attribute CellRendererText String\ncellText = strAttr [\"text\"]\n\n-- | Define a markup string instead of a text.\n--\ncellMarkup :: Attribute CellRendererText String\ncellMarkup = strAttr [\"markup\"]\n\n-- | A named color for the background paint.\n--\ncellBackground :: Attribute CellRendererText (Maybe String)\ncellBackground = mStrAttr [\"background\"]\n\n-- | A named color for the foreground paint.\n--\ncellForeground :: Attribute CellRendererText (Maybe String)\ncellForeground = mStrAttr [\"foreground\"]\n\n-- | Determines wether the content can be altered.\n--\n-- * If this flag is set, the user can alter the cell.\n--\ncellEditable :: Attribute CellRendererText (Maybe Bool)\ncellEditable = Attribute [\"editable\",\"editable-set\"] [TMboolean,TMboolean]\n\t (\\mb -> return $ case mb of\n\t\t (Just bool) -> [GVboolean bool, GVboolean True]\n\t\t Nothing -> [GVboolean True, GVboolean False])\n\t\t (\\[GVboolean e, GVboolean s] -> return $\n\t\t if s then Just e else Nothing)\n\n-- | Emitted when the user finished editing a cell.\n--\n-- * This signal is not emitted when editing is disabled (see \n-- 'cellEditable') or when the user aborts editing.\n--\nonEdited, afterEdited :: TreeModelClass tm => CellRendererText -> tm ->\n\t\t\t (TreeIter -> String -> IO ()) ->\n\t\t\t IO (ConnectId CellRendererText)\nonEdited cr tm user = connect_STRING_STRING__NONE \"edited\" False cr $\n \\path string ->\n alloca $ \\iterPtr ->\n withCString path $ \\pathPtr -> do\n res <- {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iterPtr\n pathPtr\n if toBool res\n then do\n iter <- peek iterPtr\n user iter string\n else\n putStrLn \"edited signal: invalid tree path\"\n\nafterEdited cr tm user = connect_STRING_STRING__NONE \"edited\" True cr $\n \\path string ->\n alloca $ \\iterPtr ->\n withCString path $ \\pathPtr -> do\n res <- {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iterPtr\n pathPtr\n if toBool res\n then do\n iter <- peek iterPtr\n user iter string\n else\n putStrLn \"edited signal: invalid tree path\"\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CellRendererText TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.7 $ 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-- A 'CellRenderer' which displays a single-line text.\n--\nmodule Graphics.UI.Gtk.TreeList.CellRendererText (\n-- * Detail\n-- \n-- | This widget derives from 'CellRenderer'. It provides the \n-- possibility to display some text by setting the 'Attribute' \n-- 'cellText' to the column of a 'TreeModel' by means of \n-- 'treeViewAddAttribute' from 'TreeModelColumn'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'CellRenderer'\n-- | +----CellRendererText\n-- | +----'CellRendererCombo'\n-- @\n\n-- * Types\n CellRendererText,\n CellRendererTextClass,\n castToCellRendererText,\n toCellRendererText,\n\n-- * Constructors\n cellRendererTextNew,\n\n-- * Attributes\n cellText,\n cellMarkup,\n cellBackground,\n cellForeground,\n cellEditable,\n\n-- * Signals\n onEdited,\n afterEdited\n ) where\n\nimport Maybe\t(fromMaybe)\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\nimport Graphics.UI.Gtk.General.Structs\t\t(treeIterSize)\nimport Graphics.UI.Gtk.TreeList.CellRenderer\t(Attribute(..))\nimport System.Glib.StoreValue\t\t\t(GenericValue(..), TMType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new CellRendererText object.\n--\ncellRendererTextNew :: IO CellRendererText\ncellRendererTextNew =\n makeNewObject mkCellRendererText $\n liftM (castPtr :: Ptr CellRenderer -> Ptr CellRendererText) $\n {# call unsafe cell_renderer_text_new #}\n\n-- helper function\n--\nstrAttr :: [String] -> Attribute CellRendererText String\nstrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring . Just)\n\t\t(\\[GVstring str] -> return (fromMaybe \"\" str))\n\nmStrAttr :: [String] -> Attribute CellRendererText (Maybe String)\nmStrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring)\n\t\t(\\[GVstring str] -> return str)\n\n--------------------\n-- Properties\n\n-- | Define the attribute that specifies the text to be\n-- rendered.\n--\ncellText :: Attribute CellRendererText String\ncellText = strAttr [\"text\"]\n\n-- | Define a markup string instead of a text.\n--\ncellMarkup :: Attribute CellRendererText String\ncellMarkup = strAttr [\"markup\"]\n\n-- | A named color for the background paint.\n--\ncellBackground :: Attribute CellRendererText (Maybe String)\ncellBackground = mStrAttr [\"background\"]\n\n-- | A named color for the foreground paint.\n--\ncellForeground :: Attribute CellRendererText (Maybe String)\ncellForeground = mStrAttr [\"foreground\"]\n\n-- | Determines wether the content can be altered.\n--\n-- * If this flag is set, the user can alter the cell.\n--\ncellEditable :: Attribute CellRendererText (Maybe Bool)\ncellEditable = Attribute [\"editable\",\"editable-set\"] [TMboolean,TMboolean]\n\t (\\mb -> return $ case mb of\n\t\t (Just bool) -> [GVboolean bool, GVboolean True]\n\t\t Nothing -> [GVboolean True, GVboolean False])\n\t\t (\\[GVboolean e, GVboolean s] -> return $\n\t\t if s then Just e else Nothing)\n\n-- | Emitted when the user finished editing a cell.\n--\n-- * This signal is not emitted when editing is disabled (see \n-- 'cellEditable') or when the user aborts editing.\n--\nonEdited, afterEdited :: TreeModelClass tm => CellRendererText -> tm ->\n\t\t\t (TreeIter -> String -> IO ()) ->\n\t\t\t IO (ConnectId CellRendererText)\nonEdited cr tm user = connect_PTR_STRING__NONE \"edited\" False cr $\n \\strPtr string ->\n mallocTreeIter >>= \\iter ->\n {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iter\n strPtr\n >>= \\res -> if toBool res then user iter string else\n putStrLn \"edited signal: invalid tree path\"\n\nafterEdited cr tm user = connect_PTR_STRING__NONE \"edited\" True cr $\n \\strPtr string ->\n mallocTreeIter >>= \\iter ->\n {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iter\n strPtr\n >>= \\res -> if toBool res then user iter string else\n putStrLn \"edited signal: invalid tree path\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1ca662f2faa3c789d75f7e9d34a37b9c5d858a28","subject":"Fix documentation error.","message":"Fix documentation error.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Window.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Window.chs","new_contents":"{-# LANGUAGE CPP, UndecidableInstances, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ExistentialQuantification #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.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 -- * 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.Widget\n\nimport C2HS hiding (cFromEnum, toBool,cToEnum,cToBool)\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 Widget) => 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 Window) =>\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 Window) => CustomWindowFuncs a\ndefaultCustomWindowFuncs = CustomWindowFuncs Nothing\n\n{# fun Fl_Window_default_virtual_funcs as virtualFuncs' {} -> `Ptr ()' id #}\nwindowMaker :: forall a b. (Parent a Window, Parent b Widget) =>\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 -> T.Text -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> T.Text -> 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 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')) -> customXYWithLabel' x y w h l' p >>= toRef\n (Nothing, (Just l')) -> customWithLabel' w h l' p >>= toRef\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',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_New_WithLabel as overriddenWindowNewWithLabel' { `Int',`Int', unsafeToCString `T.Text', 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 ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n\n{# fun Fl_Window_draw_super as drawSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (DrawSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> drawSuper' windowPtr\n\n{# fun Fl_Window_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (HandleSuper ()) Window orig impl where\n runOp _ _ window event = withRef window $ \\windowPtr -> handleSuper' windowPtr (fromIntegral (fromEnum event)) >>= return . successOrUnknownEvent\n\n{# fun Fl_Window_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (ResizeSuper ()) Window orig impl where\n runOp _ _ window rectangle =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in withRef window $ \\windowPtr -> resizeSuper' windowPtr x_pos y_pos width height\n\n{# fun Fl_Window_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (ShowWidgetSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> showSuper' windowPtr\n\n{# fun Fl_Window_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (HideSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hideSuper' windowPtr\n\n{# fun Fl_Window_flush_super as flushSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (FlushSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> flushSuper' windowPtr\n\n{# fun Fl_Window_show as windowShow' {id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) Window orig impl where\n runOp _ _ window = withRef window (\\p -> windowShow' p)\n\n{#fun Fl_Window_handle as windowHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) Window orig impl where\n runOp _ _ window event = withRef window (\\p -> windowHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n{# fun Fl_Window_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) Window 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\n{# fun Fl_Window_set_callback as windowSetCallback' {id `Ptr ()' , id `FunPtr CallbackWithUserDataPrim'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ ((Ref orig -> IO ()) -> IO ())) => Op (SetCallback ()) Window orig impl where\n runOp _ _ window callback =\n withRef window $ (\\p -> do\n callbackPtr <- toCallbackPrimWithUserData callback\n windowSetCallback' (castPtr p) callbackPtr)\n\n{# fun Fl_Window_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hide' windowPtr\n\n{# fun Fl_Window_changed as changed' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (Changed ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ~ (Int -> Int -> IO ())) => Op (SizeRange ()) Window orig impl where\n runOp _ _ win minw' minh' =\n withRef win $ \\winPtr -> sizeRange' winPtr minw' minh'\ninstance (impl ~ (Int -> Int -> OptionalSizeRangeArgs -> IO ())) => Op (SizeRangeWithArgs ()) Window orig impl where\n runOp _ _ win minw' 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 ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ ( IO T.Text)) => Op (GetLabel ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> label' winPtr\n\n{# fun Fl_Window_iconlabel as iconlabel' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ ( IO T.Text)) => Op (GetIconlabel ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> iconlabel' winPtr\n\n{# fun Fl_Window_set_label as setLabel' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetLabel ()) Window orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> setLabel' winPtr l'\n\n{# fun Fl_Window_set_iconlabel as setIconlabel' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetIconlabel ()) Window orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> setIconlabel' winPtr l'\n\n{# fun Fl_Window_set_label_with_iconlabel as setLabelWithIconlabel' { id `Ptr ()',unsafeToCString `T.Text',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> T.Text -> IO ())) => Op (SetLabelWithIconlabel ()) Window orig impl where\n runOp _ _ win label iconlabel = withRef win $ \\winPtr -> setLabelWithIconlabel' winPtr label iconlabel\n\n{# fun Fl_Window_copy_label as copyLabel' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (CopyLabel ()) Window orig impl where\n runOp _ _ win a = withRef win $ \\winPtr -> copyLabel' winPtr a\n\n{# fun Fl_Window_xclass as xclass' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ ( IO T.Text)) => Op (GetXclass ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xclass' winPtr\n\n{# fun Fl_Window_set_xclass as setXclass' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetXclass ()) Window orig impl where\n runOp _ _ win c = withRef win $ \\winPtr -> setXclass' winPtr c\n\n{# fun Fl_Window_icon as icon' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Image)))) => Op (GetIcon ()) Window 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 Image, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetIcon ()) Window 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 ()) Window 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 ()) Window 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 (Int))) => Op (GetXRoot ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xRoot' winPtr\n\n{# fun Fl_Window_y_root as yRoot' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetYRoot ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> yRoot' winPtr\n\n{# fun Fl_Window_current as current' { } -> `Ptr ()' id #}\ncurrentWindow :: (Parent a Window) => IO (Ref a)\ncurrentWindow = current' >>= toRef\n\n{# fun Fl_Window_make_current as makeCurrent' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeCurrent ()) Window 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 ()) Window orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setCursor' winPtr cursor\ninstance (impl ~ (Cursor -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetCursorWithFgBg ()) Window 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 ()) Window orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setDefaultCursor' winPtr cursor\ninstance (impl ~ (CursorType -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetDefaultCursorWithFgBg ()) Window 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 ()) Window 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 ()) Window 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 ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> windowDrawBox' windowPtr\ninstance (impl ~ (Boxtype -> Color -> Maybe Rectangle -> IO ())) => Op (DrawBoxWithBoxtype ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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_ ()) Window orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr >>= return . toEnum . fromInteger . toInteger\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Window\"\n-- @\n\n-- $functions\n-- @\n-- changed :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- clearBorder :: 'Ref' 'Window' -> 'IO' ()\n--\n-- copyLabel :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'Window' -> 'IO' ()\n--\n-- drawBackdrop :: 'Ref' 'Window' -> 'IO' ()\n--\n-- drawBox :: 'Ref' 'Window' -> 'IO' ()\n--\n-- drawBoxWithBoxtype :: 'Ref' 'Window' -> 'Boxtype' -> 'Color' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- drawFocus :: 'Ref' 'Window' -> 'Maybe' ('Boxtype', 'Rectangle') -> 'IO' ()\n--\n-- drawSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- flushSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- freePosition :: 'Ref' 'Window' -> 'IO' ()\n--\n-- fullscreenOff :: 'Ref' 'Window' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- getBorder :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getDecoratedH :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- getDecoratedW :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- getIcon :: 'Ref' 'Window' -> 'IO' ('Maybe' ('Ref' 'Image'))\n--\n-- getIconlabel :: 'Ref' 'Window' -> 'IO' 'T.Text'\n--\n-- getLabel :: 'Ref' 'Window' -> 'IO' 'T.Text'\n--\n-- getMenuWindow :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getModal :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getOverride :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getTooltipWindow :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getType_ :: 'Ref' 'Window' -> 'IO' ('WindowType')\n--\n-- getXRoot :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- getXclass :: 'Ref' 'Window' -> 'IO' 'T.Text'\n--\n-- getYRoot :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- handle :: 'Ref' 'Window' -> ('Event' -> 'IO' ('Either' 'UnknownEvent' ()))\n--\n-- handleSuper :: 'Ref' 'Window' -> 'Event' -> 'IO' ('Int')\n--\n-- hide :: 'Ref' 'Window' -> 'IO' ()\n--\n-- hideSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- hotSpot :: 'Ref' 'Window' -> 'PositionSpec' -> 'Maybe' 'Bool' -> 'IO' ()\n--\n-- iconize :: 'Ref' 'Window' -> 'IO' ()\n--\n-- makeCurrent :: 'Ref' 'Window' -> 'IO' ()\n--\n-- makeFullscreen :: 'Ref' 'Window' -> 'IO' ()\n--\n-- nonModal :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- resize :: 'Ref' 'Window' -> 'Rectangle' -> 'IO' ()\n--\n-- resizeSuper :: 'Ref' 'Window' -> 'Rectangle' -> 'IO' ()\n--\n-- setBorder :: 'Ref' 'Window' -> 'Bool' -> 'IO' ()\n--\n-- setCallback :: 'Ref' 'Window' -> ('Ref' orig -> 'IO' ()) -> 'IO' ()\n--\n-- setCursor :: 'Ref' 'Window' -> 'Cursor' -> 'IO' ()\n--\n-- setCursorWithFgBg :: 'Ref' 'Window' -> 'Cursor' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setDefaultCursor :: 'Ref' 'Window' -> 'CursorType' -> 'IO' ()\n--\n-- setDefaultCursorWithFgBg :: 'Ref' 'Window' -> 'CursorType' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setIcon:: ('Parent' a 'Image') => 'Ref' 'Window' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setIconlabel :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- setLabel :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- setLabelWithIconlabel :: 'Ref' 'Window' -> 'T.Text' -> 'T.Text' -> 'IO' ()\n--\n-- setMenuWindow :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setModal :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setNonModal :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setOverride :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setTooltipWindow :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setType :: 'Ref' 'Window' -> 'WindowType' -> 'IO' ()\n--\n-- setXclass :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'Window' -> 'IO' ()\n--\n-- showWidgetSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- shown :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- sizeRange :: 'Ref' 'Window' -> 'Int' -> 'Int' -> 'IO' ()\n--\n-- sizeRangeWithArgs :: 'Ref' 'Window' -> 'Int' -> 'Int' -> 'OptionalSizeRangeArgs' -> 'IO' ()\n--\n-- waitForExpose :: 'Ref' 'Window' -> 'IO' ()\n-- @\n","old_contents":"{-# LANGUAGE CPP, UndecidableInstances, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ExistentialQuantification #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.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 -- * 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.Widget\n\nimport C2HS hiding (cFromEnum, toBool,cToEnum,cToBool)\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 Widget) => 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 Window) =>\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 Window) => CustomWindowFuncs a\ndefaultCustomWindowFuncs = CustomWindowFuncs Nothing\n\n{# fun Fl_Window_default_virtual_funcs as virtualFuncs' {} -> `Ptr ()' id #}\nwindowMaker :: forall a b. (Parent a Window, Parent b Widget) =>\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 -> T.Text -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> T.Text -> 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 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')) -> customXYWithLabel' x y w h l' p >>= toRef\n (Nothing, (Just l')) -> customWithLabel' w h l' p >>= toRef\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',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_New_WithLabel as overriddenWindowNewWithLabel' { `Int',`Int', unsafeToCString `T.Text', 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 ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n\n{# fun Fl_Window_draw_super as drawSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (DrawSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> drawSuper' windowPtr\n\n{# fun Fl_Window_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (HandleSuper ()) Window orig impl where\n runOp _ _ window event = withRef window $ \\windowPtr -> handleSuper' windowPtr (fromIntegral (fromEnum event)) >>= return . successOrUnknownEvent\n\n{# fun Fl_Window_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (ResizeSuper ()) Window orig impl where\n runOp _ _ window rectangle =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in withRef window $ \\windowPtr -> resizeSuper' windowPtr x_pos y_pos width height\n\n{# fun Fl_Window_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (ShowWidgetSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> showSuper' windowPtr\n\n{# fun Fl_Window_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (HideSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hideSuper' windowPtr\n\n{# fun Fl_Window_flush_super as flushSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (FlushSuper ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> flushSuper' windowPtr\n\n{# fun Fl_Window_show as windowShow' {id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) Window orig impl where\n runOp _ _ window = withRef window (\\p -> windowShow' p)\n\n{#fun Fl_Window_handle as windowHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) Window orig impl where\n runOp _ _ window event = withRef window (\\p -> windowHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n{# fun Fl_Window_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) Window 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\n{# fun Fl_Window_set_callback as windowSetCallback' {id `Ptr ()' , id `FunPtr CallbackWithUserDataPrim'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ ((Ref orig -> IO ()) -> IO ())) => Op (SetCallback ()) Window orig impl where\n runOp _ _ window callback =\n withRef window $ (\\p -> do\n callbackPtr <- toCallbackPrimWithUserData callback\n windowSetCallback' (castPtr p) callbackPtr)\n\n{# fun Fl_Window_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hide' windowPtr\n\n{# fun Fl_Window_changed as changed' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (Changed ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ~ (Int -> Int -> IO ())) => Op (SizeRange ()) Window orig impl where\n runOp _ _ win minw' minh' =\n withRef win $ \\winPtr -> sizeRange' winPtr minw' minh'\ninstance (impl ~ (Int -> Int -> OptionalSizeRangeArgs -> IO ())) => Op (SizeRangeWithArgs ()) Window orig impl where\n runOp _ _ win minw' 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 ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ ( IO T.Text)) => Op (GetLabel ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> label' winPtr\n\n{# fun Fl_Window_iconlabel as iconlabel' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ ( IO T.Text)) => Op (GetIconlabel ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> iconlabel' winPtr\n\n{# fun Fl_Window_set_label as setLabel' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetLabel ()) Window orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> setLabel' winPtr l'\n\n{# fun Fl_Window_set_iconlabel as setIconlabel' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetIconlabel ()) Window orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> setIconlabel' winPtr l'\n\n{# fun Fl_Window_set_label_with_iconlabel as setLabelWithIconlabel' { id `Ptr ()',unsafeToCString `T.Text',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> T.Text -> IO ())) => Op (SetLabelWithIconlabel ()) Window orig impl where\n runOp _ _ win label iconlabel = withRef win $ \\winPtr -> setLabelWithIconlabel' winPtr label iconlabel\n\n{# fun Fl_Window_copy_label as copyLabel' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (CopyLabel ()) Window orig impl where\n runOp _ _ win a = withRef win $ \\winPtr -> copyLabel' winPtr a\n\n{# fun Fl_Window_xclass as xclass' { id `Ptr ()' } -> `T.Text' unsafeFromCString #}\ninstance (impl ~ ( IO T.Text)) => Op (GetXclass ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xclass' winPtr\n\n{# fun Fl_Window_set_xclass as setXclass' { id `Ptr ()',unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetXclass ()) Window orig impl where\n runOp _ _ win c = withRef win $ \\winPtr -> setXclass' winPtr c\n\n{# fun Fl_Window_icon as icon' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Image)))) => Op (GetIcon ()) Window 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 Image, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetIcon ()) Window 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 ()) Window 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 ()) Window 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 (Int))) => Op (GetXRoot ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xRoot' winPtr\n\n{# fun Fl_Window_y_root as yRoot' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetYRoot ()) Window orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> yRoot' winPtr\n\n{# fun Fl_Window_current as current' { } -> `Ptr ()' id #}\ncurrentWindow :: (Parent a Window) => IO (Ref a)\ncurrentWindow = current' >>= toRef\n\n{# fun Fl_Window_make_current as makeCurrent' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeCurrent ()) Window 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 ()) Window orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setCursor' winPtr cursor\ninstance (impl ~ (Cursor -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetCursorWithFgBg ()) Window 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 ()) Window orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setDefaultCursor' winPtr cursor\ninstance (impl ~ (CursorType -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetDefaultCursorWithFgBg ()) Window 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 ()) Window 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 ()) Window 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 ()) Window orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> windowDrawBox' windowPtr\ninstance (impl ~ (Boxtype -> Color -> Maybe Rectangle -> IO ())) => Op (DrawBoxWithBoxtype ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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 ()) Window 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_ ()) Window orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr >>= return . toEnum . fromInteger . toInteger\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Window\"\n-- @\n\n-- $functions\n-- @\n-- changed :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- clearBorder :: 'Ref' 'Window' -> 'IO' ()\n--\n-- copyLabel :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'Window' -> 'IO' ()\n--\n-- drawBackdrop :: 'Ref' 'Window' -> 'IO' ()\n--\n-- drawBox :: 'Ref' 'Window' -> 'IO' ()\n--\n-- drawBoxWithBoxtype :: 'Ref' 'Window' -> 'Boxtype' -> 'Color' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- drawFocus :: 'Ref' 'Window' -> 'Maybe' ('Boxtype', 'Rectangle') -> 'IO' ()\n--\n-- drawSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- flushSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- freePosition :: 'Ref' 'Window' -> 'IO' ()\n--\n-- fullscreenOff :: 'Ref' 'Window' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- getBorder :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getDecoratedH :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- getDecoratedW :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- getIcon :: 'Ref' 'Window' -> 'IO' ('Maybe' ('Ref' 'Image'))\n--\n-- getIconlabel :: 'Ref' 'Window' -> 'IO' 'T.Text'\n--\n-- getLabel :: 'Ref' 'Window' -> 'IO' 'T.Text'\n--\n-- getMenuWindow :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getModal :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getOverride :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getTooltipWindow :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- getType_ :: 'Ref' 'Window' -> 'IO' ('WindowType')\n--\n-- getXRoot :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- getXclass :: 'Ref' 'Window' -> 'IO' 'T.Text'\n--\n-- getYRoot :: 'Ref' 'Window' -> 'IO' ('Int')\n--\n-- handle :: 'Ref' 'Window' -> ('Event' -> 'IO' ('Either' 'UnknownEvent' ()))\n--\n-- handleSuper :: 'Ref' 'Window' -> 'Event' -> 'IO' ('Int')\n--\n-- hide :: 'Ref' 'Window' -> 'IO' ()\n--\n-- hideSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- hotSpot :: 'Ref' 'Window' -> 'PositionSpec' -> 'Maybe' 'Bool' -> 'IO' ()\n--\n-- iconize :: 'Ref' 'Window' -> 'IO' ()\n--\n-- makeCurrent :: 'Ref' 'Window' -> 'IO' ()\n--\n-- makeFullscreen :: 'Ref' 'Window' -> 'IO' ()\n--\n-- nonModal :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- resize :: 'Ref' 'Window' -> 'Rectangle' -> 'IO' ()\n--\n-- resizeSuper :: 'Ref' 'Window' -> 'Rectangle' -> 'IO' ()\n--\n-- setBorder :: 'Ref' 'Window' -> 'Bool' -> 'IO' ()\n--\n-- setCallback :: 'Ref' 'Window' -> ('Ref' orig -> 'IO' ()) -> 'IO' ()\n--\n-- setCursor :: 'Ref' 'Window' -> 'Cursor' -> 'IO' ()\n--\n-- setCursorWithFgBg :: 'Ref' 'Window' -> 'Cursor' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setDefaultCursor :: 'Ref' 'Window' -> 'CursorType' -> 'IO' ()\n--\n-- setDefaultCursorWithFgBg :: 'Ref' 'Window' -> 'CursorType' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setIcon:: ('Parent' a 'Image') => 'Ref' 'Window' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setIconlabel :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- setLabel :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- setLabelWithIconlabel :: 'Ref' 'Window' -> 'T.Text' -> 'T.Text' -> 'IO' ()\n--\n-- setMenuWindow :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setModal :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setNonModal :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setOverride :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setTooltipWindow :: 'Ref' 'Window' -> 'IO' ()\n--\n-- setType :: 'Ref' 'Window' -> 'WindowType' -> 'IO' ()\n--\n-- setXclass :: 'Ref' 'Window' -> 'T.Text' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'Window' -> 'IO' ()\n--\n-- showWidgetSuper :: 'Ref' 'Window' -> 'IO' ()\n--\n-- shown :: 'Ref' 'Window' -> 'IO' ('Bool')\n--\n-- sizeRange :: 'Ref' 'Window' -> 'Int' -> 'Int' -> 'IO' ()\n--\n-- sizeRangeWithArgs :: 'Ref' 'Window' -> 'Int' -> 'Int' -> 'OptionalSizeRangeArgs' -> 'IO' ()\n--\n-- waitForExpose :: 'Ref' 'Window' -> 'IO' ()\n\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"78cb6ccd71ef847ef03a3763f91ecc3959e79302","subject":"Fixed compatability with opencv23 in CV.Transforms","message":"Fixed compatability with opencv23 in CV.Transforms\n","repos":"aleator\/CV,aleator\/CV,TomMD\/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 as I \nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\nimport qualified CV.Matrix as M\nimport CV.Matrix (Matrix,withMatPtr)\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 cl <- I.create (getSize 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 target <- I.create (getSize 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 <- I.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 <- I.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#c\nenum HomographyMethod {\n Default = 0,\n Ransac = CV_RANSAC,\n LMeds = CV_LMEDS\n };\n#endc\n{#enum HomographyMethod {}#}\n\ngetHomography' :: Matrix Float -> Matrix Float -> HomographyMethod -> Float -> Matrix Float\ngetHomography' srcPts dstPts method ransacThreshold = \n unsafePerformIO $ do\n hmg <- M.create (3,3) :: IO (Matrix Float)\n withMatPtr srcPts $\u00a0\\c_src ->\n withMatPtr dstPts $\u00a0\\c_dst ->\n withMatPtr hmg $\u00a0\\c_hmg -> do\n {#call cvFindHomography#} \n (castPtr c_src) \n (castPtr c_dst) \n (castPtr c_hmg)\n (fromIntegral $ fromEnum method)\n (realToFrac ransacThreshold)\n nullPtr\n return hmg\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 <- I.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 <- I.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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- 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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n CCOMP = CV_DIST_LABEL_CCOMP\n ,PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\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 <- I.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#ifdef OpenCV24\n (fromIntegral . fromEnum $ CCOMP)\n#endif\n\n return result\n\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 as I \nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\nimport qualified CV.Matrix as M\nimport CV.Matrix (Matrix,withMatPtr)\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 cl <- I.create (getSize 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 target <- I.create (getSize 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 <- I.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 <- I.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#c\nenum HomographyMethod {\n Default = 0,\n Ransac = CV_RANSAC,\n LMeds = CV_LMEDS\n };\n#endc\n{#enum HomographyMethod {}#}\n\ngetHomography' :: Matrix Float -> Matrix Float -> HomographyMethod -> Float -> Matrix Float\ngetHomography' srcPts dstPts method ransacThreshold = \n unsafePerformIO $ do\n hmg <- M.create (3,3) :: IO (Matrix Float)\n withMatPtr srcPts $\u00a0\\c_src ->\n withMatPtr dstPts $\u00a0\\c_dst ->\n withMatPtr hmg $\u00a0\\c_hmg -> do\n {#call cvFindHomography#} \n (castPtr c_src) \n (castPtr c_dst) \n (castPtr c_hmg)\n (fromIntegral $ fromEnum method)\n (realToFrac ransacThreshold)\n nullPtr\n return hmg\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 <- I.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 <- I.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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- 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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#c\nenum LabelType {\n CCOMP = CV_DIST_LABEL_CCOMP\n ,PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n\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 <- I.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 (fromIntegral . fromEnum $ CCOMP)\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":"9f287c9b50adcefd450727472555b57bb92a0c86","subject":"Document the Matrix representation","message":"Document the Matrix representation\n\ndarcs-hash:20060505180256-b4c10-c2ffbad6e77f939bf6ca9120b04bbdfeb4dfa589.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"6d28f1769973220c6f390edf43de3d28329986ca","subject":"Add function sourceCompletionProviderMatch","message":"Add function sourceCompletionProviderMatch\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderGetActivation,\n sourceCompletionProviderMatch,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.SourceView.Enums\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Get with what kind of activation the provider should be activated.\nsourceCompletionProviderGetActivation :: SourceCompletionProviderClass scp => scp\n -> IO SourceCompletionActivation\nsourceCompletionProviderGetActivation scp =\n liftM (toEnum . fromIntegral) $\n {#call gtk_source_completion_provider_get_activation #}\n (toSourceCompletionProvider scp)\n\n-- | Get whether the provider match the context of completion detailed in context.\nsourceCompletionProviderMatch :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO Bool -- ^ returns 'True' if provider matches the completion context, 'False' otherwise\nsourceCompletionProviderMatch scp context =\n liftM toBool $\n {#call gtk_source_completion_provider_match #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderGetActivation,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.SourceView.Enums\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Get with what kind of activation the provider should be activated.\nsourceCompletionProviderGetActivation :: SourceCompletionProviderClass scp => scp\n -> IO SourceCompletionActivation\nsourceCompletionProviderGetActivation scp =\n liftM (toEnum . fromIntegral) $\n {#call gtk_source_completion_provider_get_activation #}\n (toSourceCompletionProvider scp)\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"973006940378b6ffd0400235004702fd66b81612","subject":"mutex is not neccesary in gdal 2","message":"mutex is not neccesary in gdal 2\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.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\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 = 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 (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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"036928267ca2e1a21a3d650d0c06092621af518b","subject":"expose Types and flags constructors in System.GIO.File","message":"expose Types and flags constructors in System.GIO.File","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-- \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":"321f65bbd1dd4535ddd3814da10ee13548f3273d","subject":"also export the valid JIT targets","message":"also export the valid JIT targets\n\nIgnore-this: 5074242ec851e527bafbf386507e98ab\n\ndarcs-hash:20091216083032-9241b-54ebdffbfc51d286d12f1025403011643ffe2d0c.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 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, loadFile, loadData, loadDataEx, unload\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.Exec\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-- 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 where peekMod = liftM Module . peek\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 , useBS* `ByteString' } -> ` Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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 , useBS* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) 2009 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(..), JITResult(..),\n getFun, loadFile, loadData, loadDataEx, unload\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.Exec\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-- 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 where peekMod = liftM Module . peek\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 , useBS* `ByteString' } -> ` Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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 , useBS* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"fb9ecf43d3641eacc5b2a2e1aa3e634ccd528178","subject":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO","message":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,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 ) 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\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\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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b8e9aaa8cda1619acab3c9b0e9dbd98f881ce36b","subject":"Add missing type","message":"Add missing type\n","repos":"gtk2hs\/gtk-mac-integration,gtk2hs\/gtk-mac-integration","old_file":"Graphics\/UI\/Gtk\/OSX\/Window.chs","new_file":"Graphics\/UI\/Gtk\/OSX\/Window.chs","new_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.Gtk.OSX.Window (\n allowFullscreen\n) where\n\nimport System.Glib.FFI\n{#import Graphics.UI.Gtk.OSX.Types#}\n\nallowFullscreen :: DrawWindowClass window => window -> IO ()\nallowFullscreen window =\n {# call unsafe gtk2hs_osx_allow_fullscreen #}\n (toDrawWindow window)\n\n","old_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.Gtk.OSX.Window (\n allowFullscreen\n) where\n\nimport System.Glib.FFI\n{#import Graphics.UI.Gtk.OSX.Types#}\n\nallowFullscreen window =\n {# call unsafe gtk2hs_osx_allow_fullscreen #}\n (toDrawWindow window)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"87cc1ef2a7fae48cce50d10faca3450f3db342dd","subject":"[project @ 2002-10-20 14:29:26 by as49] Documentation fixes.","message":"[project @ 2002-10-20 14:29:26 by as49]\nDocumentation fixes.\n","repos":"vincenthz\/webkit","old_file":"gtk\/gdk\/Drawable.chs","new_file":"gtk\/gdk\/Drawable.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Drawable@\n--\n-- Author : Axel Simon\n-- Created: 22 September 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/10\/20 14:29:26 $\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-- Drawing primitives.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This module defines drawing primitives that can operate on \n-- @ref data DrawWindow@s, @ref data Pixmap@s and \n-- @ref data Bitmap@s.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if gdk_visuals are implemented, do: get_visual\n-- * if gdk_colormaps are implemented, do: set_colormap, get_colormap\n-- * text drawing functions\n--\nmodule Drawable(\n Drawable,\n DrawableClass,\n castToDrawable,\n drawableGetDepth,\n drawableGetSize,\n drawableGetClipRegion,\n drawableGetVisibleRegion,\n drawPoint,\n drawPoints,\n drawLine,\n drawLines,\n drawSegments,\n drawRectangle,\n drawArc,\n drawPolygon,\n drawDrawable) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport GObject\t(makeNewGObject)\nimport Structs (Point)\n{#import Hierarchy#}\n{#import Region#}\t(Region, makeNewRegion)\n\n{# context lib=\"gtk\" prefix=\"gdk\" #}\n\n-- methods\n\n-- @method drawableGetDepth@ Get the size of pixels.\n--\n-- * Returns the number of bits which are use to store information on each\n-- pixels in this @ref data Drawable@.\n--\ndrawableGetDepth :: DrawableClass d => d -> IO Int\ndrawableGetDepth d = liftM fromIntegral $ \n\t\t {#call unsafe drawable_get_depth#} (toDrawable d)\n\n-- @method drawableGetSize@ Retrieve the size of the @ref type Drawable@.\n--\n-- * The result might not be up-to-date if there are still resizing messages\n-- to be processed.\n--\ndrawableGetSize :: DrawableClass d => d -> IO (Int, Int)\ndrawableGetSize d = alloca $ \\wPtr -> alloca $ \\hPtr -> do\n {#call unsafe drawable_get_size#} (toDrawable d) wPtr hPtr\n (w::{#type gint#}) <- peek wPtr\n (h::{#type gint#}) <- peek hPtr\n return (fromIntegral w, fromIntegral h)\n\n-- @method drawableGetClipRegion@ Determine where not to draw.\n--\n-- * Computes the region of a drawable that potentially can be written\n-- to by drawing primitives. This region will not take into account the\n-- clip region for the GC, and may also not take into account other\n-- factors such as if the window is obscured by other windows, but no\n-- area outside of this region will be affected by drawing primitives.\n--\ndrawableGetClipRegion :: DrawableClass d => d -> IO Region\ndrawableGetClipRegion d = do\n rPtr <- {#call unsafe drawable_get_clip_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawableGetVisibleRegion@ Determine what not to redraw.\n--\n-- * Computes the region of a drawable that is potentially visible.\n-- This does not necessarily take into account if the window is obscured\n-- by other windows, but no area outside of this region is visible.\n--\ndrawableGetVisibleRegion :: DrawableClass d => d -> IO Region\ndrawableGetVisibleRegion d = do\n rPtr <- {#call unsafe drawable_get_visible_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawPoint@ Draw a point into a @ref type Drawable@.\n--\ndrawPoint :: DrawableClass d => d -> GC -> Point -> IO ()\ndrawPoint d gc (x,y) = {#call unsafe draw_point#} (toDrawable d)\n (toGC gc) (fromIntegral x) (fromIntegral y)\n\n\n-- @method drawPoints@ Draw several points into a @ref type Drawable@.\n--\n-- * This function is more efficient than calling @ref method drawPoint@ on\n-- several points.\n--\ndrawPoints :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawPoints d gc points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_points#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawLine@ Draw a line into a @ref type Drawable@.\n--\n-- * The parameters are x1, y1, x2, y2.\n--\n-- * Drawing several separate lines can be done more efficiently by\n-- @ref method drawSegments@.\n--\ndrawLine :: DrawableClass d => d -> GC -> Point -> Point -> IO ()\ndrawLine d gc (x1,y1) (x2,y2) = {#call unsafe draw_line#} (toDrawable d)\n (toGC gc) (fromIntegral x1) (fromIntegral y1) (fromIntegral x2) \n (fromIntegral x2)\n\n-- @method drawLines@ Draw several lines.\n--\n-- * The function uses the current line width, dashing and especially the\n-- joining specification in the graphics context (in contrast to\n-- @ref method drawSegments@.\n--\ndrawLines :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawLines d gc points =\n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_lines#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawSegments@ Draw several unconnected lines.\n--\n-- * This method draws several unrelated lines.\n--\ndrawSegments :: DrawableClass d => d -> GC -> [(Point,Point)] -> IO ()\ndrawSegments d gc pps = withArray (concatMap (\\((x1,y1),(x2,y2)) -> \n [fromIntegral x1, fromIntegral y1, fromIntegral x2, fromIntegral y2])\n pps) $ \\(aPtr :: Ptr {#type gint#}) ->\n {#call unsafe draw_segments#} (toDrawable d) (toGC gc)\n (castPtr aPtr) (fromIntegral (length pps))\n\n-- @method drawRectangle@ Draw a rectangular object.\n--\n-- * Draws a rectangular outline or filled rectangle, using the\n-- foreground color and other attributes of the @ref type GC@.\n--\n-- * A rectangle drawn filled is 1 pixel smaller in both dimensions\n-- than a rectangle outlined. Calling @ref method drawRectangle@ w gc\n-- True 0 0 20 20 results in a filled rectangle 20 pixels wide and 20\n-- pixels high. Calling @ref method drawRectangle@ d gc False 0 0 20 20\n-- results in an outlined rectangle with corners at (0, 0), (0, 20), (20,\n-- 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.\n--\ndrawRectangle :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> IO ()\ndrawRectangle d gc filled x y width height = {#call unsafe draw_rectangle#}\n (toDrawable d) (toGC gc) (fromBool filled) (fromIntegral x)\n (fromIntegral y) (fromIntegral width) (fromIntegral height)\n\n-- @method drawArc@ Draws an arc or a filled 'pie slice'.\n--\n-- * The arc is defined by the bounding rectangle of the entire\n-- ellipse, and the start and end angles of the part of the ellipse to be\n-- drawn.\n--\n-- * The starting angle @ref arg aStart@ is relative to the 3 o'clock\n-- position, counter-clockwise, in 1\/64ths of a degree. @ref arg aEnd@\n-- is measured similarly, but relative to @ref arg aStart@.\n--\ndrawArc :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> Int -> Int -> IO ()\ndrawArc d gc filled x y width height aStart aEnd =\n {#call unsafe draw_arc#} (toDrawable d) (toGC gc) (fromBool filled)\n (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)\n (fromIntegral aStart) (fromIntegral aEnd)\n\n-- @method drawPolygon@ Draws an outlined or filled polygon.\n--\n-- * The polygon is closed automatically, connecting the last point to\n-- the first point if necessary.\n--\ndrawPolygon :: DrawableClass d => d -> GC -> Bool -> [Point] -> IO ()\ndrawPolygon d gc filled points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr::Ptr {#type gint#}) -> {#call unsafe draw_polygon#} (toDrawable d)\n (toGC gc) (fromBool filled) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawDrawable@ Copies another @ref type Drawable@.\n--\n-- * Copies the (width,height) region of the @ref arg src@ at coordinates\n-- (@ref arg xSrc@, @ref arg ySrc@) to coordinates (@ref arg xDest@,\n-- @ref arg yDest@) in the @ref arg dest@. The @ref arg width@ and\/or\n-- @ref arg height@ may be given as -1, in which case the entire source\n-- drawable will be copied.\n--\n-- * Most fields in @ref arg gc@ are not used for this operation, but\n-- notably the clip mask or clip region will be honored. The source and\n-- destination drawables must have the same visual and colormap, or\n-- errors will result. (On X11, failure to match visual\/colormap results\n-- in a BadMatch error from the X server.) A common cause of this\n-- problem is an attempt to draw a bitmap to a color drawable. The way to\n-- draw a bitmap is to set the bitmap as a clip mask on your\n-- @ref type GC@, then use @ref method drawRectangle@ to draw a \n-- rectangle clipped to the bitmap.\n--\ndrawDrawable :: (DrawableClass src, DrawableClass dest) => \n\t\tdest -> GC -> src -> Int -> Int -> Int -> Int -> \n\t\tInt -> Int -> IO ()\ndrawDrawable dest gc src xSrc ySrc xDest yDest width height =\n {#call unsafe draw_drawable#} (toDrawable dest) (toGC gc)\n (toDrawable src)\n (fromIntegral xSrc) (fromIntegral ySrc) (fromIntegral xDest)\n (fromIntegral yDest) (fromIntegral width) (fromIntegral height)\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Drawable@\n--\n-- Author : Axel Simon\n-- Created: 22 September 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2002\/10\/06 16:14:07 $\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-- Drawing primitives.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This module defines drawing primitives that can operate on \n-- @ref object DrawWindow@s, @ref object Pixmap@s and \n-- @ref object Bitmap@s.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if gdk_visuals are implemented, do: get_visual\n-- * if gdk_colormaps are implemented, do: set_colormap, get_colormap\n-- * text drawing functions\n--\nmodule Drawable(\n Drawable,\n DrawableClass,\n castToDrawable,\n drawableGetDepth,\n drawableGetSize,\n drawableGetClipRegion,\n drawableGetVisibleRegion,\n drawPoint,\n drawPoints,\n drawLine,\n drawLines,\n drawSegments,\n drawRectangle,\n drawArc,\n drawPolygon,\n drawDrawable) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport GObject\t(makeNewGObject)\nimport Structs (Point)\n{#import Hierarchy#}\n{#import Region#}\t(Region, makeNewRegion)\n\n{# context lib=\"gtk\" prefix=\"gdk\" #}\n\n-- methods\n\n-- @method drawableGetDepth@ Get the size of pixels.\n--\n-- * Returns the number of bits which are use to store information on each\n-- pixels in this @ref object Drawable@.\n--\ndrawableGetDepth :: DrawableClass d => d -> IO Int\ndrawableGetDepth d = liftM fromIntegral $ \n\t\t {#call unsafe drawable_get_depth#} (toDrawable d)\n\n-- @method drawableGetSize@ Retrieve the size of the @ref type Drawable@.\n--\n-- * The result might not be up-to-date if there are still resizing messages\n-- to be processed.\n--\ndrawableGetSize :: DrawableClass d => d -> IO (Int, Int)\ndrawableGetSize d = alloca $ \\wPtr -> alloca $ \\hPtr -> do\n {#call unsafe drawable_get_size#} (toDrawable d) wPtr hPtr\n (w::{#type gint#}) <- peek wPtr\n (h::{#type gint#}) <- peek hPtr\n return (fromIntegral w, fromIntegral h)\n\n-- @method drawableGetClipRegion@ Determine where not to draw.\n--\n-- * Computes the region of a drawable that potentially can be written\n-- to by drawing primitives. This region will not take into account the\n-- clip region for the GC, and may also not take into account other\n-- factors such as if the window is obscured by other windows, but no\n-- area outside of this region will be affected by drawing primitives.\n--\ndrawableGetClipRegion :: DrawableClass d => d -> IO Region\ndrawableGetClipRegion d = do\n rPtr <- {#call unsafe drawable_get_clip_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawableGetVisibleRegion@ Determine what not to redraw.\n--\n-- * Computes the region of a drawable that is potentially visible.\n-- This does not necessarily take into account if the window is obscured\n-- by other windows, but no area outside of this region is visible.\n--\ndrawableGetVisibleRegion :: DrawableClass d => d -> IO Region\ndrawableGetVisibleRegion d = do\n rPtr <- {#call unsafe drawable_get_visible_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawPoint@ Draw a point into a @ref type Drawable@.\n--\ndrawPoint :: DrawableClass d => d -> GC -> Point -> IO ()\ndrawPoint d gc (x,y) = {#call unsafe draw_point#} (toDrawable d)\n (toGC gc) (fromIntegral x) (fromIntegral y)\n\n\n-- @method drawPoints@ Draw several points into a @ref type Drawable@.\n--\n-- * This function is more efficient than calling @ref method drawPoint@ on\n-- several points.\n--\ndrawPoints :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawPoints d gc points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_points#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawLine@ Draw a line into a @ref type Drawable@.\n--\n-- * The parameters are x1, y1, x2, y2.\n--\n-- * Drawing several separate lines can be done more efficiently by\n-- @ref method drawSegments@.\n--\ndrawLine :: DrawableClass d => d -> GC -> Point -> Point -> IO ()\ndrawLine d gc (x1,y1) (x2,y2) = {#call unsafe draw_line#} (toDrawable d)\n (toGC gc) (fromIntegral x1) (fromIntegral y1) (fromIntegral x2) \n (fromIntegral x2)\n\n-- @method drawLines@ Draw several lines.\n--\n-- * The function uses the current line width, dashing and especially the\n-- joining specification in the graphics context (in contrast to\n-- @ref method drawSegments@.\n--\ndrawLines :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawLines d gc points =\n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_lines#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawSegments@ Draw several unconnected lines.\n--\n-- * This method draws several unrelated lines.\n--\ndrawSegments :: DrawableClass d => d -> GC -> [(Point,Point)] -> IO ()\ndrawSegments d gc pps = withArray (concatMap (\\((x1,y1),(x2,y2)) -> \n [fromIntegral x1, fromIntegral y1, fromIntegral x2, fromIntegral y2])\n pps) $ \\(aPtr :: Ptr {#type gint#}) ->\n {#call unsafe draw_segments#} (toDrawable d) (toGC gc)\n (castPtr aPtr) (fromIntegral (length pps))\n\n-- @method drawRectangle@ Draw a rectangular object.\n--\n-- * Draws a rectangular outline or filled rectangle, using the\n-- foreground color and other attributes of the @ref type GC@.\n--\n-- * A rectangle drawn filled is 1 pixel smaller in both dimensions\n-- than a rectangle outlined. Calling @ref method drawRectangle@ w gc\n-- True 0 0 20 20 results in a filled rectangle 20 pixels wide and 20\n-- pixels high. Calling @ref method drawRectangle@ d gc False 0 0 20 20\n-- results in an outlined rectangle with corners at (0, 0), (0, 20), (20,\n-- 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.\n--\ndrawRectangle :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> IO ()\ndrawRectangle d gc filled x y width height = {#call unsafe draw_rectangle#}\n (toDrawable d) (toGC gc) (fromBool filled) (fromIntegral x)\n (fromIntegral y) (fromIntegral width) (fromIntegral height)\n\n-- @method drawArc@ Draws an arc or a filled 'pie slice'.\n--\n-- * The arc is defined by the bounding rectangle of the entire\n-- ellipse, and the start and end angles of the part of the ellipse to be\n-- drawn.\n--\n-- * The starting angle @ref arg aStart@ is relative to the 3 o'clock\n-- position, counter-clockwise, in 1\/64ths of a degree. @ref arg aEnd@\n-- is measured similarly, but relative to @ref arg aStart@.\n--\ndrawArc :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> Int -> Int -> IO ()\ndrawArc d gc filled x y width height aStart aEnd =\n {#call unsafe draw_arc#} (toDrawable d) (toGC gc) (fromBool filled)\n (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)\n (fromIntegral aStart) (fromIntegral aEnd)\n\n-- @method drawPolygon@ Draws an outlined or filled polygon.\n--\n-- * The polygon is closed automatically, connecting the last point to\n-- the first point if necessary.\n--\ndrawPolygon :: DrawableClass d => d -> GC -> Bool -> [Point] -> IO ()\ndrawPolygon d gc filled points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr::Ptr {#type gint#}) -> {#call unsafe draw_polygon#} (toDrawable d)\n (toGC gc) (fromBool filled) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawDrawable@ Copies another @ref type Drawable@.\n--\n-- * Copies the (width,height) region of the @ref arg src@ at coordinates\n-- (@ref arg xSrc@, @ref arg ySrc@) to coordinates (@ref arg xDest@, @ref\n-- arg yDest@) in the @ref arg dest@. The @ref arg width@ and\/or @ref arg\n-- height@ may be given as -1, in which case the entire source drawable\n-- will be copied.\n--\n-- * Most fields in @ref arg gc@ are not used for this operation, but\n-- notably the clip mask or clip region will be honored. The source and\n-- destination drawables must have the same visual and colormap, or\n-- errors will result. (On X11, failure to match visual\/colormap results\n-- in a BadMatch error from the X server.) A common cause of this\n-- problem is an attempt to draw a bitmap to a color drawable. The way to\n-- draw a bitmap is to set the bitmap as a clip mask on your\n-- @ref type GC@, then use @ref method drawRectangle@ to draw a \n-- rectangle clipped to the bitmap.\n--\ndrawDrawable :: (DrawableClass src, DrawableClass dest) => \n\t\tdest -> GC -> src -> Int -> Int -> Int -> Int -> \n\t\tInt -> Int -> IO ()\ndrawDrawable dest gc src xSrc ySrc xDest yDest width height =\n {#call unsafe draw_drawable#} (toDrawable dest) (toGC gc)\n (toDrawable src)\n (fromIntegral xSrc) (fromIntegral ySrc) (fromIntegral xDest)\n (fromIntegral yDest) (fromIntegral width) (fromIntegral height)\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"94a2898324f891ae140f9a5f077adc8b35dd42e7","subject":"Make rd_kafka_destroy a safe foreign call","message":"Make rd_kafka_destroy a safe foreign call\n\n- It blocks until everything is being destroyed\r\n- It might trigger callbacks\r\n\r\nDocumentation from librdkafka:\r\n\r\n```\r\n\/**\r\n * @brief Destroy Kafka handle.\r\n *\r\n * @remark This is a blocking operation.\r\n * @remark rd_kafka_consumer_close() will be called from this function\r\n * if the instance type is RD_KAFKA_CONSUMER, a \\c group.id was\r\n * configured, and the rd_kafka_consumer_close() was not\r\n * explicitly called by the application. This in turn may\r\n * trigger consumer callbacks, such as rebalance_cb.\r\n * Use rd_kafka_destroy_flags() with\r\n * RD_KAFKA_DESTROY_F_NO_CONSUMER_CLOSE to avoid this behaviour.\r\n *\r\n * @sa rd_kafka_destroy_flags()\r\n *\/\r\nRD_EXPORT\r\nvoid rd_kafka_destroy(rd_kafka_t *rk);\r\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.Text (Text)\nimport qualified Data.Text as Text\nimport Control.Monad (liftM)\nimport Data.Int (Int32, Int64)\nimport Data.Word (Word8)\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, withForeignPtr, newForeignPtr, newForeignPtr_)\nimport Foreign.C.Error (Errno(..), getErrno)\nimport Foreign.C.String (CString, newCString, withCAString, peekCAString, peekCAStringLen, 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 }\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 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\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 rdKafkaTopicPartitionListDestroy :: FinalizerPtr RdKafkaTopicPartitionListT\n\nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy 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 rdKafkaTopicPartitionListDestroy 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 -> String -> 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 _ -> peekCAStringLen (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 newForeignPtr_\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 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 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 rdKafkaGroupListDestroy :: FinalizerPtr RdKafkaGroupListT\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 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 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 `Word8Ptr'}\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 :: FinalizerPtr RdKafkaMetadataT\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 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.Text (Text)\nimport qualified Data.Text as Text\nimport Control.Monad (liftM)\nimport Data.Int (Int32, Int64)\nimport Data.Word (Word8)\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, withForeignPtr, newForeignPtr, newForeignPtr_)\nimport Foreign.C.Error (Errno(..), getErrno)\nimport Foreign.C.String (CString, newCString, withCAString, peekCAString, peekCAStringLen, 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 }\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 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\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 rdKafkaTopicPartitionListDestroy :: FinalizerPtr RdKafkaTopicPartitionListT\n\nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy 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 rdKafkaTopicPartitionListDestroy 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 -> String -> 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 _ -> peekCAStringLen (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 newForeignPtr_\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 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 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 rdKafkaGroupListDestroy :: FinalizerPtr RdKafkaGroupListT\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 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 unsafe \"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 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 `Word8Ptr'}\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 :: FinalizerPtr RdKafkaMetadataT\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 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":"e9bcf1603332b80b2dfa5a78b080308545122103","subject":"minor tidy-up","message":"minor tidy-up\n\nIgnore-this: 79f2ad5d5becb9bd3693435058300cb3\n\ndarcs-hash:20090721131147-115f9-4cee13f33de667193f00e74294305bcbf9df6720.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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\nnewDevicePtr :: Ptr () -> IO (DevicePtr ())\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 ()))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr ptr\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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 (),Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr 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\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 (),Int64))\nmalloc3D = error \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr () -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr ()' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr () -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr ()' ,\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 () -- ^ 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 = error \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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","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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\nnewDevicePtr :: Ptr () -> IO (DevicePtr ())\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 ()))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> newDevicePtr ptr >>= (return.Right)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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 (),Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> newDevicePtr ptr >>= \\dp -> return.Right $ (dp,pitch)\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\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 (),Int64))\nmalloc3D = error \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr () -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr ()' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr () -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr ()' ,\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 () -- ^ 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 = error \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7cce48e05ca32ecd407b879e9f59dd9e3abe83ba","subject":"Gave more general type to morphological open\/close","message":"Gave more general type to morphological open\/close\n","repos":"aleator\/CV,aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV","old_file":"CV\/Morphology.chs","new_file":"CV\/Morphology.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, UnicodeSyntax, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\n\n-- Morphological opening\nopenOp :: StructuringElement -> ImageOperation GrayScale d\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 d\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 d -> ImageOperation GrayScale d\ngeodesic mask op = op #> IM.limitToOp mask\n\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 (Int, Int) -> KernelShape -> StructuringElement\nstructuringElement s d | isGoodSE s d = createSE s d \n | otherwise = error \"Bad values in structuring element\"\n\n-- Create SE with custom shape that is taken from flat list shape.\ncreateSE :: (Int, Int) -> (Int, Int) -> KernelShape -> StructuringElement\ncreateSE (fromIntegral -> w,fromIntegral -> h) (fromIntegral -> x,fromIntegral -> y) shape = unsafePerformIO $ do\n iptr <- {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ shape) nullPtr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\ncustomSE :: (CInt, CInt) -> (CInt, CInt) -> [CInt] -> ConvKernel\ncustomSE s@(w,h) o shape | isGoodSE s o \n && length shape == fromIntegral (w*h)\n = createCustomSE s o shape\n\ncreateCustomSE (w,h) (x,y) shape = unsafePerformIO $ do\n iptr <- withArray shape $ \\arr ->\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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, UnicodeSyntax, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\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\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 (Int, Int) -> KernelShape -> StructuringElement\nstructuringElement s d | isGoodSE s d = createSE s d \n | otherwise = error \"Bad values in structuring element\"\n\n-- Create SE with custom shape that is taken from flat list shape.\ncreateSE :: (Int, Int) -> (Int, Int) -> KernelShape -> StructuringElement\ncreateSE (fromIntegral -> w,fromIntegral -> h) (fromIntegral -> x,fromIntegral -> y) shape = unsafePerformIO $ do\n iptr <- {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ shape) nullPtr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\ncustomSE :: (CInt, CInt) -> (CInt, CInt) -> [CInt] -> ConvKernel\ncustomSE s@(w,h) o shape | isGoodSE s o \n && length shape == fromIntegral (w*h)\n = createCustomSE s o shape\n\ncreateCustomSE (w,h) (x,y) shape = unsafePerformIO $ do\n iptr <- withArray shape $ \\arr ->\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c0b95060608bd1ecd96bb9e848f2ec2c47faa6f9","subject":"gstreamer: more docs for M.S.G.Core.Bus","message":"gstreamer: more docs for M.S.G.Core.Bus","repos":"vincenthz\/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":"8f0f8d24477f38c3525ff3b5d04f9bfee425aa89","subject":"attempt to calculate (dense) thry spec on cpu and transfer, slightly slower.","message":"attempt to calculate (dense) thry spec on cpu and transfer, slightly slower.\n\nIgnore-this: c47c0b5e617a0dcd9f9f9ce4c56eddf8\n\ndarcs-hash:20090914225453-9241b-2b361b220342dfa01e7ca3898aa7f80d67bd4be4.gz\n","repos":"tmcdonell\/hfx,tmcdonell\/hfx,tmcdonell\/hfx","old_file":"src\/IonSeries.chs","new_file":"src\/IonSeries.chs","new_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : IonSeries\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Functions to work with a series of ions, and generate theoretical spectra\n-- suitable for matching against experimental results with the sequest\n-- cross-correlation algorithm.\n--\n--------------------------------------------------------------------------------\n\nmodule IonSeries\n (\n XCorrSpecThry(..),\n buildThrySpecXCorr\n )\n where\n\n#include \"kernels\/kernels.h\"\n\nimport Config\nimport Protein\n\n--import Mass\n--import Data.Array.Unboxed\n\nimport C2HS\nimport Foreign.CUDA (DevicePtr, withDevicePtr)\nimport qualified Foreign.CUDA as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Data structures\n--------------------------------------------------------------------------------\n\n--\n-- The mz\/intensity spectrum array for the theoretical spectrum. Keep this as a\n-- sparse array, as there are so few elements compared to the experimental data.\n--\n-- XXX: Changed to a dense array on the device, to facilitate eventual dot\n-- product operation (and because my cuda-fu is weak...)\n--\ndata XCorrSpecThry = XCorrSpecThry\n (Int,Int)\n (CUDA.DevicePtr CInt)\n\n\n--------------------------------------------------------------------------------\n-- Theoretical Spectrum\n--------------------------------------------------------------------------------\n\n#if 1\n--\n-- Generate the theoretical spectral representation of a peptide from its\n-- character code sequence, and do something useful with it. The device memory\n-- is deallocated once the action completes.\n--\nbuildThrySpecXCorr :: ConfigParams\n -> (Int,Int) -- ^ bounds of the output array\n -> Int -- ^ precursor charge state\n -> Peptide -- ^ peptide to build spectrum for\n -> (XCorrSpecThry -> IO b) -- ^ action to perform\n -> IO b\nbuildThrySpecXCorr _cp (m,n) chrg pep action =\n CUDA.allocaBytesMemset bytes 0 $ \\spec ->\n CUDA.withArrayLen (map cFloatConv . bIonLadder $ pep) $ \\l b_ions ->\n CUDA.withArray (map cFloatConv . yIonLadder $ pep) $ \\y_ions ->\n addIons chrg b_ions y_ions spec l len >>\n\n action (XCorrSpecThry (m,n) spec)\n\n where\n len = n - m + 1\n bytes = fromIntegral len * fromIntegral (sizeOf (undefined::Int))\n\n\n{# fun unsafe addIons\n { cIntConv `Int' ,\n withDevicePtr* `DevicePtr CFloat' ,\n withDevicePtr* `DevicePtr CFloat' ,\n withDevicePtr* `DevicePtr CInt' ,\n `Int' ,\n `Int' } -> `()' #}\n#endif\n#if 0\nbuildThrySpecXCorr :: ConfigParams -> Int -> Int -> Peptide -> IO XCorrSpecThry\nbuildThrySpecXCorr _cp len_spec charge peptide = do\n spec <- CUDA.forceEither `fmap` CUDA.malloc bytes\n rv <- CUDA.memset spec bytes 0\n\n case rv of\n Just e -> error e\n Nothing -> CUDA.withArrayLen (bIonLadder peptide) $ \\len_ions b_ions -> do\n CUDA.withArray (yIonLadder peptide) $ \\y_ions -> do\n addIons charge b_ions y_ions spec len_ions len_spec\n\n return $ XCorrSpecThry (0,len_spec) spec\n\n where\n bytes = fromIntegral (len_spec * sizeOf (undefined::Int))\n#endif\n#if 0\n--\n-- Sequential version\n--\nbuildThrySpecXCorr :: ConfigParams -> Float -> Peptide -> XCorrSpecThry\nbuildThrySpecXCorr _cp charge peptide =\n concatMap addIons $ [1 .. (max 1 (charge-1))]\n where\n addIons c = concatMap (addIonsAB c) b_ions ++ concatMap (addIonsY c) y_ions\n b_ions = bIonLadder peptide\n y_ions = yIonLadder peptide\n#endif\n#if 0\nbuildThrySpecXCorr :: ConfigParams\n -> (Int,Int) -- ^ bounds of the output array\n -> Int -- ^ precursor charge state\n -> Peptide -- ^ peptide to build spectrum for\n -> (XCorrSpecThry -> IO b) -- ^ action to perform\n -> IO b\nbuildThrySpecXCorr cp bnds chrg pep action =\n CUDA.withArray (map cIntConv . elems $ spec) $ \\s' -> action (XCorrSpecThry bnds s')\n where\n spec :: Array Int Int\n spec = accumArray max 0 bnds [(bin i,e) | (i,e) <- concatMap addIons [1 .. (max 1 (fromIntegral chrg-1))], inRange bnds (bin i)]\n bin mz = round (mz \/ width)\n width = if aaMassTypeMono cp then 1.0005079 else 1.0011413\n\n addIons c = concatMap (addIonsAB c) b_ions ++ concatMap (addIonsY c) y_ions\n b_ions = bIonLadder pep\n y_ions = yIonLadder pep\n#endif\n#if 0\n--\n-- Convert mass to mass\/charge ratio\n--\nionMZ :: Float -> Float -> Float\nionMZ m c = (m + massH*c) \/ c\n\n\n--\n-- Add a spectral peak for each fragment location, as well as the peaks\n-- corresponding to neutral losses of H2O and NH3.\n--\n-- The factors that contribute to the collision induced dissociation process\n-- used in tandem-MS experiments are not completely understood, so accurate\n-- prediction of fragment ion abundances are not possible. Magnitude components\n-- are assigned based on empirical knowledge.\n--\naddIonsAB, addIonsY :: Num a => Float -> Float -> [(Float, a)]\naddIonsAB charge mass = addIonsA : addIonsB\n where\n addIonsA = let m = ionMZ (mass - massCO) charge in (m, 10)\n addIonsB = let m = ionMZ mass charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massH2O\/charge, 10),\n (m - massNH3\/charge, 10)\n ]\n\naddIonsY charge mass =\n let m = ionMZ (mass + massH2O) charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massNH3\/charge, 10)\n ]\n#endif\n\n","old_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : IonSeries\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Functions to work with a series of ions, and generate theoretical spectra\n-- suitable for matching against experimental results with the sequest\n-- cross-correlation algorithm.\n--\n--------------------------------------------------------------------------------\n\nmodule IonSeries\n (\n XCorrSpecThry(..),\n buildThrySpecXCorr\n )\n where\n\n#include \"kernels\/kernels.h\"\n\nimport Config\nimport Protein\n\nimport C2HS\nimport Foreign.CUDA (DevicePtr, withDevicePtr)\nimport qualified Foreign.CUDA as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Data structures\n--------------------------------------------------------------------------------\n\n--\n-- The mz\/intensity spectrum array for the theoretical spectrum. Keep this as a\n-- sparse array, as there are so few elements compared to the experimental data.\n--\n-- XXX: Changed to a dense array on the device, to facilitate eventual dot\n-- product operation (and because my cuda-fu is weak...)\n--\ndata XCorrSpecThry = XCorrSpecThry\n (Int,Int)\n (CUDA.DevicePtr CInt)\n\n\n--------------------------------------------------------------------------------\n-- Theoretical Spectrum\n--------------------------------------------------------------------------------\n\n--\n-- Generate the theoretical spectral representation of a peptide from its\n-- character code sequence, and do something useful with it. The device memory\n-- is deallocated once the action completes.\n--\nbuildThrySpecXCorr :: ConfigParams\n -> (Int,Int) -- ^ bounds of the output array\n -> Int -- ^ precursor charge state\n -> Peptide -- ^ peptide to build spectrum for\n -> (XCorrSpecThry -> IO b) -- ^ action to perform\n -> IO b\nbuildThrySpecXCorr _cp (m,n) chrg pep action =\n CUDA.allocaBytesMemset bytes 0 $ \\spec ->\n CUDA.withArrayLen (map cFloatConv . bIonLadder $ pep) $ \\l b_ions ->\n CUDA.withArray (map cFloatConv . yIonLadder $ pep) $ \\y_ions ->\n addIons chrg b_ions y_ions spec l len >>\n\n action (XCorrSpecThry (m,n) spec)\n\n where\n len = n - m + 1\n bytes = fromIntegral len * fromIntegral (sizeOf (undefined::Int))\n\n\n{# fun unsafe addIons\n { cIntConv `Int' ,\n withDevicePtr* `DevicePtr CFloat' ,\n withDevicePtr* `DevicePtr CFloat' ,\n withDevicePtr* `DevicePtr CInt' ,\n `Int' ,\n `Int' } -> `()' #}\n\n#if 0\nbuildThrySpecXCorr :: ConfigParams -> Int -> Int -> Peptide -> IO XCorrSpecThry\nbuildThrySpecXCorr _cp len_spec charge peptide = do\n spec <- CUDA.forceEither `fmap` CUDA.malloc bytes\n rv <- CUDA.memset spec bytes 0\n\n case rv of\n Just e -> error e\n Nothing -> CUDA.withArrayLen (bIonLadder peptide) $ \\len_ions b_ions -> do\n CUDA.withArray (yIonLadder peptide) $ \\y_ions -> do\n addIons charge b_ions y_ions spec len_ions len_spec\n\n return $ XCorrSpecThry (0,len_spec) spec\n\n where\n bytes = fromIntegral (len_spec * sizeOf (undefined::Int))\n#endif\n#if 0\n--\n-- Sequential version\n--\nbuildThrySpecXCorr :: ConfigParams -> Float -> Peptide -> XCorrSpecThry\nbuildThrySpecXCorr _cp charge peptide =\n concatMap addIons $ [1 .. (max 1 (charge-1))]\n where\n addIons c = concatMap (addIonsAB c) b_ions ++ concatMap (addIonsY c) y_ions\n b_ions = bIonLadder peptide\n y_ions = yIonLadder peptide\n\n--\n-- Convert mass to mass\/charge ratio\n--\nionMZ :: Float -> Float -> Float\nionMZ m c = (m + massH*c) \/ c\n\n\n--\n-- Add a spectral peak for each fragment location, as well as the peaks\n-- corresponding to neutral losses of H2O and NH3.\n--\n-- The factors that contribute to the collision induced dissociation process\n-- used in tandem-MS experiments are not completely understood, so accurate\n-- prediction of fragment ion abundances are not possible. Magnitude components\n-- are assigned based on empirical knowledge.\n--\naddIonsAB, addIonsY :: Float -> Float -> [(Float, Float)]\naddIonsAB charge mass = addIonsA : addIonsB\n where\n addIonsA = let m = ionMZ (mass - massCO) charge in (m, 10)\n addIonsB = let m = ionMZ mass charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massH2O\/charge, 10),\n (m - massNH3\/charge, 10)\n ]\n\naddIonsY charge mass =\n let m = ionMZ (mass + massH2O) charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massNH3\/charge, 10)\n ]\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d90b8e09eb5e7c50af10ffb04c04924bb7cf72cc","subject":"GLDrawingArea: provide implementation for GObjectClass Without this patch, trying to use a GLDrawingArea results in program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject","message":"GLDrawingArea: provide implementation for GObjectClass\nWithout this patch, trying to use a GLDrawingArea results in\n program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject\n\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea where\n toGObject (GLDrawingArea gd) = toGObject gd\n unsafeCastGObject = GLDrawingArea . unsafeCastGObject\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a552aa4aa57c1a29820a98495e690d68a91f4728","subject":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty","message":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer","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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"dad73c8b1114e1fe728696d22bf0931f34d36bff","subject":"LocalArrayArg","message":"LocalArrayArg\n","repos":"HIPERFIT\/hopencl,HIPERFIT\/hopencl","old_file":"Foreign\/OpenCL\/Bindings\/Kernel.chs","new_file":"Foreign\/OpenCL\/Bindings\/Kernel.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"78a5bdaa6e9189382ccbbcabd752597caeb35ab3","subject":"point-free types","message":"point-free types\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\n , withAllDrivers\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\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\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\nwithAllDrivers act\n = registerAllDrivers >>\n finally act {#call GDALDestroyDriverManager as ^#}\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","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\n , withAllDrivers\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\ntype RODataset t = Dataset ReadOnly t\ntype RWDataset t = Dataset ReadWrite t \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\ntype ROBand t = Band ReadOnly t\ntype RWBand t = Band ReadWrite t\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\nwithAllDrivers act\n = registerAllDrivers >>\n finally act {#call GDALDestroyDriverManager as ^#}\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":"69463da94677246f7d57a94b2806d9072fc4f0f7","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\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/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":"b3da02fd24d1b3a82db346bc5ee037b0dcd9f9ca","subject":"Add yet another property for read access.","message":"Add yet another property for read access.\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n newAttrFromMaybeStringProperty,\n readAttrFromMaybeStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n readAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nreadAttrFromMaybeStringProperty :: GObjectClass gobj => String -> ReadAttr gobj (Maybe String)\nreadAttrFromMaybeStringProperty propName =\n readAttr (objectGetPropertyMaybeString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject gtype propName)\n \nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n\nreadAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> ReadAttr gobj gobj'\nreadAttrFromObjectProperty propName gtype =\n readAttr (objectGetPropertyGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n newAttrFromMaybeStringProperty,\n readAttrFromMaybeStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nreadAttrFromMaybeStringProperty :: GObjectClass gobj => String -> ReadAttr gobj (Maybe String)\nreadAttrFromMaybeStringProperty propName =\n readAttr (objectGetPropertyMaybeString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"1048956d95cbd3a82d7ce5ad258be9b362cd3fef","subject":"Add blank lines before and after little example code fragments in the haddock documentation","message":"Add blank lines before and after little example code fragments in 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--\n-- @\n-- LT input 1 \n-- @\n--\n-- | is the current token. Or a negative offset may be specified, where: \n--\n-- @\n-- LT input (-1) \n-- @\n--\n-- | is the previous token.\n--\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--\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--\n-- @\n-- tokenGetAntlrString token\n-- @\n--\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-- @\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-- @\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-- @\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-- @\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-- @\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-- @\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-- @\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-- @\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:\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"db851f3e61bd418b4876d0df4ab88f5dd9f67779","subject":"Missing bit from ImageOps","message":"Missing bit from ImageOps","repos":"aleator\/CV,BeautifulDestinations\/CV,aleator\/CV,TomMD\/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,KernelShape(EllipseShape,CrossShape,RectShape) \n )\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\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 . fromEnum $ 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, 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,KernelShape(EllipseShape,CrossShape,RectShape) \n )\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\n-- | Perform a black tophat filtering of size\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\n-- | Perform a white tophat filtering of size\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\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 . fromEnum $ 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f97e0202dded3ec96b3122b539ac5fa273b208c9","subject":"we can compile stuff now","message":"we can compile stuff now\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\ntype CSignature = Ptr CFile\n\n\n-- | The Signature type\n{#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\n\n-- We first implement a function to generate the signature which is easy to\n-- call\n#c\nrs_result genSig(char* filePath, int fd) {\n FILE* f, sigFile;\n rs_stats_t stats;\n rs_result result;\n\n f = rs_file_open(filePath, \"rb\");\n sigFile = fdopen(fd, \"w\");\n\n result = rs_sig_file(f, sigFile, &stats);\n rs_file_close(f);\n\n return result;\n}\n#endc\n\n-- cSignature :: FilePath -> IO (Either String CSignature)\n-- cSignature p = cGenSig p >>= \\r -> return $ case r of\n-- RsDone -> Right $ getSig ps\n-- _ -> Left \"some error\"\n-- where\n-- getSig :: SignaturePtr -> CSignature\n-- getSig = undefined\n\n\n\ncGenSig :: FilePath -> Handle -> IO (Handle, Result)\ncGenSig p h = handleToFd h >>= cGenSig' p >>= \\r -> return (h,r)\n\n{#fun unsafe genSig as cGenSig'\n { `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n #}\n\n\n\n-- -- | Loading signatures\n-- -- the c-function is:\n-- -- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n-- {#fun unsafe rs_loadsig_file as cRSLoadSigFile\n-- { id `Ptr CFile'\n-- , alloca- `SignaturePtr' peek*\n-- , alloca- `StatsPtr'\n-- } -> `Result' cIntToEnum\n-- #}\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n\n\ntest = do\n h <- openBinaryFile \"\/tmp\/signature\" WriteMode\n (h',r) <- cGenSig \"\/Users\/frank\/tmp\/httpd-error.log\" h\n print r\n hClose h'\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ntype CRSLong = CLLong\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- | The Signature type\ndata CSignature -- = CSignature { flength :: CRSLong\n -- , count :: CInt\n -- , remainder :: CInt\n -- , blockLenth :: CInt\n -- , strongSumLenght :: CInt\n -- , blockSigs :: BlockSigPtr\n -- , targets :: TargetPtr\n -- }\n -- deriving (Eq, Show)\n\n{#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The Stats type\ndata Stats\n{#pointer *rs_stats as StatsPtr -> Stats #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\n-- crsSignature :: Handle -> IO (Maybe CSignature, Result)\n-- crsSignature h = undefined\n\ntype CFilePtr = Ptr CFile\n\n-- | Loading signatures\n-- the c-function is:\n-- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n{#fun unsafe rs_loadsig_file as cRSLoadSigFile\n { id `CFilePtr'\n , alloca- `SignaturePtr' peek*\n , alloca- `StatsPtr'\n } -> `Result' cIntToEnum\n #}\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"98e9b39d7de2485ca865306c9d1e96531b9ff212","subject":"more work on the signature stuff.","message":"more work on the signature stuff.\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport Data.ByteString\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype Signature = ByteString\n\nsignature :: FilePath -> IO (Either String Signature)\nsignature p = undefined\n\n\n\n-- | Given a file, and a handle h, opened in binary Read-Write mode, indicating\n-- where to write the signature to. Generate the signature. The signature is\n-- written to the file corresponding to handle h. The handle is moved to the\n-- beginning of the file. The function returns a Maybe String, indicating if\n-- something goes wrong. If the result is Nothing, the operation succeeded.\nhSignature :: FilePath -> Handle -> IO (Maybe String)\nhSignature p h = copyHandleToFd h >>= cGenSig p >>= \\r -> case r of\n RsDone -> hSeek h AbsoluteSeek 0 >> return Nothing\n _ -> return $ Just \"some error\"\n\n{#fun unsafe genSig as cGenSig\n { `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n #}\n\n-- We first implement a function to generate the signature which is easy to\n-- call\n#c\nrs_result genSig(char* filePath, int fd) {\n FILE* f, sigFile;\n rs_stats_t stats;\n rs_result result;\n\n f = rs_file_open(filePath, \"rb\");\n sigFile = fdopen(fd, \"wb\");\n\n result = rs_sig_file(f, sigFile, &stats);\n rs_file_close(f);\n\n \/\/ Note that we leave the sigfile open\n\n return result;\n}\n#endc\n\n\n-- -- | Loading signatures\n-- -- the c-function is:\n-- -- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n-- {#fun unsafe rs_loadsig_file as cRSLoadSigFile\n-- { id `Ptr CFile'\n-- , alloca- `SignaturePtr' peek*\n-- , alloca- `StatsPtr'\n-- } -> `Result' cIntToEnum\n-- #}\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\ncGenDelta :: Handle -> FilePath -> Handle -> IO (Handle, Result)\ncGenDelta sigHandle p deltaHandle = undefined\n\n\n{#fun unsafe genDelta as genDelta'\n { fromIntegral `Fd'\n , `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n\n #}\n\n#c\n\/\/ generate a delta, based on the implementation of rdiff\nrs_result genDelta(int sigFd, char* filePath, int deltaFd) {\n FILE* sigFile, f, deltaFile;\n rs_result result;\n rs_signature_t* sumset;\n rs_stats_t stats;\n\n sigFile = fdopen(sigFd, \"rb\");\n f = rs_open_file(filePath, \"rb\");\n deltaFile = fdopen(deltaFd, \"wb\");\n\n result = rs_loadsig_file(sigFile, &sumset, &stats);\n if (result != RS_DONE)\n return result;\n\n if ((result = rs_build_hash_table(sumset)) != RS_DONE)\n return result;\n\n result = rs_delta_file(sumset, f, deltaFile, &stats);\n\n rs_free_sumset(sumset);\n\n \/\/ rs_file_close(deltaFile);\n rs_file_close(f);\n rs_file_close(sigFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n{#fun unsafe applyPatch as applyPatch'\n { fromIntegral `Fd'\n , `String'\n , `String'\n } -> `Result' cIntToEnum\n #}\n\n\n#c\nrs_result applyPatch(int deltaFd, char* inputPath, char* outputPath) {\n FILE* deltaFile, inputFile, outputFile;\n rs_stats_t stats;\n rs_result result;\n\n inputFile = rs_file_open(inputPath, \"rb\");\n deltaFile = fdopen(deltaFd, \"rb\");\n outputFile = rs_file_open(outputPath, \"wb\");\n\n result = rs_patch_file(inputFile, deltaFile, outputFile, &stats);\n\n rs_file_close(inputFile);\n \/\/ keep the delta file open\n rs_file_close(outputFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n\ncopyHandleToFd h = hDuplicate h >>= handleToFd\n\ntest = do\n h <- openBinaryFile \"\/tmp\/signature\" ReadWriteMode\n r <- hSignature \"\/Users\/frank\/tmp\/httpd-error.log\" h\n print r\n hClose h\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\ntype CSignature = Ptr CFile\n\n\n-- | The Signature type\n{#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\n\n-- We first implement a function to generate the signature which is easy to\n-- call\n#c\nrs_result genSig(char* filePath, int fd) {\n FILE* f, sigFile;\n rs_stats_t stats;\n rs_result result;\n\n f = rs_file_open(filePath, \"rb\");\n sigFile = fdopen(fd, \"wb\");\n\n result = rs_sig_file(f, sigFile, &stats);\n rs_file_close(f);\n\n \/\/ Note that we leave the sigfile open\n\n return result;\n}\n#endc\n\n-- cSignature :: FilePath -> IO (Either String CSignature)\n-- cSignature p = cGenSig p >>= \\r -> return $ case r of\n-- RsDone -> Right $ getSig ps\n-- _ -> Left \"some error\"\n-- where\n-- getSig :: SignaturePtr -> CSignature\n-- getSig = undefined\n\n\n\ncGenSig :: FilePath -> Handle -> IO (Handle, Result)\ncGenSig p h = handleToFd h >>= cGenSig' p >>= \\r -> return (h,r)\n\n{#fun unsafe genSig as cGenSig'\n { `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n #}\n\n\n\n-- -- | Loading signatures\n-- -- the c-function is:\n-- -- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n-- {#fun unsafe rs_loadsig_file as cRSLoadSigFile\n-- { id `Ptr CFile'\n-- , alloca- `SignaturePtr' peek*\n-- , alloca- `StatsPtr'\n-- } -> `Result' cIntToEnum\n-- #}\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n#c\n\/\/ generate a delta, based on the implementation of rdiff\nrs_result genDelta(int sigFd, char* filePath, int deltaFd) {\n FILE* sigFile, f, deltaFile;\n rs_result result;\n rs_signature_t* sumset;\n rs_stats_t stats;\n\n sigFile = fdopen(sigFd, \"rb\");\n f = rs_open_file(filePath, \"rb\");\n deltaFile = fdopen(deltaFd, \"wb\");\n\n result = rs_loadsig_file(sigFile, &sumset, &stats);\n if (result != RS_DONE)\n return result;\n\n if ((result = rs_build_hash_table(sumset)) != RS_DONE)\n return result;\n\n result = rs_delta_file(sumset, f, deltaFile, &stats);\n\n rs_free_sumset(sumset);\n\n \/\/ rs_file_close(deltaFile);\n rs_file_close(f);\n \/\/ rs_file_close(sigFile);\n\n return result;\n}\n#endc\n\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n#c\nrs_result applyPatch(int deltaFd, char* inputPath, char* outputPath) {\n FILE* deltaFile, inputFile, outputFile;\n rs_stats_t stats;\n rs_result result;\n\n inputFile = rs_file_open(inputPath, \"rb\");\n deltaFile = fdopen(deltaFd, \"rb\");\n outputFile = rs_file_open(outputPath, \"wb\");\n\n result = rs_patch_file(inputFile, deltaFile, outputFile, &stats);\n\n rs_file_close(inputFile);\n \/\/ keep the delta file open\n rs_file_close(outputFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n\n\ntest = do\n h <- openBinaryFile \"\/tmp\/signature\" WriteMode\n (h',r) <- cGenSig \"\/Users\/frank\/tmp\/httpd-error.log\" h\n print r\n hClose h'\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"24fe52d3f4e988132bde0482feebdf664861950f","subject":"gio: S.G.File: don't export FileClass's nonexistent methods","message":"gio: S.G.File: don't export FileClass's nonexistent methods","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-- \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":"019bb2218440c61a363e239171defae594b93dce","subject":"[project @ 2002-07-04 10:44:47 by as49] Realized that the onDestroy should actually be bound to the destroy of GtkObject, not to the destroy-event of GtkWidget.","message":"[project @ 2002-07-04 10:44:47 by as49]\nRealized that the onDestroy should actually be bound to the destroy of\nGtkObject, not to the destroy-event of GtkWidget.\n","repos":"vincenthz\/webkit","old_file":"gtk\/abstract\/Widget.chs","new_file":"gtk\/abstract\/Widget.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget class@\n--\n-- Author : Axel Simon\n-- \n-- Created: 27 April 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/04 10:44:47 $\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 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 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-- @dunno@Lock accelerators.\n-- * @literal@\n--widgetLockAccelerators :: WidgetClass w => w -> IO ()\n--widgetLockAccelerators = {#call unsafe widget_lock_accelerators#}.toWidget\n\n\n-- @dunno@Unlock accelerators.\n-- * @literal@\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 -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonGrabFocus = event \"grab_focus\" [] False\nafterGrabFocus = event \"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 class@\n--\n-- Author : Axel Simon\n-- \n-- Created: 27 April 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/05\/24 09:43:24 $\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 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 onDestroy,\n afterDestroy,\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 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 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-- @dunno@Lock accelerators.\n-- * @literal@\n--widgetLockAccelerators :: WidgetClass w => w -> IO ()\n--widgetLockAccelerators = {#call unsafe widget_lock_accelerators#}.toWidget\n\n\n-- @dunno@Unlock accelerators.\n-- * @literal@\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 connectToDestroy@ The widget will be destroyed.\n--\n-- * This is the last signal this widget will receive.\n--\nonDestroy, afterDestroy :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonDestroy = event \"destroy_event\" [] False\nafterDestroy = 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 -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonGrabFocus = event \"grab_focus\" [] False\nafterGrabFocus = event \"grab_focus\" [] 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":"b5878eaeff5f87d7bb799f417fd250443eb02e6a","subject":"block sink","message":"block sink\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\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 , setDatasetProjection\n , datasetGeotransform\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 , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , blockConduit\n , unsafeBlockConduit\n , blockSink\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.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>))\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.Conduit.List as CL\nimport Data.Conduit\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\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 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\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection =\n liftIO . ({#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString)\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n unsafeUseAsCString (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\ndatasetGeotransform :: Dataset s a 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 == CE_None\n then liftM Just (peek p)\n else return Nothing\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 = dataType (undefined :: a)\n\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 (bx :+: by) =\n bandMaskType band >>= \\case\n MaskNoData ->\n liftM2 mkValueUVector (noDataOrFail band) (read_ band)\n MaskAllValid ->\n liftM mkAllValidValueUVector (read_ band)\n _ ->\n liftM2 mkMaskedValueUVector (read_ =<< bandMask band) (read_ band)\n where\n sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n read_ :: forall a'. GDALType a' => Band s a' t -> GDAL s (St.Vector a')\n read_ b = liftIO $ do\n vec <- M.new (bx*by)\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 (dataType (undefined :: 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 (dataType (undefined :: a')))\n 0\n 0\n G.unsafeFreeze vec\n{-# INLINE readBand #-}\n\n\nwriteMasked\n :: GDALType a\n => RWBand s a\n -> (RWBand s a -> St.Vector a -> GDAL s ())\n -> (RWBand s Word8 -> St.Vector Word8 -> GDAL s ())\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteMasked band writer maskWriter uvec =\n bandMaskType band >>= \\case\n MaskNoData ->\n noDataOrFail band >>= writer band . flip toGVecWithNodata uvec\n MaskAllValid ->\n maybe (throwBindingException BandDoesNotAllowNoData)\n (writer band)\n (toGVec uvec)\n _ ->\n let (mask, vec) = toGVecWithMask uvec\n in writer band vec >> bandMask band >>= flip maskWriter mask\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\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@(bx :+: by) = writeMasked band write write\n where\n write :: forall a'. GDALType a'\n => RWBand s a' -> St.Vector a' -> GDAL s ()\n write band' 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 (dataType (undefined :: a')))\n 0\n 0\n{-# INLINE writeBand #-}\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\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 -> BlockIx -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (allBlocks band =$= unsafeBlockConduit 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\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\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 = dataType (undefined :: 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 (snd . 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) (BlockIx, U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band\n =$= CL.mapM (\\(i,v) -> liftIO (U.freeze v >>= \\v' -> return (i,v')))\n{-# INLINE blockConduit #-}\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockConduit band = unsafeBlockConduitM band =$= awaitForever go\n where go (ix, v) = liftIO (U.unsafeFreeze v) >>= (\\v' -> yield (ix, v'))\n{-# INLINE unsafeBlockConduit #-}\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (BlockIx, 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 = dataType (undefined :: 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 (ix, 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 (ix, 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\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\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n mapM_ (flip (writeBandBlock b) v) [i:+:j | j<-[0..ny-1], i<-[0..nx-1]]\n where\n nx:+:ny = bandBlockCount b\n v = G.replicate (bandBlockLen b) val\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\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 , setDatasetProjection\n , datasetGeotransform\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 , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , blockConduit\n , unsafeBlockConduit\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.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>))\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.Conduit.List as CL\nimport Data.Conduit\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\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, allocaBytes)\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 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\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection =\n liftIO . ({#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString)\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n unsafeUseAsCString (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\ndatasetGeotransform :: Dataset s a 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 == CE_None\n then liftM Just (peek p)\n else return Nothing\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 = dataType (undefined :: a)\n\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 (bx :+: by) =\n bandMaskType band >>= \\case\n MaskNoData ->\n liftM2 mkValueUVector (noDataOrFail band) (read_ band)\n MaskAllValid ->\n liftM mkAllValidValueUVector (read_ band)\n _ ->\n liftM2 mkMaskedValueUVector (read_ =<< bandMask band) (read_ band)\n where\n sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n read_ :: forall a'. GDALType a' => Band s a' t -> GDAL s (St.Vector a')\n read_ b = liftIO $ do\n vec <- M.new (bx*by)\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 (dataType (undefined :: 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 (dataType (undefined :: a')))\n 0\n 0\n G.unsafeFreeze vec\n{-# INLINE readBand #-}\n\n\nwriteMasked\n :: GDALType a\n => RWBand s a\n -> (RWBand s a -> St.Vector a -> GDAL s ())\n -> (RWBand s Word8 -> St.Vector Word8 -> GDAL s ())\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteMasked band writer maskWriter uvec =\n bandMaskType band >>= \\case\n MaskNoData ->\n noDataOrFail band >>= writer band . flip toGVecWithNodata uvec\n MaskAllValid ->\n maybe (throwBindingException BandDoesNotAllowNoData)\n (writer band)\n (toGVec uvec)\n _ ->\n let (mask, vec) = toGVecWithMask uvec\n in writer band vec >> bandMask band >>= flip maskWriter mask\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\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@(bx :+: by) = writeMasked band write write\n where\n write :: forall a'. GDALType a'\n => RWBand s a' -> St.Vector a' -> GDAL s ()\n write band' 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 (dataType (undefined :: a')))\n 0\n 0\n{-# INLINE writeBand #-}\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\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 -> BlockIx -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (allBlocks band =$= unsafeBlockConduit 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\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec = do\n when (bandBlockLen band \/= len) $\n throwBindingException (InvalidBlockSize len)\n writeMasked band write writeMask uvec\n where\n write\n | dtBand == dtBuf = writeNative\n | otherwise = writeTranslated\n dtBand = bandDataType (band)\n dtBuf = dataType (undefined :: a)\n len = G.length uvec\n bi = fmap fromIntegral blockIx\n\n writeNative _ buf =\n liftIO $\n St.unsafeWith buf $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call WriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n\n writeTranslated _ buf = liftIO $\n allocaBytes (len*sizeOfDataType dtBand) $ \\pWork ->\n St.unsafeWith buf $ \\pBuf -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral (sizeOfDataType dtBuf))\n pWork\n (fromEnumC dtBand)\n (fromIntegral (sizeOfDataType dtBand))\n (fromIntegral len)\n checkCPLError \"WriteBlock\" $\n {#call WriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n pWork\n\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n off = bi * bs\n win = liftA2 min bs (rs - off)\n\n writeMask mBand buf =\n liftIO $\n checkCPLError \"WriteBlock\" $\n St.unsafeWith buf $ \\pBuf ->\n {#call RasterIO as ^#}\n (unBand mBand)\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{-# INLINE writeBandBlock #-}\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 (snd . 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) (BlockIx, U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band\n =$= CL.mapM (\\(i,v) -> liftIO (U.freeze v >>= \\v' -> return (i,v')))\n{-# INLINE blockConduit #-}\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockConduit band = unsafeBlockConduitM band =$= awaitForever go\n where go (ix, v) = liftIO (U.unsafeFreeze v) >>= (\\v' -> yield (ix, v'))\n{-# INLINE unsafeBlockConduit #-}\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (BlockIx, 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 = dataType (undefined :: 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 (ix, 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 (ix, 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\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\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n mapM_ (flip (writeBandBlock b) v) [i:+:j | j<-[0..ny-1], i<-[0..nx-1]]\n where\n nx:+:ny = bandBlockCount b\n v = G.replicate (bandBlockLen b) val\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f01712847255cf4a4781785e2d20d88afc770031","subject":"remove SDL logging","message":"remove SDL logging\n","repos":"abbradar\/MySDL","old_file":"src\/Graphics\/UI\/SDL\/Monad.chs","new_file":"src\/Graphics\/UI\/SDL\/Monad.chs","new_contents":"{-# LANGUAGE UndecidableInstances #-}\n\nmodule Graphics.UI.SDL.Monad\n ( SDLT\n , withSDL\n ) where\n\nimport Foreign.C.Types (CInt(..), CUInt(..))\nimport Control.Applicative (Applicative)\nimport Control.Monad.Fix (MonadFix)\nimport Control.Monad.IO.Class (MonadIO)\nimport Control.Monad.Base (MonadBase(..))\nimport Control.Monad.Trans.Class (MonadTrans(..))\nimport Control.Monad.Trans.Control (MonadBaseControl(..))\n\nimport Graphics.UI.SDL.Class\n\n{#import Graphics.UI.SDL.Internal.Prim #}\n\n#include \n\n-- Main SDL monad transformer.\nnewtype SDLT m a = SDLT { runSDLT :: m a }\n deriving (Functor, Applicative, Monad,\n MonadFix)\n\ninstance MonadTrans SDLT where\n lift = SDLT\n\nderiving instance MonadBase IO m => MonadBase IO (SDLT m)\nderiving instance MonadIO m => MonadIO (SDLT m)\n\ninstance MonadBaseControl IO m => MonadBaseControl IO (SDLT m) where\n newtype StM (SDLT m) a = StM {unStM :: StM m a}\n liftBaseWith = liftBaseThreaded SDLT runSDLT withSDL StM\n restoreM = SDLT . restoreM . unStM\n\ninstance MonadBase IO m => MonadSDL (SDLT m) where\n\nwithSDL :: (MonadBaseControl IO m, MonadBase IO m) => SDLT m a -> m a\nwithSDL = unsafeWithSubSystem\n (liftBase $ sdlCode \"SDL_Init\" $ sDLInit mainSystem)\n (liftBase {#call unsafe SDL_Quit as ^ #})\n mainSystem . runSDLT\n where mainSystem = NoParachute\n -- TODO: Change 'Int' to 'SDLSubSystem' when issue #103 in c2hs is fixed.\n {#fun unsafe SDL_Init as ^ { `SDLSubSystem' } -> `Int' #}\n","old_contents":"{-# LANGUAGE UndecidableInstances #-}\n\nmodule Graphics.UI.SDL.Monad\n ( SDLT\n , withSDL\n ) where\n\nimport Data.Monoid\nimport qualified Data.ByteString.Char8 as S8\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport qualified Data.Text as T\nimport Foreign.C.Types (CInt(..), CUInt(..))\nimport Foreign.C.String (CString)\nimport Control.Applicative (Applicative)\nimport Control.Monad.Fix (MonadFix)\nimport Control.Monad.IO.Class (MonadIO)\nimport Control.Monad.Base (MonadBase(..))\nimport Control.Monad.Trans.Class (MonadTrans(..))\nimport Control.Monad.Trans.Control (MonadBaseControl(..))\nimport Control.Monad.Logger (MonadLogger(..),\n LogLevel(..))\nimport System.Log.FastLogger (toLogStr, fromLogStr)\nimport FileLocation.LocationString (locationToString)\n\nimport Graphics.UI.SDL.Class\n\n{#import Graphics.UI.SDL.Internal.Prim #}\n\n#include \n\n-- Main SDL monad transformer.\nnewtype SDLT m a = SDLT { runSDLT :: m a }\n deriving (Functor, Applicative, Monad,\n MonadFix)\n\ninstance MonadTrans SDLT where\n lift = SDLT\n\nderiving instance MonadBase IO m => MonadBase IO (SDLT m)\nderiving instance MonadIO m => MonadIO (SDLT m)\n\ninstance MonadBaseControl IO m => MonadBaseControl IO (SDLT m) where\n newtype StM (SDLT m) a = StM {unStM :: StM m a}\n liftBaseWith = liftBaseThreaded SDLT runSDLT withSDL StM\n restoreM = SDLT . restoreM . unStM\n\ninstance MonadBase IO m => MonadSDL (SDLT m) where\n\n-- Logging support\n \n{#enum SDL_LogPriority as SDLLogPriority {underscoreToCase} deriving (Show, Eq) #}\n\n{#enum SDL_LOG_CATEGORY_APPLICATION as SDLLogCategory {underscoreToCase} deriving (Show, Eq) #}\n\n-- SDL_LogMessage uses varargs, so it can't be imported via c2hs.\nforeign import ccall unsafe \"SDL2\/SDL_log.h SDL_LogMessage\"\n logMessage :: Int -> Int -> CString -> CString -> IO ()\n\ninstance (MonadBase IO m) => MonadLogger (SDLT m) where\n monadLoggerLog loc src lvl msg = do\n let l = fromLogStr $\n (case lvl of\n LevelOther t -> \"(\" `mappend` toLogStr t `mappend` \") \"\n _ -> mempty\n ) `mappend`\n (if T.null src\n then mempty\n else \"[\" `mappend` toLogStr src `mappend` \"] \"\n ) `mappend` toLogStr msg `mappend` \" @(\"\n `mappend` toLogStr (S8.pack $ locationToString loc)\n `mappend` \")\\n\\0\"\n liftBase $\n unsafeUseAsCString \"%s\" $ \\format ->\n unsafeUseAsCString l $ \\cmsg ->\n logMessage (fromEnum SdlLogCategoryApplication) (fromEnum $ priority lvl) format cmsg\n where priority LevelDebug = SdlLogPriorityDebug\n priority LevelWarn = SdlLogPriorityWarn\n priority LevelError = SdlLogPriorityError\n priority _ = SdlLogPriorityInfo\n\nwithSDL :: (MonadBaseControl IO m, MonadBase IO m) => SDLT m a -> m a\nwithSDL = unsafeWithSubSystem\n (liftBase $ do\n sdlCode \"SDL_Init\" $ sDLInit $ fromEnum mainSystem\n sDLLogSetPriority SdlLogCategoryApplication SdlLogPriorityVerbose\n )\n (liftBase {#call unsafe SDL_Quit as ^ #})\n mainSystem . runSDLT\n where mainSystem = NoParachute\n {#fun unsafe SDL_LogSetPriority as ^\n { `SDLLogCategory', `SDLLogPriority' } -> `()' #}\n -- TODO: Change 'Int' to 'SDLSubSystem' when issue #103 in c2hs is fixed.\n {#fun unsafe SDL_Init as ^ { `Int' } -> `Int' #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3f41f5e37b48889af7d8d7403221c67e93bbf4cb","subject":"Implement Eq Metadata.","message":"Implement Eq Metadata.\n\nIgnore the flag, just compare key and value.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Lib\/Metadata.chs","new_file":"src\/Network\/Grpc\/Lib\/Metadata.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--------------------------------------------------------------------------------\nmodule Network.Grpc.Lib.Metadata (\n Metadata(..)\n , MetadataPtr\n , mallocMetadata\n\n , isKeyValid\n , isNonBinValueValid\n , isBinaryHeader\n\n , MetadataArray\n , mallocMetadataArray\n , readMetadataArray\n , freeMetadataArray\n ) where\n\nimport qualified Foreign.C.Types as C\nimport qualified Foreign.Ptr as C\nimport qualified Foreign.ForeignPtr as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Array as C\nimport qualified Foreign.Storable as C\n\nimport Control.Monad\nimport Data.Word (Word8)\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport Data.ByteString (ByteString)\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\n{#pointer *grpc_metadata as MetadataPtr -> Metadata#}\n\ndata Metadata = Metadata !ByteString !ByteString !{#type uint32_t#} deriving (Show)\n\ninstance Eq Metadata where\n (Metadata a b _) == (Metadata x y _) = (a,b) == (x,y)\n\ninstance C.Storable Metadata where\n sizeOf _ = {#sizeof grpc_metadata#}\n alignment _ = {#alignof grpc_metadata#}\n peek p = do\n keyPtr <- {#get grpc_metadata->key#} p\n valuePtr <- {#get grpc_metadata->value#} p\n valueLength <- {#get grpc_metadata->value_length#} p\n key <- B.packCString keyPtr\n value <- B.packCStringLen (valuePtr, fromIntegral valueLength)\n flags <- {#get grpc_metadata->flags#} p\n return $! Metadata key value flags\n poke _ _ = error \"Storable Metadata: poke not implemented\"\n\ndata CMetadataArray\n{#pointer *metadata_array as MetadataArray -> CMetadataArray#}\n\n{#fun unsafe metadata_array_init as ^\n {`MetadataArray'} -> `()'#}\n\n{#fun unsafe metadata_array_destroy as ^\n {`MetadataArray'} -> `()'#}\n\nmallocMetadata :: [Metadata] -> IO (MetadataPtr, IO ())\nmallocMetadata mds = do\n arr <- C.mallocBytes (length mds * {#sizeof grpc_metadata#})\n ptrs <- forM (zip [0..] mds) $ \\(i, md) ->\n writeMetadata md (arr `C.plusPtr` (i * {#sizeof grpc_metadata#}))\n return (C.castPtr arr, mapM_ C.free (arr : concat ptrs))\n where\n writeMetadata (Metadata key value flags) arr_ptr = do\n key_ptr <- asCString key\n value_ptr <- asCString value\n {#set grpc_metadata->key#} arr_ptr key_ptr\n {#set grpc_metadata->value#} arr_ptr value_ptr\n {#set grpc_metadata->value_length#} arr_ptr (fromIntegral (B.length value))\n {#set grpc_metadata->flags#} arr_ptr flags\n return [key_ptr, value_ptr]\n\n -- | Create null terminated C-string.\n asCString :: ByteString -> IO (C.Ptr C.CChar)\n asCString (B.PS fp o l) = do\n buf <- C.mallocBytes (l+1)\n C.withForeignPtr fp $ \\p -> do\n B.memcpy buf (p `C.plusPtr` o) (fromIntegral l)\n C.pokeByteOff buf l (0::Word8)\n return (C.castPtr buf)\n\nmallocMetadataArray :: IO (C.Ptr CMetadataArray)\nmallocMetadataArray = do \n ptr <- C.mallocBytes {#sizeof grpc_metadata_array#}\n metadataArrayInit ptr\n return ptr\n\nfreeMetadataArray :: MetadataArray -> IO ()\nfreeMetadataArray arr = do\n metadataArrayDestroy arr\n C.free arr\n\nreadMetadataArray :: MetadataArray -> IO [Metadata]\nreadMetadataArray arr = do\n count <- {#get grpc_metadata_array->count#} arr\n metadataPtr <- {#get grpc_metadata_array->metadata#} arr\n C.peekArray (fromIntegral count) metadataPtr\n\n-- | Validate the key of a metadata pair.\n{#fun pure grpc_header_key_is_legal as isKeyValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Validate a non-binary value.\n{#fun pure grpc_header_nonbin_value_is_legal as isNonBinValueValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Is the key a binary key?\n{#fun pure grpc_is_binary_header as isBinaryHeader\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\nuseAsCStringLen :: Num a => B.ByteString -> ((C.Ptr C.CChar, a) -> IO b) -> IO b\nuseAsCStringLen bs act =\n B.useAsCStringLen bs $ \\(ptr, len) -> act (ptr, fromIntegral len)\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--------------------------------------------------------------------------------\nmodule Network.Grpc.Lib.Metadata (\n Metadata(..)\n , MetadataPtr\n , mallocMetadata\n\n , isKeyValid\n , isNonBinValueValid\n , isBinaryHeader\n\n , MetadataArray\n , mallocMetadataArray\n , readMetadataArray\n , freeMetadataArray\n ) where\n\nimport qualified Foreign.C.Types as C\nimport qualified Foreign.Ptr as C\nimport qualified Foreign.ForeignPtr as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Array as C\nimport qualified Foreign.Storable as C\n\nimport Control.Monad\nimport Data.Word (Word8)\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport Data.ByteString (ByteString)\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\n{#pointer *grpc_metadata as MetadataPtr -> Metadata#}\n\ndata Metadata = Metadata !ByteString !ByteString !{#type uint32_t#} deriving (Show)\n\ninstance C.Storable Metadata where\n sizeOf _ = {#sizeof grpc_metadata#}\n alignment _ = {#alignof grpc_metadata#}\n peek p = do\n keyPtr <- {#get grpc_metadata->key#} p\n valuePtr <- {#get grpc_metadata->value#} p\n valueLength <- {#get grpc_metadata->value_length#} p\n key <- B.packCString keyPtr\n value <- B.packCStringLen (valuePtr, fromIntegral valueLength)\n flags <- {#get grpc_metadata->flags#} p\n return $! Metadata key value flags\n poke _ _ = error \"Storable Metadata: poke not implemented\"\n\ndata CMetadataArray\n{#pointer *metadata_array as MetadataArray -> CMetadataArray#}\n\n{#fun unsafe metadata_array_init as ^\n {`MetadataArray'} -> `()'#}\n\n{#fun unsafe metadata_array_destroy as ^\n {`MetadataArray'} -> `()'#}\n\nmallocMetadata :: [Metadata] -> IO (MetadataPtr, IO ())\nmallocMetadata mds = do\n arr <- C.mallocBytes (length mds * {#sizeof grpc_metadata#})\n ptrs <- forM (zip [0..] mds) $ \\(i, md) ->\n writeMetadata md (arr `C.plusPtr` (i * {#sizeof grpc_metadata#}))\n return (C.castPtr arr, mapM_ C.free (arr : concat ptrs))\n where\n writeMetadata (Metadata key value flags) arr_ptr = do\n key_ptr <- asCString key\n value_ptr <- asCString value\n {#set grpc_metadata->key#} arr_ptr key_ptr\n {#set grpc_metadata->value#} arr_ptr value_ptr\n {#set grpc_metadata->value_length#} arr_ptr (fromIntegral (B.length value))\n {#set grpc_metadata->flags#} arr_ptr flags\n return [key_ptr, value_ptr]\n\n -- | Create null terminated C-string.\n asCString :: ByteString -> IO (C.Ptr C.CChar)\n asCString (B.PS fp o l) = do\n buf <- C.mallocBytes (l+1)\n C.withForeignPtr fp $ \\p -> do\n B.memcpy buf (p `C.plusPtr` o) (fromIntegral l)\n C.pokeByteOff buf l (0::Word8)\n return (C.castPtr buf)\n\nmallocMetadataArray :: IO (C.Ptr CMetadataArray)\nmallocMetadataArray = do \n ptr <- C.mallocBytes {#sizeof grpc_metadata_array#}\n metadataArrayInit ptr\n return ptr\n\nfreeMetadataArray :: MetadataArray -> IO ()\nfreeMetadataArray arr = do\n metadataArrayDestroy arr\n C.free arr\n\nreadMetadataArray :: MetadataArray -> IO [Metadata]\nreadMetadataArray arr = do\n count <- {#get grpc_metadata_array->count#} arr\n metadataPtr <- {#get grpc_metadata_array->metadata#} arr\n C.peekArray (fromIntegral count) metadataPtr\n\n-- | Validate the key of a metadata pair.\n{#fun pure grpc_header_key_is_legal as isKeyValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Validate a non-binary value.\n{#fun pure grpc_header_nonbin_value_is_legal as isNonBinValueValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Is the key a binary key?\n{#fun pure grpc_is_binary_header as isBinaryHeader\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\nuseAsCStringLen :: Num a => B.ByteString -> ((C.Ptr C.CChar, a) -> IO b) -> IO b\nuseAsCStringLen bs act =\n B.useAsCStringLen bs $ \\(ptr, len) -> act (ptr, fromIntegral len)\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"4cd4b1d1bf8c7c516dec8d82ff3bea5e850afacb","subject":"add build info functions","message":"add build info functions\n","repos":"IFCA\/opencl,IFCA\/opencl,Delan90\/opencl,Delan90\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Program.chs","new_file":"src\/System\/GPU\/OpenCL\/Program.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.Program( \n -- * Types\n CLProgram, CLBuildStatus(..),\n -- * Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram, clGetProgramReferenceCount, \n clGetProgramContext, clGetProgramNumDevices, clGetProgramDevices,\n clGetProgramSource, clGetProgramBinarySizes, clGetProgramBinaries, \n clGetProgramBuildStatus, clGetProgramBuildOptions, clGetProgramBuildLog\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLDeviceID, CLError(..), CLProgramInfo_,\n CLBuildStatus(..), CLBuildStatus_, wrapCheckSuccess, wrapPError, wrapGetInfo, \n getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\n--foreign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n-- CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it returns one of the\nfollowing error values:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the program 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.\nclGetProgramReferenceCount :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\nclGetProgramContext :: CLProgram -> IO (Either CLError CLContext)\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\nclGetProgramNumDevices :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\nclGetProgramDevices :: CLProgram -> IO (Either CLError [CLDeviceID])\nclGetProgramDevices prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\nclGetProgramSource :: CLProgram -> IO (Either CLError String)\nclGetProgramSource prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\nclGetProgramBinarySizes :: CLProgram -> IO (Either CLError [CSize])\nclGetProgramBinarySizes prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n-}\n--clGetProgramBinaries :: CLProgram -> IO (Either CLError [[Word8]])\nclGetProgramBinaries prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr (Ptr Word8)) -> do\n print sval\n print buff\n return . Left $ CL_SUCCESS\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::Ptr Word8)\n{-\nCL_PROGRAM_BINARIES\tReturn type: unsigned char *[]\nReturn the program binaries for all devices associated with program. For each device in program, the binary returned can be the binary specified for the device when program is created with clCreateProgramWithBinary or it can be the executable binary generated by clBuildProgram. If program is created with clCreateProgramWithSource, the binary returned is the binary generated by clBuildProgram. The bits returned can be an implementation-specific intermediate representation (a.k.a. IR) or device specific executable bits or both. The decision on which information is returned in the binary is up to the OpenCL implementation.\n\nparam_value points to an array of n pointers where n is the number of devices associated with program. The buffer sizes needed to allocate the memory that these n pointers refer to can be queried using the CL_PROGRAM_BINARY_SIZES query as described in this table.\n\nEach entry in this array is used by the implementation as the location in memory where to copy the program binary for a specific device, if there is a binary available. To find out which device the program binary in the array refers to, use the CL_PROGRAM_DEVICES query to get the list of devices. There is a one-to-one correspondence between the array of n pointers returned by CL_PROGRAM_BINARIES and array of devices returned by CL_PROGRAM_DEVICES.\n-}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO (Either CLError CLBuildStatus)\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildOptions prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildLog prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\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.Program( \n -- * Types\n CLProgram,\n -- * Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLDeviceID, CLError(..), \n wrapCheckSuccess, wrapPError )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'CL_DEVICE_SINGLE_FP_CONFIG'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'CL_DEVICE_DOUBLE_FP_CONFIG'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'CL_DEVICE_COMPILER_AVAILABLE' specified in the table of OpenCL Device\nQueries for 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f4079b618ec92ba81220bb17bf3f6920f71f2f62","subject":"added attribute types enums","message":"added attribute types enums\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 getModulus,\n getPublicExponent,\n getDecryptFlag,\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_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\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\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\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 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 | 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\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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\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","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 getModulus,\n getPublicExponent,\n getDecryptFlag,\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_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\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\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\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 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_LABEL as LabelType,\n CKA_KEY_TYPE as KeyTypeType,\n CKA_DECRYPT as DecryptType,\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 } deriving (Show, Eq) #}\n\ndata Attribute = Class ClassType\n | KeyType KeyTypeValue\n | Label String\n | ModulusBits Int\n | Token Bool\n | Decrypt 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\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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\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":"0f6aede6d946a1c79493cd7ff92a434b4eca0bcb","subject":"[project @ 2002-07-17 16:07:50 by juhp] Export timeoutAdd, timeoutRemove, idleAdd, idleRemove and HandlerId.","message":"[project @ 2002-07-17 16:07:50 by juhp]\nExport timeoutAdd, timeoutRemove, idleAdd, idleRemove and HandlerId.\n","repos":"vincenthz\/webkit","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 16:07:50 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:13:09 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"605722d90f9c1429b585575e7dca4ebbe19b9ba6","subject":"MPICH2: peek\/poke of MPI_Status","message":"MPICH2: peek\/poke of MPI_Status\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#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n <$> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\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#else\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#endif\n poke p x = do\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 {#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#else\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#endif\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_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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3415699cfd78b7c8b2d086f600c1e77fab4a2a0e","subject":"Add writeAttr for Enums.","message":"Add writeAttr for Enums.\n\nThis is needed for MessageDialog.\n\ndarcs-hash:20061020162336-91c87-d1e7973b7b240916e6ddf32eaa79aab8a8c8ba31.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"a046f98f02117200bd1e1645ff326f3b2a143969","subject":"Cleaned up description of the Matrix datatype.","message":"Cleaned up description of the Matrix datatype.\n\ndarcs-hash:20070503171920-b99d0-11a9d7b6b60428b2f07b04b53c73dbee828c50a7.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation.\n--\n-- The Matrix type represents a 2x2 transformation matrix along with a\n-- translation vector. @Matrix a1 a2 b1 b2 c1 c2@ describes the\n-- transformation of a point with coordinates x,y that is defined by\n--\n-- > \/ x' \\ = \/ a1 b1 \\ \/ x \\ + \/ c1 \\\n-- > \\ y' \/ \\ a2 b2 \/ \\ y \/ \\ c2 \/\n--\n-- or\n--\n-- > x' = a1 * x + b1 * y + c1\n-- > y' = a2 * x + b2 * y + c2\n\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"29d995bc0f5728c338710961d5cec9b780002e28","subject":"Made properties pure","message":"Made properties pure\n","repos":"TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV,aleator\/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-- 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\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\ncvCAP_POS_FRAMES = 1\ngetNumberOfFrames cap = unsafePerformIO $\n {#call cvGetCaptureProperty#} \n cap cvCAP_PROP_FRAME_COUNT\ngetFrameNumber cap = unsafePerformIO $\n {#call cvGetCaptureProperty#} \n cap cvCAP_POS_FRAMES\n\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-- 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\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\ncvCAP_POS_FRAMES = 1\ngetNumberOfFrames cap = {#call cvGetCaptureProperty#} \n cap cvCAP_PROP_FRAME_COUNT\ngetFrameNumber cap = {#call cvGetCaptureProperty#} \n cap cvCAP_POS_FRAMES\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"15f1d9beb2f10937df82ffaff8f45b4a1b7d92ec","subject":"Missing link","message":"Missing link\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit","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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and mainGUI then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"be96399437f31c928d7ba5d413b6d7f1b2795094","subject":"Remove unnecessary pointer dereference.","message":"Remove unnecessary pointer dereference.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Group.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Group.chs","new_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Group\n (\n -- * Constructor\n groupNew,\n groupCustom,\n groupSetCurrent,\n groupCurrent,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Group functions\n --\n -- $groupfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Widget\n\n{# fun Fl_Group_set_current as groupSetCurrent' { id `Ptr ()' } -> `()' #}\n{# fun Fl_Group_current as groupCurrent' {} -> `Ptr ()' id #}\n\ngroupSetCurrent :: (Parent a Group) => Maybe (Ref a) -> IO ()\ngroupSetCurrent group = withMaybeRef group $ \\groupPtr -> groupSetCurrent' groupPtr\n\ngroupCurrent :: IO (Maybe (Ref Group))\ngroupCurrent = groupCurrent' >>= toMaybeRef\n\n{# fun Fl_Group_New as groupNew' { `Int',`Int', `Int', `Int'} -> `Ptr ()' id #}\n{# fun Fl_Group_New_WithLabel as groupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text'} -> `Ptr ()' id #}\ngroupNew :: Rectangle -> Maybe T.Text -> IO (Ref Group)\ngroupNew rectangle label' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case label' of\n (Just l') -> groupNewWithLabel' x_pos y_pos width height l' >>= toRef\n Nothing -> groupNew' x_pos y_pos width height >>= toRef\n\n{# fun Fl_OverriddenGroup_New_WithLabel as overriddenGroupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGroup_New as overriddenGroupNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\ngroupCustom :: Rectangle -> Maybe T.Text -> Maybe (Ref Group -> IO ()) -> CustomWidgetFuncs Group -> IO (Ref Group)\ngroupCustom rectangle l' draw' funcs' =\n widgetMaker rectangle l' draw' (Just funcs') overriddenGroupNew' overriddenGroupNewWithLabel'\n\n{# fun Fl_Group_Destroy as groupDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Destroy ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> groupDestroy' groupPtr\n\n\n{# fun Fl_Group_draw_child as drawChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawChild' groupPtr widgetPtr\n\n{# fun Fl_Group_draw_children as drawChildren' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ (IO ())) => Op (DrawChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> drawChildren' groupPtr\n\n{# fun Fl_Group_draw_outside_label as drawOutsideLabel' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawOutsideLabel ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawOutsideLabel' groupPtr widgetPtr\n\n{# fun Fl_Group_update_child as updateChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (UpdateChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> updateChild' groupPtr widgetPtr\n\n{# fun Fl_Group_begin as begin' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Begin ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> begin' groupPtr\n\n{# fun Fl_Group_end as end' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (End ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> end' groupPtr\n\ninstance (\n Match obj ~ FindOp orig orig (Begin ()),\n Match obj ~ FindOp orig orig (End ()),\n Op (Begin ()) obj orig (IO ()),\n Op (End ()) obj orig (IO ()),\n impl ~ (IO () -> IO ())\n ) => Op (Within ()) Group orig impl where\n runOp _ _ group action = do\n () <- begin (castTo group :: Ref orig)\n action\n end (castTo group :: Ref orig)\n\n{# fun Fl_Group_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Find ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> find' groupPtr wPtr\n\n{# fun Fl_Group_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> IO ())) => Op (Add ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> add' groupPtr wPtr\n\n{# fun Fl_Group_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> Int -> IO ())) => Op (Insert ()) Group orig impl where\n runOp _ _ group w i = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> insert' groupPtr wPtr i\n\n{# fun Fl_Group_remove_index as removeIndex' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (RemoveIndex ()) Group orig impl where\n runOp _ _ group index' = withRef group $ \\groupPtr -> removeIndex' groupPtr index'\n\n{# fun Fl_Group_remove_widget as removeWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (RemoveWidget ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> removeWidget' groupPtr wPtr\n\n{# fun Fl_Group_clear as clear' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Clear ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clear' groupPtr\n\n{# fun Fl_Group_set_resizable as setResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Maybe ( Ref a ) -> IO ())) => Op (SetResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withMaybeRef o $ \\oPtr -> setResizable' groupPtr oPtr\n\ninstance (impl ~ IO ()) => Op (SetNotResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> setResizable' groupPtr nullPtr\n\n{# fun Fl_Group_resizable as resizable' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Widget)))) => Op (GetResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> resizable' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_add_resizable as addResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (AddResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withRef o $ \\oPtr -> addResizable' groupPtr oPtr\n\n{# fun Fl_Group_init_sizes as initSizes' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (InitSizes ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> initSizes' groupPtr\n\n{# fun Fl_Group_children as children' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Children ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> children' groupPtr\n\n{# fun Fl_Group_set_clip_children as setClipChildren' { id `Ptr ()', cFromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetClipChildren ()) Group orig impl where\n runOp _ _ group c = withRef group $ \\groupPtr -> setClipChildren' groupPtr c\n\n{# fun Fl_Group_clip_children as clipChildren' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (ClipChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clipChildren' groupPtr\n\n{# fun Fl_Group_focus as focus' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (Focus ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> focus' groupPtr wPtr\n\n{# fun Fl_Group__ddfdesign_kludge as ddfdesignKludge' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Widget)))) => Op (DdfdesignKludge ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> ddfdesignKludge' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_insert_with_before as insertWithBefore' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> Ref b -> IO ())) => Op (InsertWithBefore ()) Group orig impl where\n runOp _ _ self w before = withRef self $ \\selfPtr -> withRef w $ \\wPtr -> withRef before $ \\beforePtr -> insertWithBefore' selfPtr wPtr beforePtr\n\n{# fun Fl_Group_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id#}\ninstance (impl ~ (IO [Ref Widget])) => Op (GetArray ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> do\n childArrayPtr <- array' groupPtr\n numChildren <- children group\n arrayToRefs childArrayPtr numChildren\n\n{# fun Fl_Group_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ninstance (impl ~ (Int -> IO (Maybe (Ref Widget)))) => Op (GetChild ()) Group orig impl where\n runOp _ _ self n = withRef self $ \\selfPtr -> child' selfPtr n >>= toMaybeRef\n\n-- $groupfunctions\n-- @\n-- add:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'IO' ()\n--\n-- addResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- begin :: 'Ref' 'Group' -> 'IO' ()\n--\n-- children :: 'Ref' 'Group' -> 'IO' ('Int')\n--\n-- clear :: 'Ref' 'Group' -> 'IO' ()\n--\n-- clipChildren :: 'Ref' 'Group' -> 'IO' ('Bool')\n--\n-- ddfdesignKludge :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- destroy :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- drawChildren :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawOutsideLabel:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- end :: 'Ref' 'Group' -> 'IO' ()\n--\n-- find:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ('Int')\n--\n-- focus:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- getArray :: 'Ref' 'Group' -> 'IO' ['Ref' 'Widget']\n--\n-- getChild :: 'Ref' 'Group' -> 'Int' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- getResizable :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- initSizes :: 'Ref' 'Group' -> 'IO' ()\n--\n-- insert:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'Int' -> 'IO' ()\n--\n-- insertWithBefore:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'Ref' b -> 'IO' ()\n--\n-- removeIndex :: 'Ref' 'Group' -> 'Int' -> 'IO' ()\n--\n-- removeWidget:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- setClipChildren :: 'Ref' 'Group' -> 'Bool' -> 'IO' ()\n--\n-- setNotResizable :: 'Ref' 'Group' -> 'IO' ()\n--\n-- setResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Maybe' ( 'Ref' a ) -> 'IO' ()\n--\n-- updateChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- @\n","old_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Group\n (\n -- * Constructor\n groupNew,\n groupCustom,\n groupSetCurrent,\n groupCurrent,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Group functions\n --\n -- $groupfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Widget\n\n{# fun Fl_Group_set_current as groupSetCurrent' { id `Ptr ()' } -> `()' #}\n{# fun Fl_Group_current as groupCurrent' {} -> `Ptr ()' id #}\n\ngroupSetCurrent :: (Parent a Group) => Maybe (Ref a) -> IO ()\ngroupSetCurrent group = withMaybeRef group $ \\groupPtr -> groupSetCurrent' groupPtr\n\ngroupCurrent :: IO (Maybe (Ref Group))\ngroupCurrent = groupCurrent' >>= toMaybeRef\n\n{# fun Fl_Group_New as groupNew' { `Int',`Int', `Int', `Int'} -> `Ptr ()' id #}\n{# fun Fl_Group_New_WithLabel as groupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text'} -> `Ptr ()' id #}\ngroupNew :: Rectangle -> Maybe T.Text -> IO (Ref Group)\ngroupNew rectangle label' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case label' of\n (Just l') -> groupNewWithLabel' x_pos y_pos width height l' >>= toRef\n Nothing -> groupNew' x_pos y_pos width height >>= toRef\n\n{# fun Fl_OverriddenGroup_New_WithLabel as overriddenGroupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGroup_New as overriddenGroupNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\ngroupCustom :: Rectangle -> Maybe T.Text -> Maybe (Ref Group -> IO ()) -> CustomWidgetFuncs Group -> IO (Ref Group)\ngroupCustom rectangle l' draw' funcs' =\n widgetMaker rectangle l' draw' (Just funcs') overriddenGroupNew' overriddenGroupNewWithLabel'\n\n{# fun Fl_Group_Destroy as groupDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Destroy ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> groupDestroy' groupPtr\n\n\n{# fun Fl_Group_draw_child as drawChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawChild' groupPtr widgetPtr\n\n{# fun Fl_Group_draw_children as drawChildren' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ (IO ())) => Op (DrawChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> drawChildren' groupPtr\n\n{# fun Fl_Group_draw_outside_label as drawOutsideLabel' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawOutsideLabel ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawOutsideLabel' groupPtr widgetPtr\n\n{# fun Fl_Group_update_child as updateChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (UpdateChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> updateChild' groupPtr widgetPtr\n\n{# fun Fl_Group_begin as begin' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Begin ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> begin' groupPtr\n\n{# fun Fl_Group_end as end' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (End ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> end' groupPtr\n\ninstance (\n Match obj ~ FindOp orig orig (Begin ()),\n Match obj ~ FindOp orig orig (End ()),\n Op (Begin ()) obj orig (IO ()),\n Op (End ()) obj orig (IO ()),\n impl ~ (IO () -> IO ())\n ) => Op (Within ()) Group orig impl where\n runOp _ _ group action = withRef group $ \\groupPtr -> do\n () <- begin (castTo group :: Ref orig)\n action\n end (castTo group :: Ref orig)\n\n{# fun Fl_Group_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Find ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> find' groupPtr wPtr\n\n{# fun Fl_Group_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> IO ())) => Op (Add ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> add' groupPtr wPtr\n\n{# fun Fl_Group_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> Int -> IO ())) => Op (Insert ()) Group orig impl where\n runOp _ _ group w i = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> insert' groupPtr wPtr i\n\n{# fun Fl_Group_remove_index as removeIndex' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (RemoveIndex ()) Group orig impl where\n runOp _ _ group index' = withRef group $ \\groupPtr -> removeIndex' groupPtr index'\n\n{# fun Fl_Group_remove_widget as removeWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (RemoveWidget ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> removeWidget' groupPtr wPtr\n\n{# fun Fl_Group_clear as clear' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Clear ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clear' groupPtr\n\n{# fun Fl_Group_set_resizable as setResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Maybe ( Ref a ) -> IO ())) => Op (SetResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withMaybeRef o $ \\oPtr -> setResizable' groupPtr oPtr\n\ninstance (impl ~ IO ()) => Op (SetNotResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> setResizable' groupPtr nullPtr\n\n{# fun Fl_Group_resizable as resizable' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Widget)))) => Op (GetResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> resizable' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_add_resizable as addResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (AddResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withRef o $ \\oPtr -> addResizable' groupPtr oPtr\n\n{# fun Fl_Group_init_sizes as initSizes' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (InitSizes ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> initSizes' groupPtr\n\n{# fun Fl_Group_children as children' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Children ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> children' groupPtr\n\n{# fun Fl_Group_set_clip_children as setClipChildren' { id `Ptr ()', cFromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetClipChildren ()) Group orig impl where\n runOp _ _ group c = withRef group $ \\groupPtr -> setClipChildren' groupPtr c\n\n{# fun Fl_Group_clip_children as clipChildren' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (ClipChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clipChildren' groupPtr\n\n{# fun Fl_Group_focus as focus' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (Focus ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> focus' groupPtr wPtr\n\n{# fun Fl_Group__ddfdesign_kludge as ddfdesignKludge' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Widget)))) => Op (DdfdesignKludge ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> ddfdesignKludge' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_insert_with_before as insertWithBefore' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> Ref b -> IO ())) => Op (InsertWithBefore ()) Group orig impl where\n runOp _ _ self w before = withRef self $ \\selfPtr -> withRef w $ \\wPtr -> withRef before $ \\beforePtr -> insertWithBefore' selfPtr wPtr beforePtr\n\n{# fun Fl_Group_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id#}\ninstance (impl ~ (IO [Ref Widget])) => Op (GetArray ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> do\n childArrayPtr <- array' groupPtr\n numChildren <- children group\n arrayToRefs childArrayPtr numChildren\n\n{# fun Fl_Group_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ninstance (impl ~ (Int -> IO (Maybe (Ref Widget)))) => Op (GetChild ()) Group orig impl where\n runOp _ _ self n = withRef self $ \\selfPtr -> child' selfPtr n >>= toMaybeRef\n\n-- $groupfunctions\n-- @\n-- add:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'IO' ()\n--\n-- addResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- begin :: 'Ref' 'Group' -> 'IO' ()\n--\n-- children :: 'Ref' 'Group' -> 'IO' ('Int')\n--\n-- clear :: 'Ref' 'Group' -> 'IO' ()\n--\n-- clipChildren :: 'Ref' 'Group' -> 'IO' ('Bool')\n--\n-- ddfdesignKludge :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- destroy :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- drawChildren :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawOutsideLabel:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- end :: 'Ref' 'Group' -> 'IO' ()\n--\n-- find:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ('Int')\n--\n-- focus:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- getArray :: 'Ref' 'Group' -> 'IO' ['Ref' 'Widget']\n--\n-- getChild :: 'Ref' 'Group' -> 'Int' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- getResizable :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- initSizes :: 'Ref' 'Group' -> 'IO' ()\n--\n-- insert:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'Int' -> 'IO' ()\n--\n-- insertWithBefore:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'Ref' b -> 'IO' ()\n--\n-- removeIndex :: 'Ref' 'Group' -> 'Int' -> 'IO' ()\n--\n-- removeWidget:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- setClipChildren :: 'Ref' 'Group' -> 'Bool' -> 'IO' ()\n--\n-- setNotResizable :: 'Ref' 'Group' -> 'IO' ()\n--\n-- setResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Maybe' ( 'Ref' a ) -> 'IO' ()\n--\n-- updateChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"f35a5f87ca25ed0470c7725c3212c5cf3c1afaae","subject":"Fix docs.","message":"Fix docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceView.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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-- 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.SourceView (\n-- * Types\n SourceView,\n SourceViewClass,\n SourceSmartHomeEndType(..),\n\n-- * Methods \n castToSourceView,\n sourceViewNew,\n sourceViewNewWithBuffer,\n sourceViewSetAutoIndent,\n sourceViewGetAutoIndent,\n sourceViewSetIndentOnTab,\n sourceViewGetIndentOnTab,\n sourceViewSetIndentWidth,\n sourceViewGetIndentWidth,\n sourceViewSetInsertSpacesInsteadOfTabs,\n sourceViewGetInsertSpacesInsteadOfTabs,\n sourceViewSetSmartHomeEnd,\n sourceViewGetSmartHomeEnd,\n sourceViewSetHighlightCurrentLine,\n sourceViewGetHighlightCurrentLine,\n sourceViewSetShowLineMarks,\n sourceViewGetShowLineMarks,\n sourceViewSetShowLineNumbers,\n sourceViewGetShowLineNumbers,\n sourceViewSetShowRightMargin,\n sourceViewGetShowRightMargin,\n sourceViewSetRightMarginPosition,\n sourceViewGetRightMarginPosition,\n sourceViewSetTabWidth,\n sourceViewGetTabWidth,\n\n-- * Attributes \n sourceViewAutoIndent,\n sourceViewHighlightCurrentLine,\n sourceViewIndentOnTab,\n sourceViewIndentWidth,\n sourceViewInsertSpacesInsteadOfTabs,\n sourceViewRightMarginPosition,\n sourceViewShowLineNumbers,\n sourceViewShowRightMargin,\n sourceViewSmartHomeEnd,\n sourceViewTabWidth,\n\n-- * Signals\n sourceViewUndo,\n sourceViewRedo,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n sourceViewSetMarkCategoryPixbuf,\n sourceViewGetMarkCategoryPixbuf,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSmartHomeEndType {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n-- | Create a new 'SourceView' widget with a default 'SourceBuffer'.\n--\nsourceViewNew :: IO SourceView\nsourceViewNew = makeNewObject mkSourceView $ liftM castPtr\n {#call unsafe source_view_new#}\n\n-- | Create a new 'SourceView'\n-- widget with the given 'SourceBuffer'.\n--\nsourceViewNewWithBuffer :: SourceBuffer -> IO SourceView\nsourceViewNewWithBuffer sb = makeNewObject mkSourceView $ liftM castPtr $\n {#call source_view_new_with_buffer#} sb\n\n-- | If 'True' auto indentation of text is enabled.\n--\nsourceViewSetAutoIndent :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to enable auto indentation. \n -> IO ()\nsourceViewSetAutoIndent sv enable =\n {#call source_view_set_auto_indent#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether auto indentation of text is enabled.\n--\nsourceViewGetAutoIndent :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if auto indentation is enabled. \nsourceViewGetAutoIndent sv = liftM toBool $\n {#call unsafe source_view_get_auto_indent#} (toSourceView sv)\n\n-- | If 'True', when the tab key is pressed and there is a selection, the selected text is indented of one\n-- level instead of being replaced with the \\t characters. Shift+Tab unindents the selection.\n--\nsourceViewSetIndentOnTab :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to indent a block when tab is pressed. \n -> IO ()\nsourceViewSetIndentOnTab sv enable =\n {#call source_view_set_indent_on_tab#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether when the tab key is pressed the current selection should get indented instead of\n-- replaced with the \\t character.\n--\nsourceViewGetIndentOnTab :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the selection is indented when tab is pressed. \nsourceViewGetIndentOnTab sv = liftM toBool $\n {#call unsafe source_view_get_indent_on_tab#} (toSourceView sv)\n\n-- | Sets the number of spaces to use for each step of indent. If width is -1, the value of the\n-- 'tabWidth' property will be used.\n--\nsourceViewSetIndentWidth :: SourceViewClass sv => sv \n -> Int -- ^ @width@ indent width in characters. \n -> IO ()\nsourceViewSetIndentWidth sv width =\n {#call source_view_set_indent_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the number of spaces to use for each step of indent. See 'sourceViewSetIndentWidth'\n-- for details.\n--\nsourceViewGetIndentWidth :: SourceViewClass sv => sv \n -> IO Int -- ^ returns indent width. \nsourceViewGetIndentWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_indent_width#} (toSourceView sv)\n\n-- | If 'True' any tabulator character inserted is replaced by a group of space characters.\n--\nsourceViewSetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv \n -> Bool -- ^ @enable@ whether to insert spaces instead of tabs. \n -> IO ()\nsourceViewSetInsertSpacesInsteadOfTabs sv enable =\n {#call source_view_set_insert_spaces_instead_of_tabs#} (toSourceView sv) (fromBool enable)\n \n-- | Returns whether when inserting a tabulator character it should be replaced by a group of space\n-- characters.\n--\nsourceViewGetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if spaces are inserted instead of tabs. \nsourceViewGetInsertSpacesInsteadOfTabs sv = liftM toBool $\n {#call unsafe source_view_get_insert_spaces_instead_of_tabs#} (toSourceView sv)\n\n-- | Set the desired movement of the cursor when HOME and END keys are pressed.\n--\nsourceViewSetSmartHomeEnd :: SourceViewClass sv => sv \n -> SourceSmartHomeEndType -- ^ @smartHe@ the desired behavior among 'SourceSmartHomeEndType'. \n -> IO ()\nsourceViewSetSmartHomeEnd sv newVal =\n {#call source_view_set_smart_home_end#} (toSourceView sv) (fromIntegral $ fromEnum newVal)\n \n-- | Returns a 'SourceSmartHomeEndType' end value specifying how the cursor will move when HOME and END\n-- keys are pressed.\n--\nsourceViewGetSmartHomeEnd :: SourceViewClass sv => sv \n -> IO SourceSmartHomeEndType -- ^ returns a 'SourceSmartHomeEndTypeend' value. \nsourceViewGetSmartHomeEnd sv = liftM (toEnum . fromIntegral) $\n {#call unsafe source_view_get_smart_home_end#} (toSourceView sv)\n\n-- | If show is 'True' the current line is highlighted.\n--\nsourceViewSetHighlightCurrentLine :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether to highlight the current line \n -> IO ()\nsourceViewSetHighlightCurrentLine sv newVal =\n {#call source_view_set_highlight_current_line#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether the current line is highlighted\n--\nsourceViewGetHighlightCurrentLine :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the current line is highlighted. \nsourceViewGetHighlightCurrentLine sv = liftM toBool $\n {#call unsafe source_view_get_highlight_current_line#} (toSourceView sv)\n\n-- | If 'True' line marks will be displayed beside the text.\n--\nsourceViewSetShowLineMarks :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether line marks should be displayed. \n -> IO ()\nsourceViewSetShowLineMarks sv newVal =\n {#call source_view_set_show_line_marks#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether line marks are displayed beside the text.\n--\nsourceViewGetShowLineMarks :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the line marks are displayed. \nsourceViewGetShowLineMarks sv = liftM toBool $\n {#call unsafe source_view_get_show_line_marks#} (toSourceView sv)\n\n-- | If 'True' line numbers will be displayed beside the text.\n--\nsourceViewSetShowLineNumbers :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether line numbers should be displayed. \n -> IO ()\nsourceViewSetShowLineNumbers sv newVal =\n {#call source_view_set_show_line_numbers#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether line numbers are displayed beside the text.\n--\nsourceViewGetShowLineNumbers :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the line numbers are displayed. \nsourceViewGetShowLineNumbers sv = liftM toBool $\n {#call unsafe source_view_get_show_line_numbers#} (toSourceView sv)\n\n-- | If 'True' a right margin is displayed\n--\nsourceViewSetShowRightMargin :: SourceViewClass sv => sv \n -> Bool -- ^ @show@ whether to show a right margin. \n -> IO ()\nsourceViewSetShowRightMargin sv newVal =\n {#call source_view_set_show_right_margin#} (toSourceView sv) (fromBool newVal)\n \n-- | Returns whether a right margin is displayed.\n--\nsourceViewGetShowRightMargin :: SourceViewClass sv => sv \n -> IO Bool -- ^ returns 'True' if the right margin is shown. \nsourceViewGetShowRightMargin sv = liftM toBool $\n {#call source_view_get_show_right_margin#} (toSourceView sv)\n \n-- | Sets the position of the right margin in the given view.\n--\nsourceViewSetRightMarginPosition :: SourceViewClass sv => sv \n -> Word -- ^ @pos@ the width in characters where to position the right margin. \n -> IO ()\nsourceViewSetRightMarginPosition sv margin =\n {#call source_view_set_right_margin_position#} (toSourceView sv) (fromIntegral margin)\n \n-- | Gets the position of the right margin in the given view.\n--\nsourceViewGetRightMarginPosition :: SourceViewClass sv => sv \n -> IO Int -- ^ returns the position of the right margin. \nsourceViewGetRightMarginPosition sv = liftM fromIntegral $\n {#call unsafe source_view_get_right_margin_position#} (toSourceView sv)\n\n-- | Sets the width of tabulation in characters.\n--\nsourceViewSetTabWidth :: SourceViewClass sv => sv \n -> Int -- ^ @width@ width of tab in characters. \n -> IO ()\nsourceViewSetTabWidth sv width =\n {#call source_view_set_tab_width#} (toSourceView sv) (fromIntegral width)\n \n-- | Returns the width of tabulation in characters.\n--\nsourceViewGetTabWidth :: SourceViewClass sv => sv \n -> IO Int -- ^ returns width of tab. \nsourceViewGetTabWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_tab_width#} (toSourceView sv)\n\n-- | Set the priority for the given mark category. When there are multiple marks on the same line, marks\n-- of categories with higher priorities will be drawn on top.\n--\nsourceViewSetMarkCategoryPriority :: SourceViewClass sv => sv \n -> String -- ^ @category@ a mark category. \n -> Int -- ^ @priority@ the priority for the category \n -> IO ()\nsourceViewSetMarkCategoryPriority sv markerType priority = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_priority#} (toSourceView sv) strPtr (fromIntegral priority)\n\n-- | Gets the priority which is associated with the given category.\n--\nsourceViewGetMarkCategoryPriority :: SourceViewClass sv => sv \n -> String -- ^ @category@ a mark category. \n -> IO Int -- ^ returns the priority or if category exists but no priority was set, it defaults to 0.\nsourceViewGetMarkCategoryPriority sv markerType = withCString markerType $ \\strPtr ->\n liftM fromIntegral $\n {#call unsafe source_view_get_mark_category_priority#} (toSourceView sv) strPtr\n\n-- | Whether to enable auto indentation.\n-- \n-- Default value: 'False'\n--\nsourceViewAutoIndent :: SourceViewClass sv => Attr sv Bool\nsourceViewAutoIndent = newAttrFromBoolProperty \"auto-indent\"\n\n-- | Whether to highlight the current line.\n-- \n-- Default value: 'False'\n--\nsourceViewHighlightCurrentLine :: SourceViewClass sv => Attr sv Bool\nsourceViewHighlightCurrentLine = newAttrFromBoolProperty \"highlight-current-line\"\n\n-- | Whether to indent the selected text when the tab key is pressed.\n-- \n-- Default value: 'True'\n--\nsourceViewIndentOnTab :: SourceViewClass sv => Attr sv Bool\nsourceViewIndentOnTab = newAttrFromBoolProperty \"indent-on-tab\"\n\n-- | Width of an indentation step expressed in number of spaces.\n-- \n-- Allowed values: [GMaxulong,32]\n-- \n-- Default value: -1\n--\nsourceViewIndentWidth :: SourceViewClass sv => Attr sv Int\nsourceViewIndentWidth = newAttrFromIntProperty \"indent-width\"\n\n-- | Whether to insert spaces instead of tabs.\n-- \n-- Default value: 'False'\n--\nsourceViewInsertSpacesInsteadOfTabs :: SourceViewClass sv => Attr sv Bool\nsourceViewInsertSpacesInsteadOfTabs = newAttrFromBoolProperty \"insert-spaces-instead-of-tabs\"\n\n-- | Position of the right margin.\n-- \n-- Allowed values: [1,200]\n-- \n-- Default value: 80\n--\nsourceViewRightMarginPosition :: SourceViewClass sv => Attr sv Int\nsourceViewRightMarginPosition = newAttrFromUIntProperty \"right-margin-position\"\n\n-- | Whether to display line numbers\n-- \n-- Default value: 'False'\n--\nsourceViewShowLineNumbers :: SourceViewClass sv => Attr sv Bool\nsourceViewShowLineNumbers = newAttrFromBoolProperty \"show-line-numbers\"\n\n-- | Whether to display line mark pixbufs\n-- \n-- Default value: 'False'\n--\nsourceViewShowRightMargin :: SourceViewClass sv => Attr sv Bool\nsourceViewShowRightMargin = newAttrFromBoolProperty \"show-right-margin\"\n\n-- | Set the behavior of the HOME and END keys.\n-- \n-- Default value: 'SourceSmartHomeEndDisabled'\n-- \n-- Since 2.0\n--\nsourceViewSmartHomeEnd :: SourceViewClass sv => Attr sv SourceSmartHomeEndType\nsourceViewSmartHomeEnd = newAttrFromEnumProperty \"smart-home-end\" {#call fun gtk_source_smart_home_end_type_get_type#}\n\n-- | Width of an tab character expressed in number of spaces.\n-- \n-- Allowed values: [1,32]\n-- \n-- Default value: 8\n--\nsourceViewTabWidth :: SourceViewClass sv => Attr sv Int\nsourceViewTabWidth = newAttrFromUIntProperty \"tab-width\"\n\n-- |\n--\nsourceViewUndo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewUndo = Signal $ connect_NONE__NONE \"undo\"\n\n-- |\n--\nsourceViewRedo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewRedo = Signal $ connect_NONE__NONE \"redo\"\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | 'sourceViewSetMarkCategoryPixbuf' is deprecated and should not be used in newly-written\n-- code. Use 'sourceViewSetMarkCategoryIconFromPixbuf' instead\n--\nsourceViewSetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> Pixbuf -> IO ()\nsourceViewSetMarkCategoryPixbuf sv markerType marker = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_pixbuf#} (toSourceView sv) strPtr marker\n\n-- | 'sourceViewGetMarkCategoryPixbuf' is deprecated and should not be used in newly-written code.\n--\nsourceViewGetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> IO Pixbuf\nsourceViewGetMarkCategoryPixbuf sv markerType = withCString markerType $ \\strPtr ->\n constructNewGObject mkPixbuf $\n {#call unsafe source_view_get_mark_category_pixbuf#} (toSourceView sv) strPtr\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceView (\n SourceView,\n SourceViewClass,\n SourceSmartHomeEndType(..),\n castToSourceView,\n sourceViewNew,\n sourceViewNewWithBuffer,\n sourceViewSetAutoIndent,\n sourceViewGetAutoIndent,\n sourceViewSetIndentOnTab,\n sourceViewGetIndentOnTab,\n sourceViewSetIndentWidth,\n sourceViewGetIndentWidth,\n sourceViewSetInsertSpacesInsteadOfTabs,\n sourceViewGetInsertSpacesInsteadOfTabs,\n sourceViewSetSmartHomeEnd,\n sourceViewGetSmartHomeEnd,\n sourceViewSetHighlightCurrentLine,\n sourceViewGetHighlightCurrentLine,\n sourceViewSetShowLineMarks,\n sourceViewGetShowLineMarks,\n sourceViewSetShowLineNumbers,\n sourceViewGetShowLineNumbers,\n sourceViewSetShowRightMargin,\n sourceViewGetShowRightMargin,\n sourceViewSetRightMarginPosition,\n sourceViewGetRightMarginPosition,\n sourceViewSetTabWidth,\n sourceViewGetTabWidth,\n sourceViewSetMarkCategoryPixbuf,\n sourceViewGetMarkCategoryPixbuf,\n sourceViewAutoIndent,\n sourceViewHighlightCurrentLine,\n sourceViewIndentOnTab,\n sourceViewIndentWidth,\n sourceViewInsertSpacesInsteadOfTabs,\n sourceViewRightMarginPosition,\n sourceViewShowLineNumbers,\n sourceViewShowRightMargin,\n sourceViewSmartHomeEnd,\n sourceViewTabWidth,\n sourceViewUndo,\n sourceViewRedo\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSmartHomeEndType {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n-- | Create a new 'SourceView' widget with a default 'SourceBuffer'.\n--\nsourceViewNew :: IO SourceView\nsourceViewNew = makeNewObject mkSourceView $ liftM castPtr\n {#call unsafe source_view_new#}\n\n-- | Create a new 'SourceView'\n-- widget with the given 'SourceBuffer'.\n--\nsourceViewNewWithBuffer :: SourceBuffer -> IO SourceView\nsourceViewNewWithBuffer sb = makeNewObject mkSourceView $ liftM castPtr $\n {#call source_view_new_with_buffer#} sb\n\n-- | \n--\nsourceViewSetAutoIndent :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetAutoIndent sv newVal =\n {#call source_view_set_auto_indent#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetAutoIndent :: SourceViewClass sv => sv -> IO Bool \nsourceViewGetAutoIndent sv = liftM toBool $\n {#call unsafe source_view_get_auto_indent#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetIndentOnTab :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetIndentOnTab sv newVal =\n {#call source_view_set_indent_on_tab#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetIndentOnTab :: SourceViewClass sv => sv -> IO Bool \nsourceViewGetIndentOnTab sv = liftM toBool $\n {#call unsafe source_view_get_indent_on_tab#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetIndentWidth :: SourceViewClass sv => sv -> Int -> IO ()\nsourceViewSetIndentWidth sv newVal =\n {#call source_view_set_indent_width#} (toSourceView sv) (fromIntegral newVal)\n\n-- | \n--\nsourceViewGetIndentWidth :: SourceViewClass sv => sv -> IO Int\nsourceViewGetIndentWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_indent_width#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetInsertSpacesInsteadOfTabs sv newVal =\n {#call source_view_set_insert_spaces_instead_of_tabs#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv -> IO Bool \nsourceViewGetInsertSpacesInsteadOfTabs sv = liftM toBool $\n {#call unsafe source_view_get_insert_spaces_instead_of_tabs#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetSmartHomeEnd :: SourceViewClass sv => sv -> SourceSmartHomeEndType -> IO ()\nsourceViewSetSmartHomeEnd sv newVal =\n {#call source_view_set_smart_home_end#} (toSourceView sv) (fromIntegral $ fromEnum newVal)\n \n-- | \n--\nsourceViewGetSmartHomeEnd :: SourceViewClass sv => sv -> IO SourceSmartHomeEndType\nsourceViewGetSmartHomeEnd sv = liftM (toEnum . fromIntegral) $\n {#call unsafe source_view_get_smart_home_end#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetHighlightCurrentLine :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetHighlightCurrentLine sv newVal =\n {#call source_view_set_highlight_current_line#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetHighlightCurrentLine :: SourceViewClass sv => sv -> IO Bool \nsourceViewGetHighlightCurrentLine sv = liftM toBool $\n {#call unsafe source_view_get_highlight_current_line#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetShowLineMarks :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetShowLineMarks sv newVal =\n {#call source_view_set_show_line_marks#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetShowLineMarks :: SourceViewClass sv => sv -> IO Bool \nsourceViewGetShowLineMarks sv = liftM toBool $\n {#call unsafe source_view_get_show_line_marks#} (toSourceView sv)\n\n--- | \n--\nsourceViewSetShowLineNumbers :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetShowLineNumbers sv newVal =\n {#call source_view_set_show_line_numbers#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetShowLineNumbers :: SourceViewClass sv => sv -> IO Bool \nsourceViewGetShowLineNumbers sv = liftM toBool $\n {#call unsafe source_view_get_show_line_numbers#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetShowRightMargin :: SourceViewClass sv => sv -> Bool -> IO ()\nsourceViewSetShowRightMargin sv newVal =\n {#call source_view_set_show_right_margin#} (toSourceView sv) (fromBool newVal)\n \n-- | \n--\nsourceViewGetShowRightMargin :: SourceViewClass sv => sv -> IO Bool\nsourceViewGetShowRightMargin sv = liftM toBool $\n {#call source_view_get_show_right_margin#} (toSourceView sv)\n \n-- | \n--\nsourceViewSetRightMarginPosition :: SourceViewClass sv => sv -> Word -> IO ()\nsourceViewSetRightMarginPosition sv margin =\n {#call source_view_set_right_margin_position#} (toSourceView sv) (fromIntegral margin)\n \n-- | \n--\nsourceViewGetRightMarginPosition :: SourceViewClass sv => sv -> IO Int \nsourceViewGetRightMarginPosition sv = liftM fromIntegral $\n {#call unsafe source_view_get_right_margin_position#} (toSourceView sv)\n\n-- | \n--\nsourceViewSetTabWidth :: SourceViewClass sv => sv -> Int -> IO ()\nsourceViewSetTabWidth sv width =\n {#call source_view_set_tab_width#} (toSourceView sv) (fromIntegral width)\n \n-- | \n--\nsourceViewGetTabWidth :: SourceViewClass sv => sv -> IO Int \nsourceViewGetTabWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_tab_width#} (toSourceView sv)\n\n-- |\n--\nsourceViewSetMarkCategoryPriority :: SourceViewClass sv => sv -> String -> Int -> IO ()\nsourceViewSetMarkCategoryPriority sv markerType priority = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_priority#} (toSourceView sv) strPtr (fromIntegral priority)\n\n-- |\n--\nsourceViewGetMarkCategoryPriority :: SourceViewClass sv => sv -> String -> IO Int\nsourceViewGetMarkCategoryPriority sv markerType = withCString markerType $ \\strPtr ->\n liftM fromIntegral $\n {#call unsafe source_view_get_mark_category_priority#} (toSourceView sv) strPtr\n\n--- |\n--\nsourceViewSetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> Pixbuf -> IO ()\nsourceViewSetMarkCategoryPixbuf sv markerType marker = withCString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_pixbuf#} (toSourceView sv) strPtr marker\n\n-- |\n--\nsourceViewGetMarkCategoryPixbuf :: SourceViewClass sv => sv -> String -> IO Pixbuf\nsourceViewGetMarkCategoryPixbuf sv markerType = withCString markerType $ \\strPtr ->\n constructNewGObject mkPixbuf $\n {#call unsafe source_view_get_mark_category_pixbuf#} (toSourceView sv) strPtr\n\n-- |\n--\nsourceViewAutoIndent :: SourceViewClass sv => Attr sv Bool\nsourceViewAutoIndent = newAttrFromBoolProperty \"auto-indent\"\n\n-- |\n--\nsourceViewHighlightCurrentLine :: SourceViewClass sv => Attr sv Bool\nsourceViewHighlightCurrentLine = newAttrFromBoolProperty \"highlight-current-line\"\n\n-- |\n--\nsourceViewIndentOnTab :: SourceViewClass sv => Attr sv Bool\nsourceViewIndentOnTab = newAttrFromBoolProperty \"indent-on-tab\"\n\n-- |\n--\nsourceViewIndentWidth :: SourceViewClass sv => Attr sv Int\nsourceViewIndentWidth = newAttrFromIntProperty \"indent-width\"\n\n-- |\n--\nsourceViewInsertSpacesInsteadOfTabs :: SourceViewClass sv => Attr sv Bool\nsourceViewInsertSpacesInsteadOfTabs = newAttrFromBoolProperty \"insert-spaces-instead-of-tabs\"\n\n-- |\n--\nsourceViewRightMarginPosition :: SourceViewClass sv => Attr sv Int\nsourceViewRightMarginPosition = newAttrFromUIntProperty \"right-margin-position\"\n\n-- |\n--\nsourceViewShowLineNumbers :: SourceViewClass sv => Attr sv Bool\nsourceViewShowLineNumbers = newAttrFromBoolProperty \"show-line-numbers\"\n\n-- |\n--\nsourceViewShowRightMargin :: SourceViewClass sv => Attr sv Bool\nsourceViewShowRightMargin = newAttrFromBoolProperty \"show-right-margin\"\n\n-- |\n--\nsourceViewSmartHomeEnd :: SourceViewClass sv => Attr sv SourceSmartHomeEndType\nsourceViewSmartHomeEnd = newAttrFromEnumProperty \"smart-home-end\" {#call fun gtk_source_smart_home_end_type_get_type#}\n\n-- |\n--\nsourceViewTabWidth :: SourceViewClass sv => Attr sv Int\nsourceViewTabWidth = newAttrFromUIntProperty \"tab-width\"\n\n-- |\n--\nsourceViewUndo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewUndo = Signal $ connect_NONE__NONE \"undo\"\n\n-- |\n--\nsourceViewRedo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewRedo = Signal $ connect_NONE__NONE \"redo\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9dfca4dccb6a1381c316254a1460b0ec6dbf97c8","subject":"LLVM stores its branch arguments in a strange order.","message":"LLVM stores its branch arguments in a strange order.\n\nThis is documented in their headers but not the doxygen (or anywhere\nelse, really).\n","repos":"travitch\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/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 ( 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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , typeIdSrc :: IORef Int\n , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> IORef Int -> KnotState\nemptyState r1 r2 = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref)\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 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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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","old_contents":"{-# 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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , typeIdSrc :: IORef Int\n , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> IORef Int -> KnotState\nemptyState r1 r2 = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref)\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 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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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\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 { 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"30d9b1e81b29717b3fb78ec18f884ced093dc784","subject":"Fix IconTheme to only compile if gio is present.","message":"Fix IconTheme to only compile if gio is present.\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items, such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0) && HAVE_GIO\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0) && HAVE_GIO\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b609445c618d4dcc87127795f7faa0dd02104841","subject":"Update SourceMark to 2.10.4","message":"Update SourceMark to 2.10.4\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n\n-- * Methods\n castToSourceMark,\n sourceMarkNew,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev,\n\n-- * Attributes\n sourceMarkCategory\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Creates a text mark. Add it to a buffer using 'textBufferAddMark'. If name is 'Nothing', the mark\n-- is anonymous; otherwise, the mark can be retrieved by name using\n-- 'textBufferGetMark'. Normally marks are created using the utility function\n-- 'sourceBufferCreateMark'.\nsourceMarkNew :: Maybe String -- ^ @name@ Name of the 'SourceMark', can be 'Nothing' when not using a name\n -> String -- ^ @category@ is used to classify marks according to common characteristics (e.g. all the marks representing a bookmark could \n -> IO SourceMark\nsourceMarkNew name category = \n makeNewGObject mkSourceMark $\n maybeWith withUTFString name $ \\namePtr ->\n withUTFString category $ \\categoryPtr ->\n {#call gtk_source_mark_new#}\n namePtr\n categoryPtr\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n-- | The category of the 'SourceMark', classifies the mark and controls which pixbuf is used and with\n-- which priority it is drawn.\n-- Default value: \\\"\\\"\n--\nsourceMarkCategory :: Attr SourceMark String\nsourceMarkCategory = newAttrFromStringProperty \"category\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n\n-- * Methods\n castToSourceMark,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f9fa4c2115859496af7671dcab39476ea3df5528","subject":"Fix gtksourceview2","message":"Fix gtksourceview2\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceView.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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-- 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.SourceView (\n-- * Description\n-- | 'SourceView' is the main object of the gtksourceview library. It provides a text view which syntax\n-- highlighting, undo\/redo and text marks. Use a 'SourceBuffer' to display text with a 'SourceView'.\n\n-- * Types\n SourceView,\n SourceViewClass,\n\n-- * Enums\n SourceSmartHomeEndType(..),\n SourceDrawSpacesFlags(..),\n SourceViewGutterPosition (..),\n\n-- * Methods\n castToSourceView,\n gTypeSourceView,\n toSourceView,\n sourceViewNew,\n sourceViewNewWithBuffer,\n sourceViewSetAutoIndent,\n sourceViewGetAutoIndent,\n sourceViewSetIndentOnTab,\n sourceViewGetIndentOnTab,\n sourceViewSetIndentWidth,\n sourceViewGetIndentWidth,\n sourceViewSetInsertSpacesInsteadOfTabs,\n sourceViewGetInsertSpacesInsteadOfTabs,\n sourceViewSetSmartHomeEnd,\n sourceViewGetSmartHomeEnd,\n#if GTK_MAJOR_VERSION < 3\n sourceViewSetMarkCategoryPriority,\n sourceViewGetMarkCategoryPriority,\n sourceViewSetMarkCategoryIconFromPixbuf,\n sourceViewSetMarkCategoryIconFromStock,\n sourceViewSetMarkCategoryIconFromIconName,\n sourceViewSetMarkCategoryBackground,\n sourceViewGetMarkCategoryBackground,\n#endif\n sourceViewSetHighlightCurrentLine,\n sourceViewGetHighlightCurrentLine,\n sourceViewSetShowLineMarks,\n sourceViewGetShowLineMarks,\n sourceViewSetShowLineNumbers,\n sourceViewGetShowLineNumbers,\n sourceViewSetShowRightMargin,\n sourceViewGetShowRightMargin,\n sourceViewSetRightMarginPosition,\n sourceViewGetRightMarginPosition,\n sourceViewSetTabWidth,\n sourceViewGetTabWidth,\n sourceViewSetDrawSpaces,\n sourceViewGetDrawSpaces,\n sourceViewGetGutter,\n\n#if GTK_MAJOR_VERSION >= 3\n#if MIN_VERSION_gtksourceview_3_0(3, 16, 0)\n sourceViewIndentLines,\n sourceViewUnindentLines,\n#endif\n sourceViewGetVisualColumn,\n sourceViewSetMarkAttributes,\n sourceViewGetMarkAttributes,\n#endif\n\n-- * Attributes\n sourceViewAutoIndent,\n sourceViewCompletion,\n sourceViewDrawSpaces,\n sourceViewHighlightCurrentLine,\n sourceViewIndentOnTab,\n sourceViewIndentWidth,\n sourceViewInsertSpacesInsteadOfTabs,\n sourceViewRightMarginPosition,\n sourceViewShowLineNumbers,\n sourceViewShowRightMargin,\n sourceViewSmartHomeEnd,\n sourceViewTabWidth,\n\n-- * Signals\n sourceViewUndo,\n sourceViewRedo,\n sourceViewMoveLines,\n sourceViewShowCompletion,\n sourceViewLineMarkActivated,\n\n-- * Deprecated\n#if GTK_MAJOR_VERSION < 3\n#ifndef DISABLE_DEPRECATED\n sourceViewSetMarkCategoryPixbuf,\n sourceViewGetMarkCategoryPixbuf,\n#endif\n#endif\n ) where\n\nimport Control.Applicative\nimport Prelude\nimport Control.Monad (liftM)\nimport Control.Monad.Reader ( runReaderT )\nimport Data.Maybe (fromMaybe)\n\nimport Graphics.UI.Gtk.Abstract.Object (makeNewObject)\nimport Graphics.UI.Gtk.Abstract.Widget (Color)\nimport Graphics.UI.Gtk.Gdk.EventM (EventM, EAny)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.SourceView.Enums\nimport Graphics.UI.GtkInternals ( TextIter, mkTextIterCopy )\nimport System.Glib.GObject (wrapNewGObject, makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags (toFlags, fromFlags)\n\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import System.Glib.Properties#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Create a new 'SourceView' widget with a default 'SourceBuffer'.\n--\nsourceViewNew :: IO SourceView\nsourceViewNew = makeNewObject mkSourceView $ liftM castPtr\n {#call unsafe source_view_new#}\n\n-- | Create a new 'SourceView'\n-- widget with the given 'SourceBuffer'.\n--\nsourceViewNewWithBuffer :: SourceBuffer -> IO SourceView\nsourceViewNewWithBuffer sb = makeNewObject mkSourceView $ liftM castPtr $\n {#call source_view_new_with_buffer#} sb\n\n-- | If 'True' auto indentation of text is enabled.\n--\nsourceViewSetAutoIndent :: SourceViewClass sv => sv\n -> Bool -- ^ @enable@ whether to enable auto indentation.\n -> IO ()\nsourceViewSetAutoIndent sv enable =\n {#call source_view_set_auto_indent#} (toSourceView sv) (fromBool enable)\n\n-- | Returns whether auto indentation of text is enabled.\n--\nsourceViewGetAutoIndent :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if auto indentation is enabled.\nsourceViewGetAutoIndent sv = liftM toBool $\n {#call unsafe source_view_get_auto_indent#} (toSourceView sv)\n\n-- | If 'True', when the tab key is pressed and there is a selection, the selected text is indented of one\n-- level instead of being replaced with the \\t characters. Shift+Tab unindents the selection.\n--\nsourceViewSetIndentOnTab :: SourceViewClass sv => sv\n -> Bool -- ^ @enable@ whether to indent a block when tab is pressed.\n -> IO ()\nsourceViewSetIndentOnTab sv enable =\n {#call source_view_set_indent_on_tab#} (toSourceView sv) (fromBool enable)\n\n-- | Returns whether when the tab key is pressed the current selection should get indented instead of\n-- replaced with the \\t character.\n--\nsourceViewGetIndentOnTab :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the selection is indented when tab is pressed.\nsourceViewGetIndentOnTab sv = liftM toBool $\n {#call unsafe source_view_get_indent_on_tab#} (toSourceView sv)\n\n-- | Sets the number of spaces to use for each step of indent. If width is -1, the value of the\n-- 'tabWidth' property will be used.\n--\nsourceViewSetIndentWidth :: SourceViewClass sv => sv\n -> Int -- ^ @width@ indent width in characters.\n -> IO ()\nsourceViewSetIndentWidth sv width =\n {#call source_view_set_indent_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the number of spaces to use for each step of indent. See 'sourceViewSetIndentWidth'\n-- for details.\n--\nsourceViewGetIndentWidth :: SourceViewClass sv => sv\n -> IO Int -- ^ returns indent width.\nsourceViewGetIndentWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_indent_width#} (toSourceView sv)\n\n-- | If 'True' any tabulator character inserted is replaced by a group of space characters.\n--\nsourceViewSetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv\n -> Bool -- ^ @enable@ whether to insert spaces instead of tabs.\n -> IO ()\nsourceViewSetInsertSpacesInsteadOfTabs sv enable =\n {#call source_view_set_insert_spaces_instead_of_tabs#} (toSourceView sv) (fromBool enable)\n\n-- | Returns whether when inserting a tabulator character it should be replaced by a group of space\n-- characters.\n--\nsourceViewGetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if spaces are inserted instead of tabs.\nsourceViewGetInsertSpacesInsteadOfTabs sv = liftM toBool $\n {#call unsafe source_view_get_insert_spaces_instead_of_tabs#} (toSourceView sv)\n\n-- | Set the desired movement of the cursor when HOME and END keys are pressed.\n--\nsourceViewSetSmartHomeEnd :: SourceViewClass sv => sv\n -> SourceSmartHomeEndType -- ^ @smartHe@ the desired behavior among 'SourceSmartHomeEndType'.\n -> IO ()\nsourceViewSetSmartHomeEnd sv newVal =\n {#call source_view_set_smart_home_end#} (toSourceView sv) (fromIntegral $ fromEnum newVal)\n\n-- | Returns a 'SourceSmartHomeEndType' end value specifying how the cursor will move when HOME and END\n-- keys are pressed.\n--\nsourceViewGetSmartHomeEnd :: SourceViewClass sv => sv\n -> IO SourceSmartHomeEndType -- ^ returns a 'SourceSmartHomeEndTypeend' value.\nsourceViewGetSmartHomeEnd sv = liftM (toEnum . fromIntegral) $\n {#call unsafe source_view_get_smart_home_end#} (toSourceView sv)\n\n-- | If show is 'True' the current line is highlighted.\n--\nsourceViewSetHighlightCurrentLine :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether to highlight the current line\n -> IO ()\nsourceViewSetHighlightCurrentLine sv newVal =\n {#call source_view_set_highlight_current_line#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether the current line is highlighted\n--\nsourceViewGetHighlightCurrentLine :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the current line is highlighted.\nsourceViewGetHighlightCurrentLine sv = liftM toBool $\n {#call unsafe source_view_get_highlight_current_line#} (toSourceView sv)\n\n-- | If 'True' line marks will be displayed beside the text.\n--\nsourceViewSetShowLineMarks :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether line marks should be displayed.\n -> IO ()\nsourceViewSetShowLineMarks sv newVal =\n {#call source_view_set_show_line_marks#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether line marks are displayed beside the text.\n--\nsourceViewGetShowLineMarks :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the line marks are displayed.\nsourceViewGetShowLineMarks sv = liftM toBool $\n {#call unsafe source_view_get_show_line_marks#} (toSourceView sv)\n\n-- | If 'True' line numbers will be displayed beside the text.\n--\nsourceViewSetShowLineNumbers :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether line numbers should be displayed.\n -> IO ()\nsourceViewSetShowLineNumbers sv newVal =\n {#call source_view_set_show_line_numbers#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether line numbers are displayed beside the text.\n--\nsourceViewGetShowLineNumbers :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the line numbers are displayed.\nsourceViewGetShowLineNumbers sv = liftM toBool $\n {#call unsafe source_view_get_show_line_numbers#} (toSourceView sv)\n\n-- | If 'True' a right margin is displayed\n--\nsourceViewSetShowRightMargin :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether to show a right margin.\n -> IO ()\nsourceViewSetShowRightMargin sv newVal =\n {#call source_view_set_show_right_margin#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether a right margin is displayed.\n--\nsourceViewGetShowRightMargin :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the right margin is shown.\nsourceViewGetShowRightMargin sv = liftM toBool $\n {#call source_view_get_show_right_margin#} (toSourceView sv)\n\n-- | Sets the position of the right margin in the given view.\n--\nsourceViewSetRightMarginPosition :: SourceViewClass sv => sv\n -> Word -- ^ @pos@ the width in characters where to position the right margin.\n -> IO ()\nsourceViewSetRightMarginPosition sv margin =\n {#call source_view_set_right_margin_position#} (toSourceView sv) (fromIntegral margin)\n\n-- | Gets the position of the right margin in the given view.\n--\nsourceViewGetRightMarginPosition :: SourceViewClass sv => sv\n -> IO Int -- ^ returns the position of the right margin.\nsourceViewGetRightMarginPosition sv = liftM fromIntegral $\n {#call unsafe source_view_get_right_margin_position#} (toSourceView sv)\n\n-- | Sets the width of tabulation in characters.\n--\nsourceViewSetTabWidth :: SourceViewClass sv => sv\n -> Int -- ^ @width@ width of tab in characters.\n -> IO ()\nsourceViewSetTabWidth sv width =\n {#call source_view_set_tab_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the width of tabulation in characters.\n--\nsourceViewGetTabWidth :: SourceViewClass sv => sv\n -> IO Int -- ^ returns width of tab.\nsourceViewGetTabWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_tab_width#} (toSourceView sv)\n\n-- | Set if and how the spaces should be visualized. Specifying flags as [] will disable display of\n-- spaces.\nsourceViewSetDrawSpaces :: SourceViewClass sv => sv\n -> [SourceDrawSpacesFlags] -- ^ @flags@ 'SourceDrawSpacesFlags' specifing how white spaces should be displayed\n -> IO ()\nsourceViewSetDrawSpaces view flags =\n {#call gtk_source_view_set_draw_spaces #}\n (toSourceView view)\n (fromIntegral $ fromFlags flags)\n\n-- | Returns the 'SourceDrawSpacesFlags' specifying if and how spaces should be displayed for this view.\nsourceViewGetDrawSpaces :: SourceViewClass sv => sv\n -> IO [SourceDrawSpacesFlags] -- ^ returns the 'SourceDrawSpacesFlags', [] if no spaces should be drawn.\nsourceViewGetDrawSpaces view =\n liftM (toFlags . fromIntegral) $\n {#call gtk_source_view_get_draw_spaces #}\n (toSourceView view)\n\n-- | Returns the 'SourceGutter' object associated with @windowType@ for view. Only 'TextWindowLeft'\n-- and 'TextWindowRight' are supported, respectively corresponding to the left and right\n-- gutter. The line numbers and mark category icons are rendered in the gutter corresponding to\n-- 'TextWindowLeft'.\nsourceViewGetGutter :: SourceViewClass sv => sv\n -> TextWindowType -- ^ @windowType@ the gutter window type\n -> IO SourceGutter\nsourceViewGetGutter sv windowType =\n makeNewGObject mkSourceGutter $\n {#call gtk_source_view_get_gutter #}\n (toSourceView sv)\n (fromIntegral $ fromEnum windowType)\n\n#if GTK_MAJOR_VERSION < 3\n-- | Set the priority for the given mark category. When there are multiple marks on the same line, marks\n-- of categories with higher priorities will be drawn on top.\n--\nsourceViewSetMarkCategoryPriority :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Int -- ^ @priority@ the priority for the category\n -> IO ()\nsourceViewSetMarkCategoryPriority sv markerType priority = withUTFString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_priority#} (toSourceView sv) strPtr (fromIntegral priority)\n\n-- | Gets the priority which is associated with the given category.\n--\nsourceViewGetMarkCategoryPriority :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> IO Int -- ^ returns the priority or if category exists but no priority was set, it defaults to 0.\nsourceViewGetMarkCategoryPriority sv markerType = withUTFString markerType $ \\strPtr ->\n liftM fromIntegral $\n {#call unsafe source_view_get_mark_category_priority#} (toSourceView sv) strPtr\n\n-- | Sets the icon to be used for category to pixbuf. If pixbuf is 'Nothing', the icon is unset.\nsourceViewSetMarkCategoryIconFromPixbuf :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe Pixbuf -- ^ @pixbuf@ a 'Pixbuf' or 'Nothing'.\n -> IO ()\nsourceViewSetMarkCategoryIconFromPixbuf sv category pixbuf =\n withUTFString category $ \\categoryPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_pixbuf #}\n (toSourceView sv)\n categoryPtr\n (fromMaybe (Pixbuf nullForeignPtr) pixbuf)\n\n-- | Sets the icon to be used for category to the stock item @stockId@. If @stockId@ is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromStock :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe string -- ^ @stockId@ the stock id or 'Nothing'.\n -> IO ()\nsourceViewSetMarkCategoryIconFromStock sv category stockId =\n withUTFString category $ \\categoryPtr ->\n maybeWith withUTFString stockId $ \\stockIdPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_stock #}\n (toSourceView sv)\n categoryPtr\n stockIdPtr\n\n-- | Sets the icon to be used for category to the named theme item name. If name is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromIconName :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe string -- ^ @name@ the themed icon name or 'Nothing'.\n -> IO ()\nsourceViewSetMarkCategoryIconFromIconName sv category name =\n withUTFString category $ \\categoryPtr ->\n maybeWith withUTFString name $ \\namePtr ->\n {#call gtk_source_view_set_mark_category_icon_from_icon_name #}\n (toSourceView sv)\n categoryPtr\n namePtr\n\n-- | Sets given background color for mark category. If color is 'Nothing', the background color is unset.\nsourceViewSetMarkCategoryBackground :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe Color -- ^ @color@ background color or 'Nothing' to unset it.\n -> IO ()\nsourceViewSetMarkCategoryBackground sv category color =\n let withMB :: Storable a => Maybe a -> (Ptr a -> IO b) -> IO b\n withMB Nothing f = f nullPtr\n withMB (Just x) f = with x f\n in withUTFString category $ \\categoryPtr ->\n withMB color $ \\colorPtr ->\n {#call gtk_source_view_set_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n\n-- | Gets the background color associated with given category.\nsourceViewGetMarkCategoryBackground :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Color -- ^ @dest@ destination 'Color' structure to fill in.\n -> IO Bool -- ^ returns 'True' if background color for category was set and dest is set to a valid color, or 'False' otherwise.\nsourceViewGetMarkCategoryBackground sv category color =\n liftM toBool $\n withUTFString category $ \\ categoryPtr ->\n with color $ \\ colorPtr ->\n {#call gtk_source_view_get_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n#endif\n\n#if GTK_MAJOR_VERSION >= 3\n#if MIN_VERSION_gtksourceview_3_0(3, 16, 0)\n-- | Insert one indentation level at the beginning of the specified lines.\n--\nsourceViewIndentLines :: SourceViewClass sv\n => sv\n -> TextIter -- ^ @start@ the first line to indent.\n -> TextIter -- ^ @end@ the last line to indent.\n -> IO ()\nsourceViewIndentLines sv start end =\n {# call gtk_source_view_indent_lines #}\n (toSourceView sv)\n start\n end\n\n-- | Removes one indentation level at the beginning of the specified lines.\n--\nsourceViewUnindentLines :: SourceViewClass sv\n => sv\n -> TextIter -- ^ @start@ the first line to indent.\n -> TextIter -- ^ @end@ the last line to indent.\n -> IO ()\nsourceViewUnindentLines sv start end =\n {# call gtk_source_view_unindent_lines #}\n (toSourceView sv)\n start\n end\n#endif\n\n-- | Determines the visual column at iter taking into consideration the `tabWidth` of the view.\n--\nsourceViewGetVisualColumn :: SourceViewClass sv\n => sv\n -> TextIter -- ^ @iter@ a position in view.\n -> IO Word\nsourceViewGetVisualColumn sv iter = fromIntegral <$>\n {# call gtk_source_view_get_visual_column #}\n (toSourceView sv)\n iter\n\n-- | Sets attributes and priority for the category.\n--\nsourceViewSetMarkAttributes :: (SourceViewClass sv, GlibString category, SourceMarkAttributesClass attributes)\n => sv\n -> category\n -> Maybe attributes\n -> Int\n -> IO ()\nsourceViewSetMarkAttributes sv category attributes priority =\n withUTFString category $ \\categoryPtr ->\n {# call gtk_source_view_set_mark_attributes #}\n (toSourceView sv)\n categoryPtr\n (maybe (SourceMarkAttributes nullForeignPtr) toSourceMarkAttributes attributes)\n (fromIntegral priority)\n\n-- | Gets attributes and priority for the category\n--\nsourceViewGetMarkAttributes :: (SourceViewClass sv, GlibString category)\n => sv\n -> category\n -> IO (Maybe (SourceMarkAttributes, Int))\nsourceViewGetMarkAttributes sv category =\n withUTFString category $ \\categoryPtr ->\n alloca $ \\ priority -> do\n attributes <- maybeNull (makeNewObject mkSourceMarkAttributes) $\n {# call gtk_source_view_get_mark_attributes #}\n (toSourceView sv)\n categoryPtr\n priority\n case attributes of\n Just a -> do\n p <- peek priority\n return $ Just (a, fromIntegral p)\n Nothing -> return Nothing\n#endif\n\n-- | Whether to enable auto indentation.\n--\n-- Default value: 'False'\n--\nsourceViewAutoIndent :: SourceViewClass sv => Attr sv Bool\nsourceViewAutoIndent = newAttrFromBoolProperty \"auto-indent\"\n\n-- | The completion object associated with the view.\n--\nsourceViewCompletion :: SourceViewClass sv => ReadAttr sv SourceCompletion\nsourceViewCompletion = readAttrFromObjectProperty \"completion\"\n {#call pure unsafe gtk_source_completion_get_type #}\n\n-- | Set if and how the spaces should be visualized.\n--\nsourceViewDrawSpaces :: SourceViewClass sv => Attr sv [SourceDrawSpacesFlags]\nsourceViewDrawSpaces = newAttrFromFlagsProperty \"draw-spaces\" {#call fun gtk_source_draw_spaces_flags_get_type#}\n\n-- | Whether to highlight the current line.\n--\n-- Default value: 'False'\n--\nsourceViewHighlightCurrentLine :: SourceViewClass sv => Attr sv Bool\nsourceViewHighlightCurrentLine = newAttrFromBoolProperty \"highlight-current-line\"\n\n-- | Whether to indent the selected text when the tab key is pressed.\n--\n-- Default value: 'True'\n--\nsourceViewIndentOnTab :: SourceViewClass sv => Attr sv Bool\nsourceViewIndentOnTab = newAttrFromBoolProperty \"indent-on-tab\"\n\n-- | Width of an indentation step expressed in number of spaces.\n--\n-- Allowed values: [GMaxulong,32]\n--\n-- Default value: -1\n--\nsourceViewIndentWidth :: SourceViewClass sv => Attr sv Int\nsourceViewIndentWidth = newAttrFromIntProperty \"indent-width\"\n\n-- | Whether to insert spaces instead of tabs.\n--\n-- Default value: 'False'\n--\nsourceViewInsertSpacesInsteadOfTabs :: SourceViewClass sv => Attr sv Bool\nsourceViewInsertSpacesInsteadOfTabs = newAttrFromBoolProperty \"insert-spaces-instead-of-tabs\"\n\n-- | Position of the right margin.\n--\n-- Allowed values: [1,200]\n--\n-- Default value: 80\n--\nsourceViewRightMarginPosition :: SourceViewClass sv => Attr sv Int\nsourceViewRightMarginPosition = newAttrFromUIntProperty \"right-margin-position\"\n\n-- | Whether to display line numbers\n--\n-- Default value: 'False'\n--\nsourceViewShowLineNumbers :: SourceViewClass sv => Attr sv Bool\nsourceViewShowLineNumbers = newAttrFromBoolProperty \"show-line-numbers\"\n\n-- | Whether to display line mark pixbufs\n--\n-- Default value: 'False'\n--\nsourceViewShowRightMargin :: SourceViewClass sv => Attr sv Bool\nsourceViewShowRightMargin = newAttrFromBoolProperty \"show-right-margin\"\n\n-- | Set the behavior of the HOME and END keys.\n--\n-- Default value: 'SourceSmartHomeEndDisabled'\n--\n-- Since 2.0\n--\nsourceViewSmartHomeEnd :: SourceViewClass sv => Attr sv SourceSmartHomeEndType\nsourceViewSmartHomeEnd = newAttrFromEnumProperty \"smart-home-end\" {#call fun gtk_source_smart_home_end_type_get_type#}\n\n-- | Width of an tab character expressed in number of spaces.\n--\n-- Allowed values: [1,32]\n--\n-- Default value: 8\n--\nsourceViewTabWidth :: SourceViewClass sv => Attr sv Int\nsourceViewTabWidth = newAttrFromUIntProperty \"tab-width\"\n\n-- |\n--\nsourceViewUndo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewUndo = Signal $ connect_NONE__NONE \"undo\"\n\n-- |\n--\nsourceViewRedo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewRedo = Signal $ connect_NONE__NONE \"redo\"\n\n-- | The 'moveLines' signal is a keybinding which gets emitted when the user initiates moving a\n-- line. The default binding key is Alt+Up\/Down arrow. And moves the currently selected lines, or the\n-- current line by count. For the moment, only count of -1 or 1 is valid.\nsourceViewMoveLines :: SourceViewClass sv => Signal sv (Bool -> Int -> IO ())\nsourceViewMoveLines = Signal $ connect_BOOL_INT__NONE \"move-lines\"\n\n-- | The 'showCompletion' signal is a keybinding signal which gets emitted when the user initiates a\n-- completion in default mode.\n--\n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the default mode completion activation.\nsourceViewShowCompletion :: SourceViewClass sv => Signal sv (IO ())\nsourceViewShowCompletion = Signal $ connect_NONE__NONE \"show-completion\"\n\n-- | Emitted when a line mark has been activated (for instance when there was a button press in the line\n-- marks gutter). You can use iter to determine on which line the activation took place.\nsourceViewLineMarkActivated :: SourceViewClass sv => Signal sv (TextIter -> EventM EAny ())\nsourceViewLineMarkActivated =\n Signal (\\after obj fun ->\n connect_BOXED_PTR__NONE \"line-mark-activated\" mkTextIterCopy after obj\n (\\iter eventPtr -> runReaderT (fun iter) eventPtr)\n )\n\n#if GTK_MAJOR_VERSION < 3\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | 'sourceViewSetMarkCategoryPixbuf' is deprecated and should not be used in newly-written\n-- code. Use 'sourceViewSetMarkCategoryIconFromPixbuf' instead\n--\nsourceViewSetMarkCategoryPixbuf :: (SourceViewClass sv, GlibString string) => sv -> string -> Pixbuf -> IO ()\nsourceViewSetMarkCategoryPixbuf sv markerType marker = withUTFString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_pixbuf#} (toSourceView sv) strPtr marker\n\n-- | 'sourceViewGetMarkCategoryPixbuf' is deprecated and should not be used in newly-written code.\n--\nsourceViewGetMarkCategoryPixbuf :: (SourceViewClass sv, GlibString string) => sv -> string -> IO Pixbuf\nsourceViewGetMarkCategoryPixbuf sv markerType = withUTFString markerType $ \\strPtr ->\n wrapNewGObject mkPixbuf $\n {#call unsafe source_view_get_mark_category_pixbuf#} (toSourceView sv) strPtr\n#endif\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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-- 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.SourceView (\n-- * Description\n-- | 'SourceView' is the main object of the gtksourceview library. It provides a text view which syntax\n-- highlighting, undo\/redo and text marks. Use a 'SourceBuffer' to display text with a 'SourceView'.\n\n-- * Types\n SourceView,\n SourceViewClass,\n\n-- * Enums\n SourceSmartHomeEndType(..),\n SourceDrawSpacesFlags(..),\n SourceViewGutterPosition (..),\n\n-- * Methods\n castToSourceView,\n gTypeSourceView,\n toSourceView,\n sourceViewNew,\n sourceViewNewWithBuffer,\n sourceViewSetAutoIndent,\n sourceViewGetAutoIndent,\n sourceViewSetIndentOnTab,\n sourceViewGetIndentOnTab,\n sourceViewSetIndentWidth,\n sourceViewGetIndentWidth,\n sourceViewSetInsertSpacesInsteadOfTabs,\n sourceViewGetInsertSpacesInsteadOfTabs,\n sourceViewSetSmartHomeEnd,\n sourceViewGetSmartHomeEnd,\n#if GTK_MAJOR_VERSION < 3\n sourceViewSetMarkCategoryPriority,\n sourceViewGetMarkCategoryPriority,\n sourceViewSetMarkCategoryIconFromPixbuf,\n sourceViewSetMarkCategoryIconFromStock,\n sourceViewSetMarkCategoryIconFromIconName,\n sourceViewSetMarkCategoryBackground,\n sourceViewGetMarkCategoryBackground,\n#endif\n sourceViewSetHighlightCurrentLine,\n sourceViewGetHighlightCurrentLine,\n sourceViewSetShowLineMarks,\n sourceViewGetShowLineMarks,\n sourceViewSetShowLineNumbers,\n sourceViewGetShowLineNumbers,\n sourceViewSetShowRightMargin,\n sourceViewGetShowRightMargin,\n sourceViewSetRightMarginPosition,\n sourceViewGetRightMarginPosition,\n sourceViewSetTabWidth,\n sourceViewGetTabWidth,\n sourceViewSetDrawSpaces,\n sourceViewGetDrawSpaces,\n sourceViewGetGutter,\n\n#if GTK_MAJOR_VERSION >= 3\n#if MIN_VERSION_gtksourceview_3_0(3, 16, 0)\n sourceViewIndentLines,\n sourceViewUnindentLines,\n#endif\n sourceViewGetVisualColumn,\n sourceViewSetMarkAttributes,\n sourceViewGetMarkAttributes,\n#endif\n\n-- * Attributes\n sourceViewAutoIndent,\n sourceViewCompletion,\n sourceViewDrawSpaces,\n sourceViewHighlightCurrentLine,\n sourceViewIndentOnTab,\n sourceViewIndentWidth,\n sourceViewInsertSpacesInsteadOfTabs,\n sourceViewRightMarginPosition,\n sourceViewShowLineNumbers,\n sourceViewShowRightMargin,\n sourceViewSmartHomeEnd,\n sourceViewTabWidth,\n\n-- * Signals\n sourceViewUndo,\n sourceViewRedo,\n sourceViewMoveLines,\n sourceViewShowCompletion,\n sourceViewLineMarkActivated,\n\n-- * Deprecated\n#if GTK_MAJOR_VERSION < 3\n#ifndef DISABLE_DEPRECATED\n sourceViewSetMarkCategoryPixbuf,\n sourceViewGetMarkCategoryPixbuf,\n#endif\n#endif\n ) where\n\nimport Control.Applicative\nimport Prelude\nimport Control.Monad (liftM)\nimport Control.Monad.Reader ( runReaderT )\nimport Data.Maybe (fromMaybe)\n\nimport Graphics.UI.Gtk.Abstract.Object (makeNewObject)\nimport Graphics.UI.Gtk.Abstract.Widget (Color)\nimport Graphics.UI.Gtk.Gdk.EventM (EventM, EAny)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.SourceView.Enums\nimport Graphics.UI.GtkInternals ( TextIter, mkTextIterCopy )\nimport System.Glib.GObject (wrapNewGObject, makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags (toFlags, fromFlags)\n\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import System.Glib.Properties#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Create a new 'SourceView' widget with a default 'SourceBuffer'.\n--\nsourceViewNew :: IO SourceView\nsourceViewNew = makeNewObject mkSourceView $ liftM castPtr\n {#call unsafe source_view_new#}\n\n-- | Create a new 'SourceView'\n-- widget with the given 'SourceBuffer'.\n--\nsourceViewNewWithBuffer :: SourceBuffer -> IO SourceView\nsourceViewNewWithBuffer sb = makeNewObject mkSourceView $ liftM castPtr $\n {#call source_view_new_with_buffer#} sb\n\n-- | If 'True' auto indentation of text is enabled.\n--\nsourceViewSetAutoIndent :: SourceViewClass sv => sv\n -> Bool -- ^ @enable@ whether to enable auto indentation.\n -> IO ()\nsourceViewSetAutoIndent sv enable =\n {#call source_view_set_auto_indent#} (toSourceView sv) (fromBool enable)\n\n-- | Returns whether auto indentation of text is enabled.\n--\nsourceViewGetAutoIndent :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if auto indentation is enabled.\nsourceViewGetAutoIndent sv = liftM toBool $\n {#call unsafe source_view_get_auto_indent#} (toSourceView sv)\n\n-- | If 'True', when the tab key is pressed and there is a selection, the selected text is indented of one\n-- level instead of being replaced with the \\t characters. Shift+Tab unindents the selection.\n--\nsourceViewSetIndentOnTab :: SourceViewClass sv => sv\n -> Bool -- ^ @enable@ whether to indent a block when tab is pressed.\n -> IO ()\nsourceViewSetIndentOnTab sv enable =\n {#call source_view_set_indent_on_tab#} (toSourceView sv) (fromBool enable)\n\n-- | Returns whether when the tab key is pressed the current selection should get indented instead of\n-- replaced with the \\t character.\n--\nsourceViewGetIndentOnTab :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the selection is indented when tab is pressed.\nsourceViewGetIndentOnTab sv = liftM toBool $\n {#call unsafe source_view_get_indent_on_tab#} (toSourceView sv)\n\n-- | Sets the number of spaces to use for each step of indent. If width is -1, the value of the\n-- 'tabWidth' property will be used.\n--\nsourceViewSetIndentWidth :: SourceViewClass sv => sv\n -> Int -- ^ @width@ indent width in characters.\n -> IO ()\nsourceViewSetIndentWidth sv width =\n {#call source_view_set_indent_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the number of spaces to use for each step of indent. See 'sourceViewSetIndentWidth'\n-- for details.\n--\nsourceViewGetIndentWidth :: SourceViewClass sv => sv\n -> IO Int -- ^ returns indent width.\nsourceViewGetIndentWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_indent_width#} (toSourceView sv)\n\n-- | If 'True' any tabulator character inserted is replaced by a group of space characters.\n--\nsourceViewSetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv\n -> Bool -- ^ @enable@ whether to insert spaces instead of tabs.\n -> IO ()\nsourceViewSetInsertSpacesInsteadOfTabs sv enable =\n {#call source_view_set_insert_spaces_instead_of_tabs#} (toSourceView sv) (fromBool enable)\n\n-- | Returns whether when inserting a tabulator character it should be replaced by a group of space\n-- characters.\n--\nsourceViewGetInsertSpacesInsteadOfTabs :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if spaces are inserted instead of tabs.\nsourceViewGetInsertSpacesInsteadOfTabs sv = liftM toBool $\n {#call unsafe source_view_get_insert_spaces_instead_of_tabs#} (toSourceView sv)\n\n-- | Set the desired movement of the cursor when HOME and END keys are pressed.\n--\nsourceViewSetSmartHomeEnd :: SourceViewClass sv => sv\n -> SourceSmartHomeEndType -- ^ @smartHe@ the desired behavior among 'SourceSmartHomeEndType'.\n -> IO ()\nsourceViewSetSmartHomeEnd sv newVal =\n {#call source_view_set_smart_home_end#} (toSourceView sv) (fromIntegral $ fromEnum newVal)\n\n-- | Returns a 'SourceSmartHomeEndType' end value specifying how the cursor will move when HOME and END\n-- keys are pressed.\n--\nsourceViewGetSmartHomeEnd :: SourceViewClass sv => sv\n -> IO SourceSmartHomeEndType -- ^ returns a 'SourceSmartHomeEndTypeend' value.\nsourceViewGetSmartHomeEnd sv = liftM (toEnum . fromIntegral) $\n {#call unsafe source_view_get_smart_home_end#} (toSourceView sv)\n\n-- | If show is 'True' the current line is highlighted.\n--\nsourceViewSetHighlightCurrentLine :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether to highlight the current line\n -> IO ()\nsourceViewSetHighlightCurrentLine sv newVal =\n {#call source_view_set_highlight_current_line#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether the current line is highlighted\n--\nsourceViewGetHighlightCurrentLine :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the current line is highlighted.\nsourceViewGetHighlightCurrentLine sv = liftM toBool $\n {#call unsafe source_view_get_highlight_current_line#} (toSourceView sv)\n\n-- | If 'True' line marks will be displayed beside the text.\n--\nsourceViewSetShowLineMarks :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether line marks should be displayed.\n -> IO ()\nsourceViewSetShowLineMarks sv newVal =\n {#call source_view_set_show_line_marks#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether line marks are displayed beside the text.\n--\nsourceViewGetShowLineMarks :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the line marks are displayed.\nsourceViewGetShowLineMarks sv = liftM toBool $\n {#call unsafe source_view_get_show_line_marks#} (toSourceView sv)\n\n-- | If 'True' line numbers will be displayed beside the text.\n--\nsourceViewSetShowLineNumbers :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether line numbers should be displayed.\n -> IO ()\nsourceViewSetShowLineNumbers sv newVal =\n {#call source_view_set_show_line_numbers#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether line numbers are displayed beside the text.\n--\nsourceViewGetShowLineNumbers :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the line numbers are displayed.\nsourceViewGetShowLineNumbers sv = liftM toBool $\n {#call unsafe source_view_get_show_line_numbers#} (toSourceView sv)\n\n-- | If 'True' a right margin is displayed\n--\nsourceViewSetShowRightMargin :: SourceViewClass sv => sv\n -> Bool -- ^ @show@ whether to show a right margin.\n -> IO ()\nsourceViewSetShowRightMargin sv newVal =\n {#call source_view_set_show_right_margin#} (toSourceView sv) (fromBool newVal)\n\n-- | Returns whether a right margin is displayed.\n--\nsourceViewGetShowRightMargin :: SourceViewClass sv => sv\n -> IO Bool -- ^ returns 'True' if the right margin is shown.\nsourceViewGetShowRightMargin sv = liftM toBool $\n {#call source_view_get_show_right_margin#} (toSourceView sv)\n\n-- | Sets the position of the right margin in the given view.\n--\nsourceViewSetRightMarginPosition :: SourceViewClass sv => sv\n -> Word -- ^ @pos@ the width in characters where to position the right margin.\n -> IO ()\nsourceViewSetRightMarginPosition sv margin =\n {#call source_view_set_right_margin_position#} (toSourceView sv) (fromIntegral margin)\n\n-- | Gets the position of the right margin in the given view.\n--\nsourceViewGetRightMarginPosition :: SourceViewClass sv => sv\n -> IO Int -- ^ returns the position of the right margin.\nsourceViewGetRightMarginPosition sv = liftM fromIntegral $\n {#call unsafe source_view_get_right_margin_position#} (toSourceView sv)\n\n-- | Sets the width of tabulation in characters.\n--\nsourceViewSetTabWidth :: SourceViewClass sv => sv\n -> Int -- ^ @width@ width of tab in characters.\n -> IO ()\nsourceViewSetTabWidth sv width =\n {#call source_view_set_tab_width#} (toSourceView sv) (fromIntegral width)\n\n-- | Returns the width of tabulation in characters.\n--\nsourceViewGetTabWidth :: SourceViewClass sv => sv\n -> IO Int -- ^ returns width of tab.\nsourceViewGetTabWidth sv = liftM fromIntegral $\n {#call unsafe source_view_get_tab_width#} (toSourceView sv)\n\n-- | Set if and how the spaces should be visualized. Specifying flags as [] will disable display of\n-- spaces.\nsourceViewSetDrawSpaces :: SourceViewClass sv => sv\n -> [SourceDrawSpacesFlags] -- ^ @flags@ 'SourceDrawSpacesFlags' specifing how white spaces should be displayed\n -> IO ()\nsourceViewSetDrawSpaces view flags =\n {#call gtk_source_view_set_draw_spaces #}\n (toSourceView view)\n (fromIntegral $ fromFlags flags)\n\n-- | Returns the 'SourceDrawSpacesFlags' specifying if and how spaces should be displayed for this view.\nsourceViewGetDrawSpaces :: SourceViewClass sv => sv\n -> IO [SourceDrawSpacesFlags] -- ^ returns the 'SourceDrawSpacesFlags', [] if no spaces should be drawn.\nsourceViewGetDrawSpaces view =\n liftM (toFlags . fromIntegral) $\n {#call gtk_source_view_get_draw_spaces #}\n (toSourceView view)\n\n-- | Returns the 'SourceGutter' object associated with @windowType@ for view. Only 'TextWindowLeft'\n-- and 'TextWindowRight' are supported, respectively corresponding to the left and right\n-- gutter. The line numbers and mark category icons are rendered in the gutter corresponding to\n-- 'TextWindowLeft'.\nsourceViewGetGutter :: SourceViewClass sv => sv\n -> TextWindowType -- ^ @windowType@ the gutter window type\n -> IO SourceGutter\nsourceViewGetGutter sv windowType =\n makeNewGObject mkSourceGutter $\n {#call gtk_source_view_get_gutter #}\n (toSourceView sv)\n (fromIntegral $ fromEnum windowType)\n\n#if GTK_MAJOR_VERSION < 3\n-- | Set the priority for the given mark category. When there are multiple marks on the same line, marks\n-- of categories with higher priorities will be drawn on top.\n--\nsourceViewSetMarkCategoryPriority :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Int -- ^ @priority@ the priority for the category\n -> IO ()\nsourceViewSetMarkCategoryPriority sv markerType priority = withUTFString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_priority#} (toSourceView sv) strPtr (fromIntegral priority)\n\n-- | Gets the priority which is associated with the given category.\n--\nsourceViewGetMarkCategoryPriority :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> IO Int -- ^ returns the priority or if category exists but no priority was set, it defaults to 0.\nsourceViewGetMarkCategoryPriority sv markerType = withUTFString markerType $ \\strPtr ->\n liftM fromIntegral $\n {#call unsafe source_view_get_mark_category_priority#} (toSourceView sv) strPtr\n\n-- | Sets the icon to be used for category to pixbuf. If pixbuf is 'Nothing', the icon is unset.\nsourceViewSetMarkCategoryIconFromPixbuf :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe Pixbuf -- ^ @pixbuf@ a 'Pixbuf' or 'Nothing'.\n -> IO ()\nsourceViewSetMarkCategoryIconFromPixbuf sv category pixbuf =\n withUTFString category $ \\categoryPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_pixbuf #}\n (toSourceView sv)\n categoryPtr\n (fromMaybe (Pixbuf nullForeignPtr) pixbuf)\n\n-- | Sets the icon to be used for category to the stock item @stockId@. If @stockId@ is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromStock :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe string -- ^ @stockId@ the stock id or 'Nothing'.\n -> IO ()\nsourceViewSetMarkCategoryIconFromStock sv category stockId =\n withUTFString category $ \\categoryPtr ->\n maybeWith withUTFString stockId $ \\stockIdPtr ->\n {#call gtk_source_view_set_mark_category_icon_from_stock #}\n (toSourceView sv)\n categoryPtr\n stockIdPtr\n\n-- | Sets the icon to be used for category to the named theme item name. If name is 'Nothing', the icon is\n-- unset.\nsourceViewSetMarkCategoryIconFromIconName :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe string -- ^ @name@ the themed icon name or 'Nothing'.\n -> IO ()\nsourceViewSetMarkCategoryIconFromIconName sv category name =\n withUTFString category $ \\categoryPtr ->\n maybeWith withUTFString name $ \\namePtr ->\n {#call gtk_source_view_set_mark_category_icon_from_icon_name #}\n (toSourceView sv)\n categoryPtr\n namePtr\n\n-- | Sets given background color for mark category. If color is 'Nothing', the background color is unset.\nsourceViewSetMarkCategoryBackground :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Maybe Color -- ^ @color@ background color or 'Nothing' to unset it.\n -> IO ()\nsourceViewSetMarkCategoryBackground sv category color =\n let withMB :: Storable a => Maybe a -> (Ptr a -> IO b) -> IO b\n withMB Nothing f = f nullPtr\n withMB (Just x) f = with x f\n in withUTFString category $ \\categoryPtr ->\n withMB color $ \\colorPtr ->\n {#call gtk_source_view_set_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n\n-- | Gets the background color associated with given category.\nsourceViewGetMarkCategoryBackground :: (SourceViewClass sv, GlibString string) => sv\n -> string -- ^ @category@ a mark category.\n -> Color -- ^ @dest@ destination 'Color' structure to fill in.\n -> IO Bool -- ^ returns 'True' if background color for category was set and dest is set to a valid color, or 'False' otherwise.\nsourceViewGetMarkCategoryBackground sv category color =\n liftM toBool $\n withUTFString category $ \\ categoryPtr ->\n with color $ \\ colorPtr ->\n {#call gtk_source_view_get_mark_category_background #}\n (toSourceView sv)\n categoryPtr\n (castPtr colorPtr)\n#endif\n\n#if MIN_VERSION_gtksourceview_3_0(3, 16, 0)\n-- | Insert one indentation level at the beginning of the specified lines.\n--\nsourceViewIndentLines :: SourceViewClass sv\n => sv\n -> TextIter -- ^ @start@ the first line to indent.\n -> TextIter -- ^ @end@ the last line to indent.\n -> IO ()\nsourceViewIndentLines sv start end =\n {# call gtk_source_view_indent_lines #}\n (toSourceView sv)\n start\n end\n\n-- | Removes one indentation level at the beginning of the specified lines.\n--\nsourceViewUnindentLines :: SourceViewClass sv\n => sv\n -> TextIter -- ^ @start@ the first line to indent.\n -> TextIter -- ^ @end@ the last line to indent.\n -> IO ()\nsourceViewUnindentLines sv start end =\n {# call gtk_source_view_unindent_lines #}\n (toSourceView sv)\n start\n end\n#endif\n\n-- | Determines the visual column at iter taking into consideration the `tabWidth` of the view.\n--\nsourceViewGetVisualColumn :: SourceViewClass sv\n => sv\n -> TextIter -- ^ @iter@ a position in view.\n -> IO Word\nsourceViewGetVisualColumn sv iter = fromIntegral <$>\n {# call gtk_source_view_get_visual_column #}\n (toSourceView sv)\n iter\n\n-- | Sets attributes and priority for the category.\n--\nsourceViewSetMarkAttributes :: (SourceViewClass sv, GlibString category, SourceMarkAttributesClass attributes)\n => sv\n -> category\n -> Maybe attributes\n -> Int\n -> IO ()\nsourceViewSetMarkAttributes sv category attributes priority =\n withUTFString category $ \\categoryPtr ->\n {# call gtk_source_view_set_mark_attributes #}\n (toSourceView sv)\n categoryPtr\n (maybe (SourceMarkAttributes nullForeignPtr) toSourceMarkAttributes attributes)\n (fromIntegral priority)\n\n-- | Gets attributes and priority for the category\n--\nsourceViewGetMarkAttributes :: (SourceViewClass sv, GlibString category)\n => sv\n -> category\n -> IO (Maybe (SourceMarkAttributes, Int))\nsourceViewGetMarkAttributes sv category =\n withUTFString category $ \\categoryPtr ->\n alloca $ \\ priority -> do\n attributes <- maybeNull (makeNewObject mkSourceMarkAttributes) $\n {# call gtk_source_view_get_mark_attributes #}\n (toSourceView sv)\n categoryPtr\n priority\n case attributes of\n Just a -> do\n p <- peek priority\n return $ Just (a, fromIntegral p)\n Nothing -> return Nothing\n\n-- | Whether to enable auto indentation.\n--\n-- Default value: 'False'\n--\nsourceViewAutoIndent :: SourceViewClass sv => Attr sv Bool\nsourceViewAutoIndent = newAttrFromBoolProperty \"auto-indent\"\n\n-- | The completion object associated with the view.\n--\nsourceViewCompletion :: SourceViewClass sv => ReadAttr sv SourceCompletion\nsourceViewCompletion = readAttrFromObjectProperty \"completion\"\n {#call pure unsafe gtk_source_completion_get_type #}\n\n-- | Set if and how the spaces should be visualized.\n--\nsourceViewDrawSpaces :: SourceViewClass sv => Attr sv [SourceDrawSpacesFlags]\nsourceViewDrawSpaces = newAttrFromFlagsProperty \"draw-spaces\" {#call fun gtk_source_draw_spaces_flags_get_type#}\n\n-- | Whether to highlight the current line.\n--\n-- Default value: 'False'\n--\nsourceViewHighlightCurrentLine :: SourceViewClass sv => Attr sv Bool\nsourceViewHighlightCurrentLine = newAttrFromBoolProperty \"highlight-current-line\"\n\n-- | Whether to indent the selected text when the tab key is pressed.\n--\n-- Default value: 'True'\n--\nsourceViewIndentOnTab :: SourceViewClass sv => Attr sv Bool\nsourceViewIndentOnTab = newAttrFromBoolProperty \"indent-on-tab\"\n\n-- | Width of an indentation step expressed in number of spaces.\n--\n-- Allowed values: [GMaxulong,32]\n--\n-- Default value: -1\n--\nsourceViewIndentWidth :: SourceViewClass sv => Attr sv Int\nsourceViewIndentWidth = newAttrFromIntProperty \"indent-width\"\n\n-- | Whether to insert spaces instead of tabs.\n--\n-- Default value: 'False'\n--\nsourceViewInsertSpacesInsteadOfTabs :: SourceViewClass sv => Attr sv Bool\nsourceViewInsertSpacesInsteadOfTabs = newAttrFromBoolProperty \"insert-spaces-instead-of-tabs\"\n\n-- | Position of the right margin.\n--\n-- Allowed values: [1,200]\n--\n-- Default value: 80\n--\nsourceViewRightMarginPosition :: SourceViewClass sv => Attr sv Int\nsourceViewRightMarginPosition = newAttrFromUIntProperty \"right-margin-position\"\n\n-- | Whether to display line numbers\n--\n-- Default value: 'False'\n--\nsourceViewShowLineNumbers :: SourceViewClass sv => Attr sv Bool\nsourceViewShowLineNumbers = newAttrFromBoolProperty \"show-line-numbers\"\n\n-- | Whether to display line mark pixbufs\n--\n-- Default value: 'False'\n--\nsourceViewShowRightMargin :: SourceViewClass sv => Attr sv Bool\nsourceViewShowRightMargin = newAttrFromBoolProperty \"show-right-margin\"\n\n-- | Set the behavior of the HOME and END keys.\n--\n-- Default value: 'SourceSmartHomeEndDisabled'\n--\n-- Since 2.0\n--\nsourceViewSmartHomeEnd :: SourceViewClass sv => Attr sv SourceSmartHomeEndType\nsourceViewSmartHomeEnd = newAttrFromEnumProperty \"smart-home-end\" {#call fun gtk_source_smart_home_end_type_get_type#}\n\n-- | Width of an tab character expressed in number of spaces.\n--\n-- Allowed values: [1,32]\n--\n-- Default value: 8\n--\nsourceViewTabWidth :: SourceViewClass sv => Attr sv Int\nsourceViewTabWidth = newAttrFromUIntProperty \"tab-width\"\n\n-- |\n--\nsourceViewUndo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewUndo = Signal $ connect_NONE__NONE \"undo\"\n\n-- |\n--\nsourceViewRedo :: SourceViewClass sv => Signal sv (IO ())\nsourceViewRedo = Signal $ connect_NONE__NONE \"redo\"\n\n-- | The 'moveLines' signal is a keybinding which gets emitted when the user initiates moving a\n-- line. The default binding key is Alt+Up\/Down arrow. And moves the currently selected lines, or the\n-- current line by count. For the moment, only count of -1 or 1 is valid.\nsourceViewMoveLines :: SourceViewClass sv => Signal sv (Bool -> Int -> IO ())\nsourceViewMoveLines = Signal $ connect_BOOL_INT__NONE \"move-lines\"\n\n-- | The 'showCompletion' signal is a keybinding signal which gets emitted when the user initiates a\n-- completion in default mode.\n--\n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the default mode completion activation.\nsourceViewShowCompletion :: SourceViewClass sv => Signal sv (IO ())\nsourceViewShowCompletion = Signal $ connect_NONE__NONE \"show-completion\"\n\n-- | Emitted when a line mark has been activated (for instance when there was a button press in the line\n-- marks gutter). You can use iter to determine on which line the activation took place.\nsourceViewLineMarkActivated :: SourceViewClass sv => Signal sv (TextIter -> EventM EAny ())\nsourceViewLineMarkActivated =\n Signal (\\after obj fun ->\n connect_BOXED_PTR__NONE \"line-mark-activated\" mkTextIterCopy after obj\n (\\iter eventPtr -> runReaderT (fun iter) eventPtr)\n )\n\n#if GTK_MAJOR_VERSION < 3\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | 'sourceViewSetMarkCategoryPixbuf' is deprecated and should not be used in newly-written\n-- code. Use 'sourceViewSetMarkCategoryIconFromPixbuf' instead\n--\nsourceViewSetMarkCategoryPixbuf :: (SourceViewClass sv, GlibString string) => sv -> string -> Pixbuf -> IO ()\nsourceViewSetMarkCategoryPixbuf sv markerType marker = withUTFString markerType $ \\strPtr ->\n {#call source_view_set_mark_category_pixbuf#} (toSourceView sv) strPtr marker\n\n-- | 'sourceViewGetMarkCategoryPixbuf' is deprecated and should not be used in newly-written code.\n--\nsourceViewGetMarkCategoryPixbuf :: (SourceViewClass sv, GlibString string) => sv -> string -> IO Pixbuf\nsourceViewGetMarkCategoryPixbuf sv markerType = withUTFString markerType $ \\strPtr ->\n wrapNewGObject mkPixbuf $\n {#call unsafe source_view_get_mark_category_pixbuf#} (toSourceView sv) strPtr\n#endif\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"3810b73aee1bebfcef4e38a108782940d697187b","subject":"storable instance for the state","message":"storable instance for the state\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface,\n EmptyDataDecls\n #-}\nmodule Network.LibRSync.Internal where\n\nimport Control.Applicative((<$>),(<*>))\nimport Control.Monad\n\nimport Data.ByteString\nimport Data.Conduit\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\nimport Foreign.Marshal.Alloc\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \"internal.h\"\n\n-- #include \"..\/..\/..\/c_src\/internal.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ndata CInMemoryBuffer = CInMemoryBuffer (Ptr CChar) CSize CSize\n\n{#pointer *inMemoryBuffer_t as CInMemoryBufferPtr -> CInMemoryBuffer #}\n\ninstance Storable CInMemoryBuffer where\n sizeOf = const {#sizeof inMemoryBuffer_t #}\n alignment = const 4\n peek p = CInMemoryBuffer\n <$> {#get inMemoryBuffer_t->buffer #} p\n <*> liftM fromIntegral ({#get inMemoryBuffer_t->size #} p)\n <*> liftM fromIntegral ({#get inMemoryBuffer_t->inUse #} p)\n poke = undefined\n\ngetData :: CInMemoryBuffer -> IO ByteString\ngetData (CInMemoryBuffer xs _ s) = packCStringLen (xs,fromIntegral s)\n\n\n\n\n\n\n-- data CRSFileBuf = CRSFileBuf (Ptr CFile) CSize\n\n-- {#pointer *rs_filebuf_t as CRSFileBufPtr -> CRSFileBuf #}\n\ndata CJob\ndata CBuffers\ndata CRSFileBuf\n\ndata CRSyncSourceState = CRSyncSourceState { f :: Ptr CFile\n , job :: Ptr CJob\n , buf :: Ptr CBuffers\n , inBuf :: Ptr CRSFileBuf\n , outputBuf' :: CInMemoryBufferPtr\n }\n\n{#pointer *rsyncSourceState_t as CRSyncSourceStatePtr -> CRSyncSourceState #}\n\ninstance Storable CRSyncSourceState where\n sizeOf = const {#sizeof rsyncSourceState_t #}\n alignment = const 4\n -- We can only access the output buffer and the return state\n peek p = CRSyncSourceState undefined undefined undefined undefined\n <$> {#get rsyncSourceState_t->outputBuf #} p\n poke = undefined\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype RSyncSourceState = CRSyncSourceStatePtr\n\noutputBuf :: RSyncSourceState -> IO CInMemoryBuffer\noutputBuf p = (outputBuf' <$> peek p) >>= peek\n\ntype Signature = ByteString\n\n\nstartSignature :: FilePath -> IO RSyncSourceState\nstartSignature path = do\n state <- malloc :: IO (Ptr CRSyncSourceState)\n rsres <- cStartSignature path state\n return state\n -- TODO: check what to do with rsres\n -- case rsres of\n -- RsDone ->\n\nendSignature :: RSyncSourceState -> IO ()\nendSignature state = cEndSignature state >> free state\n\nsignatureSource :: MonadResource m => RSyncSourceState -> Source m Signature\nsignatureSource state = undefined -- do\n -- (CInMemoryBuffer xs size inUse) <- {#get inMemorybuffer->outputBuf-> state\n\n\n\n\n\n\n\n{#fun unsafe startSignature as cStartSignature\n { `String' -- FilePath\n , id `CRSyncSourceStatePtr'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe signatureChunk as cSignatureChunk\n { id `CRSyncSourceStatePtr'\n , `Bool'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe endSignature as cEndSignature\n { id `CRSyncSourceStatePtr'\n } -> `()'\n #}\n\n\n-- type Signature = ByteString\n\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface,\n EmptyDataDecls\n #-}\nmodule Network.LibRSync.Internal where\n\nimport Control.Applicative((<$>),(<*>))\nimport Control.Monad\n\nimport Data.ByteString\nimport Data.Conduit\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\nimport Foreign.Marshal.Alloc\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \"internal.h\"\n\n-- #include \"..\/..\/..\/c_src\/internal.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ndata CInMemoryBuffer = CInMemoryBuffer (Ptr CChar) CSize CSize\n\n{#pointer *inMemoryBuffer_t as CInMemoryBufferPtr -> CInMemoryBuffer #}\n\ninstance Storable CInMemoryBuffer where\n sizeOf = const {#sizeof inMemoryBuffer_t #}\n alignment = const 4\n peek p = CInMemoryBuffer\n <$> {#get inMemoryBuffer_t->buffer #} p\n <*> liftM fromIntegral ({#get inMemoryBuffer_t->size #} p)\n <*> liftM fromIntegral ({#get inMemoryBuffer_t->inUse #} p)\n poke = undefined\n\n\n\ngetData :: CInMemoryBuffer -> IO ByteString\ngetData (CInMemoryBuffer xs _ s) = packCStringLen (xs,fromIntegral s)\n\n\n\n\n\n\n-- data CRSFileBuf = CRSFileBuf (Ptr CFile) CSize\n\n-- {#pointer *rs_filebuf_t as CRSFileBufPtr -> CRSFileBuf #}\n\ndata CJob\ndata CBuffers\ndata CRSFileBuf\n\ndata CRSyncSourceState = CRSyncSourceState { f :: Ptr CFile\n , job :: Ptr CJob\n , buf :: Ptr CBuffers\n , inBuf :: Ptr CRSFileBuf\n , outputBuf :: CInMemoryBufferPtr\n }\n\ninstance Storable CRSyncSourceState where\n sizeOf = const {#sizeof rsyncSourceState_t #}\n alignment = const 4\n peek = undefined\n poke = undefined\n\n\n{#pointer *rsyncSourceState_t as CRSyncSourceStatePtr -> CRSyncSourceState #}\n\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype RSyncSourceState = CRSyncSourceStatePtr\n\ntype Signature = ByteString\n\n\nstartSignature :: FilePath -> IO RSyncSourceState\nstartSignature path = do\n state <- malloc :: IO (Ptr CRSyncSourceState)\n rsres <- cStartSignature path state\n return state\n -- TODO: check what to do with rsres\n -- case rsres of\n -- RsDone ->\n\nendSignature :: RSyncSourceState -> IO ()\nendSignature state = cEndSignature state >> free state\n\nsignatureSource :: MonadResource m => RSyncSourceState -> Source m Signature\nsignatureSource state = undefined -- do\n -- (CInMemoryBuffer xs size inUse) <- {#get inMemorybuffer->outputBuf-> state\n\n\n\n\n\n\n\n{#fun unsafe startSignature as cStartSignature\n { `String' -- FilePath\n , id `CRSyncSourceStatePtr'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe signatureChunk as cSignatureChunk\n { id `CRSyncSourceStatePtr'\n , `Bool'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe endSignature as cEndSignature\n { id `CRSyncSourceStatePtr'\n } -> `()'\n #}\n\n\n-- type Signature = ByteString\n\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7e051a5ddf757415ae81d06fd0a98d8518349921","subject":"doc comment","message":"doc comment\n\nSigned-off-by: Ricky Elrod <3de8762d49a778edd8b1aa9f381ea5a9ccb62944@elrod.me>\n","repos":"relrod\/bindings-hamlib,relrod\/bindings-hamlib","old_file":"src\/Communication\/Hamlib\/Rig.chs","new_file":"src\/Communication\/Hamlib\/Rig.chs","new_contents":"{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\n--------------------------------------------------------------------------------\n-- |\n-- Copyright : (c) 2014 Ricky Elrod\n-- License : BSD2\n--\n-- Maintainer : Ricky Elrod \n-- Stability : experimental\n--\n-- Provides a Haskell interface to hamlib's @rig.h@.\n--------------------------------------------------------------------------------\n\nmodule Communication.Hamlib.Rig where\n\nimport Control.Lens hiding (Setting)\nimport Foreign.Ptr\nimport Foreign.C.Types\n\n#include \n\n-- Macro-defined constants\n{#enum define Consts {\n RIGNAMSIZ as RigNameSize\n , FILPATHLEN as FilePathLength\n , FRQRANGESIZ as FrequencyRangeSize\n , MAXCHANDESC as MaxChannelDescription\n , TSLSTSIZ as TuningStepListSize\n , FLTLSTSIZ as FilterListSize\n , MAXDBLSTSIZ as MaxDBListSize\n , CHANLSTSIZ as ChannelListSize\n , MAX_CAL_LENGTH as MaxClibrationPlots\n } deriving (Eq, Ord, Show)#}\n\n{#enum rig_errcode_e as RigError {underscoreToCase}#}\n{#enum rig_debug_level_e as RigDebugLevel {underscoreToCase}#}\n{#enum rig_level_e as RigLevel {underscoreToCase}#}\n{#enum rig_port_e as RigPort {underscoreToCase}#}\n{#enum serial_parity_e as SerialParity {underscoreToCase}#}\n{#enum serial_handshake_e as SerialHandshake {underscoreToCase}#}\n{#enum serial_control_state_e as SerialControlState {underscoreToCase}#}\n{#enum rmode_t as Rmode {underscoreToCase}#}\n{#enum split_t as Split {underscoreToCase}#}\n{#enum rptr_shift_t as RptrShift {underscoreToCase}#}\n{#enum rig_type_t as RigType {underscoreToCase}#}\n{#enum rig_status_e as RigStatus {underscoreToCase}#}\n{#enum dcd_e as Dcd {underscoreToCase}#}\n{#enum dcd_type_t as DcdType {underscoreToCase}#}\n{#enum ptt_t as Ptt {underscoreToCase}#}\n{#enum powerstat_t as Powerstat {underscoreToCase}#}\n{#enum reset_t as Reset {underscoreToCase}#}\n{#enum vfo_op_t as VfoOp {underscoreToCase}#}\n{#enum scan_t as Scan {underscoreToCase}#}\n{#enum rig_conf_e as RigConf {underscoreToCase}#}\n{#enum ann_t as Announce {underscoreToCase}#}\n{#enum agc_level_e as AgcLevel {underscoreToCase}#}\n{#enum meter_level_e as MeterLevel {underscoreToCase}#}\n{#enum rig_parm_e as RigParm {underscoreToCase}#}\n{#enum rig_func_e as RigFunc {underscoreToCase}#}\n{#enum chan_type_t as ChanType {underscoreToCase}#}\n\ndata Value = I Int | F Float | S String | Cs String\n\ntype Vfo = Int\ntype Freq = Double\ntype ShortFreq = Integer\ntype Pbwidth = ShortFreq\ntype Setting = Integer\ntype Tone = Int\ntype Ant = Int\ntype Token = Integer\n\ndata Channel =\n Channel {\n channelNum :: Int\n , bankNum :: Int\n , channelVfo :: Vfo\n , channelAnt :: Int\n , freq :: Freq\n , mode :: Rmode\n , channelWidth :: Pbwidth\n , txFreq :: Freq\n , txMode :: Rmode\n , txWidth :: Pbwidth\n , split :: Split\n , txVfo :: Vfo\n , rptrShift :: RptrShift\n , rptrOffs :: ShortFreq\n , tuningStep :: ShortFreq\n , rit :: ShortFreq\n , xit :: ShortFreq\n , funcs :: Setting\n , levels :: [Value]\n , ctcssTone :: Tone\n , ctcssSql :: Tone\n , dcsCode :: Tone\n , dcsSql :: Tone\n , scanGroup :: Int\n , flags :: Int\n , channelDesc :: String\n }\n\n{#pointer *channel as ChannelPtr -> Channel #}\n\n--------------------------------------------------------------------------------\n\ndata FreqRangeList =\n FreqRangeList {\n _freqrangeStart :: Freq\n , _freqrangeEnd :: Freq\n , _freqrangeFreqRangemodes :: Rmode\n , _freqrangeLowPower :: Int\n , _freqrangeHighPower :: Int\n , _freqrangeVfo :: Vfo\n , _freqrangeAnt :: Ant\n }\n\n{#pointer *freq_range_list as FreqRangeListPtr -> FreqRangeList #}\n\nmakeFields ''FreqRangeList\n\n--------------------------------------------------------------------------------\n\ndata TuningStepList =\n TuningStepList {\n _tuningstepModes :: Rmode\n , _tuningstepTs :: ShortFreq\n }\n\n{#pointer *tuning_step_list as TuningStepListPtr -> TuningStepList #}\n\nmakeFields ''TuningStepList\n\n--------------------------------------------------------------------------------\n\ndata FilterList =\n FilterList {\n _filterModes :: Rmode\n , _filterWidth :: Pbwidth\n }\n\n{#pointer *filter_list as FilterListPtr -> FilterList #}\n\nmakeFields ''FilterList\n\n--------------------------------------------------------------------------------\n\ndata ExtList =\n ExtList {\n _extToken :: Token\n , _extVal :: Value\n }\n\n{#pointer *ext_list as ExtListPtr -> ExtList #}\n\nmakeFields ''ExtList\n","old_contents":"{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n\nmodule Communication.Hamlib.Rig where\n\nimport Control.Lens hiding (Setting)\nimport Foreign.Ptr\nimport Foreign.C.Types\n\n#include \n\n-- Macro-defined constants\n{#enum define Consts {\n RIGNAMSIZ as RigNameSize\n , FILPATHLEN as FilePathLength\n , FRQRANGESIZ as FrequencyRangeSize\n , MAXCHANDESC as MaxChannelDescription\n , TSLSTSIZ as TuningStepListSize\n , FLTLSTSIZ as FilterListSize\n , MAXDBLSTSIZ as MaxDBListSize\n , CHANLSTSIZ as ChannelListSize\n , MAX_CAL_LENGTH as MaxClibrationPlots\n } deriving (Eq, Ord, Show)#}\n\n{#enum rig_errcode_e as RigError {underscoreToCase}#}\n{#enum rig_debug_level_e as RigDebugLevel {underscoreToCase}#}\n{#enum rig_level_e as RigLevel {underscoreToCase}#}\n{#enum rig_port_e as RigPort {underscoreToCase}#}\n{#enum serial_parity_e as SerialParity {underscoreToCase}#}\n{#enum serial_handshake_e as SerialHandshake {underscoreToCase}#}\n{#enum serial_control_state_e as SerialControlState {underscoreToCase}#}\n{#enum rmode_t as Rmode {underscoreToCase}#}\n{#enum split_t as Split {underscoreToCase}#}\n{#enum rptr_shift_t as RptrShift {underscoreToCase}#}\n{#enum rig_type_t as RigType {underscoreToCase}#}\n{#enum rig_status_e as RigStatus {underscoreToCase}#}\n{#enum dcd_e as Dcd {underscoreToCase}#}\n{#enum dcd_type_t as DcdType {underscoreToCase}#}\n{#enum ptt_t as Ptt {underscoreToCase}#}\n{#enum powerstat_t as Powerstat {underscoreToCase}#}\n{#enum reset_t as Reset {underscoreToCase}#}\n{#enum vfo_op_t as VfoOp {underscoreToCase}#}\n{#enum scan_t as Scan {underscoreToCase}#}\n{#enum rig_conf_e as RigConf {underscoreToCase}#}\n{#enum ann_t as Announce {underscoreToCase}#}\n{#enum agc_level_e as AgcLevel {underscoreToCase}#}\n{#enum meter_level_e as MeterLevel {underscoreToCase}#}\n{#enum rig_parm_e as RigParm {underscoreToCase}#}\n{#enum rig_func_e as RigFunc {underscoreToCase}#}\n{#enum chan_type_t as ChanType {underscoreToCase}#}\n\ndata Value = I Int | F Float | S String | Cs String\n\ntype Vfo = Int\ntype Freq = Double\ntype ShortFreq = Integer\ntype Pbwidth = ShortFreq\ntype Setting = Integer\ntype Tone = Int\ntype Ant = Int\ntype Token = Integer\n\ndata Channel =\n Channel {\n channelNum :: Int\n , bankNum :: Int\n , channelVfo :: Vfo\n , channelAnt :: Int\n , freq :: Freq\n , mode :: Rmode\n , channelWidth :: Pbwidth\n , txFreq :: Freq\n , txMode :: Rmode\n , txWidth :: Pbwidth\n , split :: Split\n , txVfo :: Vfo\n , rptrShift :: RptrShift\n , rptrOffs :: ShortFreq\n , tuningStep :: ShortFreq\n , rit :: ShortFreq\n , xit :: ShortFreq\n , funcs :: Setting\n , levels :: [Value]\n , ctcssTone :: Tone\n , ctcssSql :: Tone\n , dcsCode :: Tone\n , dcsSql :: Tone\n , scanGroup :: Int\n , flags :: Int\n , channelDesc :: String\n }\n\n{#pointer *channel as ChannelPtr -> Channel #}\n\n--------------------------------------------------------------------------------\n\ndata FreqRangeList =\n FreqRangeList {\n _freqrangeStart :: Freq\n , _freqrangeEnd :: Freq\n , _freqrangeFreqRangemodes :: Rmode\n , _freqrangeLowPower :: Int\n , _freqrangeHighPower :: Int\n , _freqrangeVfo :: Vfo\n , _freqrangeAnt :: Ant\n }\n\n{#pointer *freq_range_list as FreqRangeListPtr -> FreqRangeList #}\n\nmakeFields ''FreqRangeList\n\n--------------------------------------------------------------------------------\n\ndata TuningStepList =\n TuningStepList {\n _tuningstepModes :: Rmode\n , _tuningstepTs :: ShortFreq\n }\n\n{#pointer *tuning_step_list as TuningStepListPtr -> TuningStepList #}\n\nmakeFields ''TuningStepList\n\n--------------------------------------------------------------------------------\n\ndata FilterList =\n FilterList {\n _filterModes :: Rmode\n , _filterWidth :: Pbwidth\n }\n\n{#pointer *filter_list as FilterListPtr -> FilterList #}\n\nmakeFields ''FilterList\n\n--------------------------------------------------------------------------------\n\ndata ExtList =\n ExtList {\n _extToken :: Token\n , _extVal :: Value\n }\n\n{#pointer *ext_list as ExtListPtr -> ExtList #}\n\nmakeFields ''ExtList\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"61a2b0ca2617845a666e0cf017787906a35e19e0","subject":"Added NFData instances for ErrorType and ErrorNum","message":"Added NFData instances for ErrorType and ErrorNum\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/CPLError.chs","new_file":"src\/GDAL\/Internal\/CPLError.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n , checkCPLError\n , checkGDALCall\n , checkGDALCall_\n , withQuietErrorHandler\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Monad (void, liftM)\nimport Control.DeepSeq (NFData(..))\nimport Control.Monad.Catch (MonadThrow(throwM))\nimport Control.Exception (\n Exception (..)\n , SomeException\n , throw\n , finally\n )\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable, cast)\n\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr)\nimport Foreign.Storable (peekByteOff, peek)\nimport Foreign.Marshal.Utils (with)\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport GDAL.Internal.Util (toEnumC, runBounded)\nimport GDAL.Internal.CPLString (peekEncodedCString)\n\n#include \"cpl_error.h\"\n#include \"errorhandler.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\ninstance NFData ErrorType where\n rnf e = seq e ()\n\n\ndata GDALException\n = forall e. Exception e =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !Text}\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException :: Exception e=> e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException :: Exception e => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\nthrowBindingException :: (MonadThrow m, Exception e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\ninstance NFData ErrorNum where\n rnf e = seq e ()\n\ncheckGDALCall\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO a\ncheckGDALCall isOk act = withErrorHandler $ \\ stack -> do\n a <- act\n err <- peekLastError stack\n case isOk err a of\n Nothing -> return a\n Just e -> throw e\n{-# INLINE checkGDALCall #-}\n\ncheckGDALCall_\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO ()\n{-# INLINE checkGDALCall_ #-}\ncheckGDALCall_ isOk = void . checkGDALCall isOk\n\ncheckCPLError :: Text -> IO CInt -> IO ()\ncheckCPLError msg = checkGDALCall_ $ \\mExc r ->\n case (mExc, toEnumC r) of\n (Nothing, CE_None) -> Nothing\n (Nothing, e) -> Just (GDALException e AssertionFailed msg)\n (e, _) -> e\n{-# INLINE checkCPLError #-}\n\n{#pointer ErrorCell #}\ntype ErrorStack = Ptr ErrorCell\n\npeekLastError :: ErrorStack -> IO (Maybe GDALException)\npeekLastError stack = do\n ec <- peek stack\n if ec == nullPtr\n then return Nothing\n else do\n msg <- peekEncodedCString =<< {#get ErrorCell->msg #} ec\n errClass <- liftM toEnumC ({#get ErrorCell->errClass#} ec)\n errNo <- liftM toEnumC ({#get ErrorCell->errNo#} ec)\n return (Just (GDALException errClass errNo msg))\n\nwithErrorHandler :: (ErrorStack -> IO a) -> IO a\nwithErrorHandler act = runBounded $ with nullPtr $ \\stack ->\n ({#call unsafe push_error_handler as ^#} stack >> act stack)\n `finally` ({#call unsafe pop_error_handler as ^#} stack)\n{-# INLINE withErrorHandler #-}\n\n\nwithQuietErrorHandler :: IO a -> IO a\nwithQuietErrorHandler a = runBounded ((pushIt >> a) `finally` popIt)\n where\n pushIt = {#call unsafe CPLPushErrorHandler as ^#} c_quietErrorHandler\n popIt = {#call unsafe CPLPopErrorHandler as ^#}\n\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr (CInt -> CInt -> Ptr CChar -> IO ())\n","old_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.CPLError (\n GDALException (..)\n , ErrorType (..)\n , ErrorNum (..)\n , isGDALException\n , isBindingException\n , throwBindingException\n , bindingExceptionToException\n , bindingExceptionFromException\n , checkCPLError\n , checkGDALCall\n , checkGDALCall_\n , withQuietErrorHandler\n) where\n\n{# context lib = \"gdal\" prefix = \"CPL\" #}\n\nimport Control.Monad (void, liftM)\nimport Control.Monad.Catch (MonadThrow(throwM))\nimport Control.Exception (\n Exception (..)\n , SomeException\n , throw\n , finally\n )\nimport Data.Maybe (isJust)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable, cast)\n\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr)\nimport Foreign.Storable (peekByteOff, peek)\nimport Foreign.Marshal.Utils (with)\n\n-- work around https:\/\/github.com\/haskell\/c2hs\/issues\/151\nimport qualified Foreign.C.Types as C2HSImp\n\nimport GDAL.Internal.Util (toEnumC, runBounded)\nimport GDAL.Internal.CPLString (peekEncodedCString)\n\n#include \"cpl_error.h\"\n#include \"errorhandler.h\"\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq, Show) #}\n\n\ndata GDALException\n = forall e. Exception e =>\n GDALBindingException !e\n | GDALException { gdalErrType :: !ErrorType\n , gdalErrNum :: !ErrorNum\n , gdalErrMsg :: !Text}\n deriving Typeable\n\nderiving instance Show GDALException\n\ninstance Exception GDALException\n\nbindingExceptionToException :: Exception e=> e -> SomeException\nbindingExceptionToException = toException . GDALBindingException\n\nbindingExceptionFromException :: Exception e => SomeException -> Maybe e\nbindingExceptionFromException x = do\n GDALBindingException a <- fromException x\n cast a\n\n\nthrowBindingException :: (MonadThrow m, Exception e) => e -> m a\nthrowBindingException = throwM . bindingExceptionToException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\nisBindingException :: SomeException -> Bool\nisBindingException e\n = case fromException e of\n Just (GDALBindingException _) -> True\n _ -> False\n\n{#enum define ErrorNum {\n CPLE_None as None\n , CPLE_AppDefined as AppDefined\n , CPLE_OutOfMemory as OutOfMemory\n , CPLE_FileIO as FileIO\n , CPLE_OpenFailed as OpenFailed\n , CPLE_IllegalArg as IllegalArg\n , CPLE_NotSupported as NotSupported\n , CPLE_AssertionFailed as AssertionFailed\n , CPLE_NoWriteAccess as NoWriteAccess\n , CPLE_UserInterrupt as UserInterrupt\n , CPLE_ObjectNull as ObjectNull\n } deriving (Eq, Bounded, Show) #}\n\n\ncheckGDALCall\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO a\ncheckGDALCall isOk act = withErrorHandler $ \\ stack -> do\n a <- act\n err <- peekLastError stack\n case isOk err a of\n Nothing -> return a\n Just e -> throw e\n{-# INLINE checkGDALCall #-}\n\ncheckGDALCall_\n :: Exception e\n => (Maybe GDALException -> a -> Maybe e) -> IO a -> IO ()\n{-# INLINE checkGDALCall_ #-}\ncheckGDALCall_ isOk = void . checkGDALCall isOk\n\ncheckCPLError :: Text -> IO CInt -> IO ()\ncheckCPLError msg = checkGDALCall_ $ \\mExc r ->\n case (mExc, toEnumC r) of\n (Nothing, CE_None) -> Nothing\n (Nothing, e) -> Just (GDALException e AssertionFailed msg)\n (e, _) -> e\n{-# INLINE checkCPLError #-}\n\n{#pointer ErrorCell #}\ntype ErrorStack = Ptr ErrorCell\n\npeekLastError :: ErrorStack -> IO (Maybe GDALException)\npeekLastError stack = do\n ec <- peek stack\n if ec == nullPtr\n then return Nothing\n else do\n msg <- peekEncodedCString =<< {#get ErrorCell->msg #} ec\n errClass <- liftM toEnumC ({#get ErrorCell->errClass#} ec)\n errNo <- liftM toEnumC ({#get ErrorCell->errNo#} ec)\n return (Just (GDALException errClass errNo msg))\n\nwithErrorHandler :: (ErrorStack -> IO a) -> IO a\nwithErrorHandler act = runBounded $ with nullPtr $ \\stack ->\n ({#call unsafe push_error_handler as ^#} stack >> act stack)\n `finally` ({#call unsafe pop_error_handler as ^#} stack)\n{-# INLINE withErrorHandler #-}\n\n\nwithQuietErrorHandler :: IO a -> IO a\nwithQuietErrorHandler a = runBounded ((pushIt >> a) `finally` popIt)\n where\n pushIt = {#call unsafe CPLPushErrorHandler as ^#} c_quietErrorHandler\n popIt = {#call unsafe CPLPopErrorHandler as ^#}\n\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr (CInt -> CInt -> Ptr CChar -> IO ())\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f92fe9d1e7eedd1ff986e6049511901ee283ce3e","subject":"Fix memory leak.","message":"Fix memory leak.\n\ndarcs-hash:20090201203541-ed7c9-b3b21c584d51a4662ca5126d9b025541c60ef94a.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 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 = String -> [(String,String)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = String -> 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 = String -> 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 <- peekCString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekCString 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\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 <- peekCString 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_ <- peekCStringLen (cdata, fromIntegral len)\n handler data_\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","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 C2HS\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BSL\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 ()\nnewtype Parser = Parser (ForeignPtr ())\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 return $ Parser fptr\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.\n{#fun XML_Parse as parseChunk\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 = String -> [(String,String)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = String -> 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 = String -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler handler = mkCStartElementHandler h where\n h ptr cname cattrs = do\n name <- peekCString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekCString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser handler = do\n withParser parser $ \\p -> do\n handler' <- wrapStartElementHandler handler\n {#call unsafe XML_SetStartElementHandler as ^#} p handler'\n\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler handler = mkCEndElementHandler h where\n h ptr cname = do\n name <- peekCString cname\n handler name\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser handler = do\n withParser parser $ \\p -> do\n handler' <- wrapEndElementHandler handler\n {#call unsafe XML_SetEndElementHandler as ^#} p handler'\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler handler = mkCCharacterDataHandler h where\n h ptr cdata len = do\n data_ <- peekCStringLen (cdata, fromIntegral len)\n handler data_\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser handler = do\n withParser parser $ \\p -> do\n handler' <- wrapCharacterDataHandler handler\n {#call unsafe XML_SetCharacterDataHandler as ^#} p handler'\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6f21a8c8c04b831ac91d2a1a04405e7496d7211f","subject":"gnomevfs: use c2hs {#enum#} for FilePermissions instead of hand coding it","message":"gnomevfs: use c2hs {#enum#} for FilePermissions instead of hand coding it\n\ndarcs-hash:20071108034949-21862-cad7f55a434b5539daafb47a762e4808dc0ab28d.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gnomevfs\/System\/Gnome\/VFS\/Types.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Types (\n \n Handle(..),\n withHandle,\n \n Result(..),\n Error(..),\n \n OpenMode(..),\n SeekPosition(..),\n \n FileInfo(..),\n FileFlags(..),\n FileInfoFields(..),\n SetFileInfoMask(..),\n FileInfoOptions(..),\n FilePermissions(..),\n FileSize,\n FileOffset,\n FileType(..),\n InodeNumber,\n IDs,\n \n MonitorHandle(..),\n withMonitorHandle,\n MonitorCallback,\n MonitorType,\n MonitorEventType,\n \n URI(..),\n TextURI,\n newURI,\n withURI,\n ToplevelURI(..),\n newToplevelURI,\n withToplevelURI,\n URIHideOptions(..),\n \n DirectoryHandle(..),\n withDirectoryHandle,\n \n MakeURIDirs(..),\n DirectoryVisitOptions(..),\n DirectoryVisitCallback,\n DirectoryVisitResult(..),\n FindDirectoryKind(..),\n \n XferOptions(..),\n XferProgressStatus(..),\n XferOverwriteMode(..),\n XferOverwriteAction(..),\n XferErrorMode(..),\n XferErrorAction(..),\n XferPhase(..),\n XferProgressInfo(..),\n XferProgressCallback,\n XferErrorCallback,\n XferOverwriteCallback,\n XferDuplicateCallback,\n \n Cancellation(..),\n newCancellation,\n withCancellation,\n \n VolumeOpSuccessCallback,\n VolumeOpFailureCallback,\n CVolumeOpCallback,\n VolumeType(..),\n DeviceType(..),\n \n MIMEType,\n \n module System.Gnome.VFS.Hierarchy,\n \n DriveID,\n newDrive,\n withDrive,\n \n VolumeID,\n newVolume,\n withVolume,\n \n wrapVolumeMonitor,\n withVolumeMonitor\n \n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.Reader\nimport Data.ByteString (ByteString)\nimport Data.Typeable\nimport Data.Word (Word64)\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GObject#} (GObject(..),\n GObjectClass,\n toGObject,\n unsafeCastGObject)\n{#import System.Glib.GType#} (GType,\n typeInstanceIsA)\n{#import System.Gnome.VFS.Hierarchy#}\n\nimport System.Posix.Types (DeviceID, EpochTime)\n\n--------------------------------------------------------------------\n\ngTypeCast :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\ngTypeCast gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n--------------------------------------------------------------------\n\n-- | The result of a file operation.\n{# enum GnomeVFSResult as Result {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show, Typeable) #}\n\nnewtype Error = Error Result\n deriving (Show, Typeable)\n\n-- | A handle to an open file\n{# pointer *GnomeVFSHandle as Handle foreign newtype #}\nwithHandle (Handle cHandle) = withForeignPtr cHandle\n\n-- | Specifies the start position for a seek operation.\n{# enum GnomeVFSSeekPosition as SeekPosition {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n{# enum GnomeVFSOpenMode as OpenMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n--------------------------------------------------------------------\n\n-- | A record type containing information about a file.\ndata FileInfo = FileInfo {\n fileInfoName :: Maybe String, -- ^ the name of the file,\n -- without the path\n fileInfoType :: Maybe FileType, -- ^ the type of the file;\n -- i.e. regular, directory,\n -- block-device, etc.\n fileInfoPermissions :: Maybe [FilePermissions], -- ^ the permissions for the\n -- file\n fileInfoFlags :: Maybe [FileFlags], -- ^ flags providing\n -- additional information\n -- about the file\n fileInfoDevice :: Maybe DeviceID, -- ^ the device the file\n -- resides on\n fileInfoInode :: Maybe InodeNumber, -- ^ the inode number of the\n -- file\n fileInfoLinkCount :: Maybe Int, -- ^ the total number of\n -- hard links to the file\n fileInfoIDs :: Maybe IDs, -- ^ the user and group IDs\n -- owning the file\n fileInfoSize :: Maybe FileSize, -- ^ the size of the file in\n -- bytes\n fileInfoBlockCount :: Maybe FileSize, -- ^ the size of the file in\n -- filesystem blocks\n fileInfoIOBlockSize :: Maybe FileSize, -- ^ the optimal buffer size\n -- for reading from and\n -- writing to the file\n fileInfoATime :: Maybe EpochTime, -- ^ the time of last access\n fileInfoMTime :: Maybe EpochTime, -- ^ the time of last modification\n fileInfoCTime :: Maybe EpochTime, -- ^ the time of last attribute modification\n fileInfoSymlinkName :: Maybe String, -- ^ the location this\n -- symlink points to, if\n -- @fileInfoFlags@ contains 'FileFlagsSymlink'\n fileInfoMIMEType :: Maybe MIMEType -- ^ the MIME-type of the\n -- file\n } deriving (Eq, Show)\n\n{# enum GnomeVFSFileInfoFields as FileInfoFields {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Options for reading information from a file.\n{# enum GnomeVFSFileInfoOptions as FileInfoOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying additional information about a file.\n{# enum GnomeVFSFileFlags as FileFlags {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying the attributes of a file that should be changed.\n{# enum GnomeVFSSetFileInfoMask as SetFileInfoMask {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Identifies the type of a file.\n{# enum GnomeVFSFileType as FileType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ninstance Flags FileInfoOptions\ninstance Flags FileInfoFields\ninstance Flags FileFlags\ninstance Flags SetFileInfoMask\n\n-- | An integral type wide enough to hold the size of a file.\ntype FileSize = Word64\n\n-- | An integral type wide enough to hold an offset into a file.\ntype FileOffset = Word64\n\n-- | An integral type wide enough to hold the inode number of a file.\ntype InodeNumber = Word64\n\n-- | A pair holding the user ID and group ID of a file owner.\ntype IDs = (Int, Int)\n\n-- | UNIX-like permissions for a file.\n{# enum GnomeVFSFilePermissions as FilePermissions {\n GNOME_VFS_PERM_SUID as PermSUID,\n GNOME_VFS_PERM_SGID as PermSGID,\n GNOME_VFS_PERM_STICKY as PermSticky,\n GNOME_VFS_PERM_USER_READ as PermUserRead,\n GNOME_VFS_PERM_USER_WRITE as PermUserWrite,\n GNOME_VFS_PERM_USER_EXEC as PermUserExec,\n GNOME_VFS_PERM_USER_ALL as PermUserAll,\n GNOME_VFS_PERM_GROUP_READ as PermGroupRead,\n GNOME_VFS_PERM_GROUP_WRITE as PermGroupWrite,\n GNOME_VFS_PERM_GROUP_EXEC as PermGroupExec,\n GNOME_VFS_PERM_GROUP_ALL as PermGroupAll,\n GNOME_VFS_PERM_OTHER_READ as PermOtherRead,\n GNOME_VFS_PERM_OTHER_WRITE as PermOtherWrite,\n GNOME_VFS_PERM_OTHER_EXEC as PermOtherExec,\n GNOME_VFS_PERM_OTHER_ALL as PermOtherAll,\n GNOME_VFS_PERM_ACCESS_READABLE as PermAccessReadable,\n GNOME_VFS_PERM_ACCESS_WRITABLE as PermAccessWritable,\n GNOME_VFS_PERM_ACCESS_EXECUTABLE as PermAccessExecutable\n } deriving (Eq, Bounded, Show) #}\ninstance Flags FilePermissions\n\n--------------------------------------------------------------------\n\n-- | A 'URI' is a semi-textual representation of a uniform\n-- resource identifier. It contains the information about a resource\n-- location encoded as canononicalized text, but also holds extra\n-- information about the context in which the URI is used.\n{# pointer *GnomeVFSURI as URI foreign newtype #}\n\nnewURI :: Ptr URI\n -> IO URI\nnewURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr cURI cURIFinalizer\nwrapURI :: Ptr URI\n -> IO URI\nwrapURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr_ cURI\nforeign import ccall \"&gnome_vfs_uri_unref\"\n cURIFinalizer :: FunPtr (Ptr URI -> IO ())\n\nwithURI (URI cURI) = withForeignPtr cURI\n\n-- | The toplevel URI element used to access resources stored on a\n-- remote server.\n{# pointer *GnomeVFSToplevelURI as ToplevelURI foreign newtype #}\nwithToplevelURI (ToplevelURI cToplevelURI) = withForeignPtr cToplevelURI\nnewToplevelURI :: Ptr ToplevelURI\n -> IO ToplevelURI\nnewToplevelURI cToplevelURI = liftM ToplevelURI $ newForeignPtr_ cToplevelURI\n\n-- | Flags specifying which fields of a 'URI' should be hidden when\n-- converted to a string using 'uriToString'.\n{# enum GnomeVFSURIHideOptions as URIHideOptions {\n GNOME_VFS_URI_HIDE_NONE as URIHideNone,\n GNOME_VFS_URI_HIDE_USER_NAME as URIHideUserName,\n GNOME_VFS_URI_HIDE_PASSWORD as URIHidePassword,\n GNOME_VFS_URI_HIDE_HOST_NAME as URIHideHostName,\n GNOME_VFS_URI_HIDE_HOST_PORT as URIHideHostPort,\n GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD as URIHideToplevelMethod,\n GNOME_VFS_URI_HIDE_FRAGMENT_IDENTIFIER as URIHideFragmentIdentifier\n } deriving (Eq, Bounded, Show) #}\ninstance Flags URIHideOptions\n\n-- | A string that can be passed to 'uriFromString' to create a valid\n-- 'URI'.\ntype TextURI = String\n\n--------------------------------------------------------------------\n\n-- | A handle to an open directory.\n{# pointer *GnomeVFSDirectoryHandle as DirectoryHandle foreign newtype #}\nwithDirectoryHandle (DirectoryHandle cDirectoryHandle) = withForeignPtr cDirectoryHandle\n\n-- | Options controlling the way in which a directories are visited.\n{# enum GnomeVFSDirectoryVisitOptions as DirectoryVisitOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags DirectoryVisitOptions\n\n-- | A callback that will be called for each entry when passed to\n-- 'directoryVisit', 'directoryVisitURI', 'directoryVisitFiles', or\n-- 'directoryVisitFilesAtURI'.\ntype DirectoryVisitCallback = String -- ^ the path of the visited file, relative to the base directory\n -> FileInfo -- ^ the 'FileInfo' for the visited file\n -> Bool -- ^ 'True' if returning 'DirectoryVisitRecurse' will cause a loop\n -> IO DirectoryVisitResult -- ^ the next action to be taken\n\n-- | An enumerated value that must be returned from a\n-- 'DirectoryVisitCallback'. The 'directoryVisit' and related\n-- functions will perform the action specified.\ndata DirectoryVisitResult = DirectoryVisitStop -- ^ stop visiting files\n | DirectoryVisitContinue -- ^ continue as normal\n | DirectoryVisitRecurse -- ^ recursively visit the current entry\n deriving (Eq, Enum)\n\n-- | Specifies which kind of directory 'findDirectory' should look for.\n{# enum GnomeVFSFindDirectoryKind as FindDirectoryKind {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n-- | Flags that may be passed to 'makeURIFromInputWithDirs'. If the\n-- path passed is non-absolute (i.e., a relative path), the\n-- directories specified will be searched as well.\n{# enum GnomeVFSMakeURIDirs as MakeURIDirs {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags MakeURIDirs\n\n--------------------------------------------------------------------\n\n-- | A handle to a file-system monitor.\nnewtype MonitorHandle = MonitorHandle (ForeignPtr MonitorHandle, {# type GnomeVFSMonitorCallback #})\nwithMonitorHandle (MonitorHandle (monitorHandleForeignPtr, _)) = withForeignPtr monitorHandleForeignPtr\n\n-- | A callback that must be passed to 'monitorAdd'. It will be\n-- called any time a file or directory is changed.\ntype MonitorCallback = MonitorHandle -- ^ the handle to a filesystem monitor\n -> TextURI -- ^ the URI being monitored\n -> TextURI -- ^ the actual file that was modified\n -> MonitorEventType -- ^ the event that occured\n -> IO ()\n\n-- | The type of filesystem object that is to be monitored.\n{# enum GnomeVFSMonitorType as MonitorType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | The type of event that caused a 'MonitorCallback' to be called.\n{# enum GnomeVFSMonitorEventType as MonitorEventType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\nwrapMonitorHandle :: (Ptr MonitorHandle, {# type GnomeVFSMonitorCallback #})\n -> IO MonitorHandle\nwrapMonitorHandle (cMonitorHandle, cMonitorCallback) =\n do monitorHandleForeignPtr <- newForeignPtr_ cMonitorHandle\n return $ MonitorHandle (monitorHandleForeignPtr, cMonitorCallback)\n\n--------------------------------------------------------------------\n\n-- | Options controlling how the 'System.Gnome.VFS.Xfer.xferURI' and related functions behave.\n{# enum GnomeVFSXferOptions as XferOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags XferOptions\n\n{# enum GnomeVFSXferProgressStatus as XferProgressStatus {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteMode as XferOverwriteMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteAction as XferOverwriteAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorMode as XferErrorMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorAction as XferErrorAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferPhase as XferPhase {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ndata XferProgressInfo = XferProgressInfo {\n xferProgressInfoVFSStatus :: Result, -- ^ current VFS status\n xferProgressInfoPhase :: XferPhase, -- ^ phase of the transfer\n xferProgressInfoSourceName :: Maybe String, -- ^ currently transferring source URI\n xferProgressInfoTargetName :: Maybe String, -- ^ currently transferring target URI\n xferProgressInfoFileIndex :: Word, -- ^ index of the file currently being transferred\n xferProgressInfoFilesTotal :: Word, -- ^ total number of files being transferred\n xferProgressInfoBytesTotal :: FileSize, -- ^ total size of all files in bytes\n xferProgressInfoFileSize :: FileSize, -- ^ size of the file currently being transferred\n xferProgressInfoBytesCopied :: FileSize, -- ^ number of bytes already transferred in the current file\n xferProgressInfoTotalBytesCopied :: FileSize, -- ^ total number of bytes already transferred\n xferProgressInfoTopLevelItem :: Bool -- ^ 'True' if the file being transferred is a top-level item;\n -- 'False' if it is inside a directory\n } deriving (Eq)\n\n-- | The type of the first callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI' and related functions. This\n-- callback will be called periodically during transfers that are\n-- progressing normally.\ntype XferProgressCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO Bool -- ^ return 'Prelude.False' to abort the transfer, 'Prelude.True' otherwise.\n\n-- | The type of the second callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- whenever an error occurs.\ntype XferErrorCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferErrorAction -- ^ the action to be performed in response to the error\n\n-- | The type of the third callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a file would be overwritten.\ntype XferOverwriteCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferOverwriteAction -- ^ the action to be performed when the target file already exists\n\n-- | The type of the fourth callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a duplicate filename is found.\ntype XferDuplicateCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> String -- ^ @duplicateName@ - the name of the target file\n -> Int -- ^ @duplicateCount@ - the number of duplicates that exist\n -> IO (Maybe String) -- ^ the new filename that should be used, or 'Prelude.Nothing' to abort.\n\n--------------------------------------------------------------------\n\n-- | An object that can be used for signalling cancellation of an\n-- operation.\n{# pointer *GnomeVFSCancellation as Cancellation foreign newtype #}\n\nnewCancellation :: Ptr Cancellation\n -> IO Cancellation\nnewCancellation cCancellationPtr | cCancellationPtr \/= nullPtr =\n liftM Cancellation $ newForeignPtr cCancellationPtr cancellationFinalizer\nforeign import ccall unsafe \"&gnome_vfs_cancellation_destroy\"\n cancellationFinalizer :: FunPtr (Ptr Cancellation -> IO ())\nwithCancellation (Cancellation cCancellation) = withForeignPtr cCancellation\n\n--------------------------------------------------------------------\n\nwithVolume (Volume cVolume) = withForeignPtr cVolume\nnewVolume :: Ptr Volume\n -> IO Volume\nnewVolume cVolume | cVolume \/= nullPtr =\n liftM Volume $ newForeignPtr cVolume volumeFinalizer\nforeign import ccall unsafe \"&gnome_vfs_volume_unref\"\n volumeFinalizer :: FunPtr (Ptr Volume -> IO ())\n\n-- | An action to be performed when a volume operation completes successfully.\ntype VolumeOpSuccessCallback = IO ()\n-- | An action to be performed when a volume operation fails.\ntype VolumeOpFailureCallback = String\n -> String\n -> IO ()\n\n-- | Identifies the device type of a 'Volume' or 'Drive'.\n{#enum GnomeVFSDeviceType as DeviceType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n-- | Identifies the type of a 'Volume'.\n{#enum GnomeVFSVolumeType as VolumeType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ntype CVolumeOpCallback = {# type gboolean #}\n -> CString\n -> CString\n -> Ptr ()\n -> IO ()\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Drive'\ntype DriveID = {# type gulong #}\n\nwithDrive (Drive cDrive) = withForeignPtr cDrive\nnewDrive :: Ptr Drive\n -> IO Drive\nnewDrive cDrive | cDrive \/= nullPtr =\n liftM Drive $ newForeignPtr cDrive driveFinalizer\nforeign import ccall unsafe \"&gnome_vfs_drive_unref\"\n driveFinalizer :: FunPtr (Ptr Drive -> IO ())\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Volume'.\ntype VolumeID = {# type gulong #}\n\nwithVolumeMonitor (VolumeMonitor cVolumeMonitor) = withForeignPtr cVolumeMonitor\nwrapVolumeMonitor :: Ptr VolumeMonitor\n -> IO VolumeMonitor\nwrapVolumeMonitor cVolumeMonitor | cVolumeMonitor \/= nullPtr =\n liftM VolumeMonitor $ newForeignPtr_ cVolumeMonitor\n\n--------------------------------------------------------------------\n\n-- | A string that will be treated as a MIME-type.\ntype MIMEType = String\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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Types (\n \n Handle(..),\n withHandle,\n \n Result(..),\n Error(..),\n \n OpenMode(..),\n SeekPosition(..),\n \n FileInfo(..),\n FileFlags(..),\n FileInfoFields(..),\n SetFileInfoMask(..),\n FileInfoOptions(..),\n FilePermissions(..),\n FileSize,\n FileOffset,\n FileType(..),\n InodeNumber,\n IDs,\n \n MonitorHandle(..),\n withMonitorHandle,\n MonitorCallback,\n MonitorType,\n MonitorEventType,\n \n URI(..),\n TextURI,\n newURI,\n withURI,\n ToplevelURI(..),\n newToplevelURI,\n withToplevelURI,\n URIHideOptions(..),\n \n DirectoryHandle(..),\n withDirectoryHandle,\n \n MakeURIDirs(..),\n DirectoryVisitOptions(..),\n DirectoryVisitCallback,\n DirectoryVisitResult(..),\n FindDirectoryKind(..),\n \n XferOptions(..),\n XferProgressStatus(..),\n XferOverwriteMode(..),\n XferOverwriteAction(..),\n XferErrorMode(..),\n XferErrorAction(..),\n XferPhase(..),\n XferProgressInfo(..),\n XferProgressCallback,\n XferErrorCallback,\n XferOverwriteCallback,\n XferDuplicateCallback,\n \n Cancellation(..),\n newCancellation,\n withCancellation,\n \n VolumeOpSuccessCallback,\n VolumeOpFailureCallback,\n CVolumeOpCallback,\n VolumeType(..),\n DeviceType(..),\n \n MIMEType,\n \n module System.Gnome.VFS.Hierarchy,\n \n DriveID,\n newDrive,\n withDrive,\n \n VolumeID,\n newVolume,\n withVolume,\n \n wrapVolumeMonitor,\n withVolumeMonitor\n \n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.Reader\nimport Data.ByteString (ByteString)\nimport Data.Typeable\nimport Data.Word (Word64)\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GObject#} (GObject(..),\n GObjectClass,\n toGObject,\n unsafeCastGObject)\n{#import System.Glib.GType#} (GType,\n typeInstanceIsA)\n{#import System.Gnome.VFS.Hierarchy#}\n\nimport System.Posix.Types (DeviceID, EpochTime)\n\n--------------------------------------------------------------------\n\ngTypeCast :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\ngTypeCast gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n--------------------------------------------------------------------\n\n-- | The result of a file operation.\n{# enum GnomeVFSResult as Result {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show, Typeable) #}\n\nnewtype Error = Error Result\n deriving (Show, Typeable)\n\n-- | A handle to an open file\n{# pointer *GnomeVFSHandle as Handle foreign newtype #}\nwithHandle (Handle cHandle) = withForeignPtr cHandle\n\n-- | Specifies the start position for a seek operation.\n{# enum GnomeVFSSeekPosition as SeekPosition {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n{# enum GnomeVFSOpenMode as OpenMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n--------------------------------------------------------------------\n\n-- | A record type containing information about a file.\ndata FileInfo = FileInfo {\n fileInfoName :: Maybe String, -- ^ the name of the file,\n -- without the path\n fileInfoType :: Maybe FileType, -- ^ the type of the file;\n -- i.e. regular, directory,\n -- block-device, etc.\n fileInfoPermissions :: Maybe [FilePermissions], -- ^ the permissions for the\n -- file\n fileInfoFlags :: Maybe [FileFlags], -- ^ flags providing\n -- additional information\n -- about the file\n fileInfoDevice :: Maybe DeviceID, -- ^ the device the file\n -- resides on\n fileInfoInode :: Maybe InodeNumber, -- ^ the inode number of the\n -- file\n fileInfoLinkCount :: Maybe Int, -- ^ the total number of\n -- hard links to the file\n fileInfoIDs :: Maybe IDs, -- ^ the user and group IDs\n -- owning the file\n fileInfoSize :: Maybe FileSize, -- ^ the size of the file in\n -- bytes\n fileInfoBlockCount :: Maybe FileSize, -- ^ the size of the file in\n -- filesystem blocks\n fileInfoIOBlockSize :: Maybe FileSize, -- ^ the optimal buffer size\n -- for reading from and\n -- writing to the file\n fileInfoATime :: Maybe EpochTime, -- ^ the time of last access\n fileInfoMTime :: Maybe EpochTime, -- ^ the time of last modification\n fileInfoCTime :: Maybe EpochTime, -- ^ the time of last attribute modification\n fileInfoSymlinkName :: Maybe String, -- ^ the location this\n -- symlink points to, if\n -- @fileInfoFlags@ contains 'FileFlagsSymlink'\n fileInfoMIMEType :: Maybe MIMEType -- ^ the MIME-type of the\n -- file\n } deriving (Eq, Show)\n\n{# enum GnomeVFSFileInfoFields as FileInfoFields {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Options for reading information from a file.\n{# enum GnomeVFSFileInfoOptions as FileInfoOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying additional information about a file.\n{# enum GnomeVFSFileFlags as FileFlags {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying the attributes of a file that should be changed.\n{# enum GnomeVFSSetFileInfoMask as SetFileInfoMask {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Identifies the type of a file.\n{# enum GnomeVFSFileType as FileType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ninstance Flags FileInfoOptions\ninstance Flags FileInfoFields\ninstance Flags FileFlags\ninstance Flags SetFileInfoMask\n\n-- | An integral type wide enough to hold the size of a file.\ntype FileSize = Word64\n\n-- | An integral type wide enough to hold an offset into a file.\ntype FileOffset = Word64\n\n-- | An integral type wide enough to hold the inode number of a file.\ntype InodeNumber = Word64\n\n-- | A pair holding the user ID and group ID of a file owner.\ntype IDs = (Int, Int)\n\n-- | UNIX-like permissions for a file.\ndata FilePermissions = PermSUID -- ^ the set-user-ID bit\n | PermSGID -- ^ the set-group-ID bit\n | PermSticky -- ^ the \\\"sticky\\\" bit\n | PermUserRead -- ^ owner read permission\n | PermUserWrite -- ^ owner write permission\n | PermUserExec -- ^ owner execute permission\n | PermUserAll -- ^ equivalent to\n -- @['PermUserRead', 'PermUserWrite', 'PermUserExec']@\n | PermGroupRead -- ^ group read permission\n | PermGroupWrite -- ^ group write permission\n | PermGroupExec -- ^ group execute permission\n | PermGroupAll -- ^ equivalent to\n -- @['PermGroupRead', 'PermGroupWrite', 'PermGroupExec']@\n | PermOtherRead -- ^ world read permission\n | PermOtherWrite -- ^ world write permission\n | PermOtherExec -- ^ world execute permission\n | PermOtherAll -- ^ equivalent to\n -- @['PermOtherRead', 'PermOtherWrite', 'PermOtherExec']@\n | PermAccessReadable -- ^ readable by the current process\n | PermAccessWritable -- ^ writable by the current process\n | PermAccessExecutable -- ^ executable by the current process\n deriving (Eq, Bounded, Show)\ninstance Flags FilePermissions\ninstance Enum FilePermissions where\n fromEnum PermSUID = 2048\n fromEnum PermSGID = 1024\n fromEnum PermSticky = 512\n fromEnum PermUserRead = 256\n fromEnum PermUserWrite = 128\n fromEnum PermUserExec = 64\n fromEnum PermUserAll = 448\n fromEnum PermGroupRead = 32\n fromEnum PermGroupWrite = 16\n fromEnum PermGroupExec = 8\n fromEnum PermGroupAll = 56\n fromEnum PermOtherRead = 4\n fromEnum PermOtherWrite = 2\n fromEnum PermOtherExec = 1\n fromEnum PermOtherAll = 7\n fromEnum PermAccessReadable = 65536\n fromEnum PermAccessWritable = 131072\n fromEnum PermAccessExecutable = 262144\n \n toEnum 2048 = PermSUID\n toEnum 1024 = PermSGID\n toEnum 512 = PermSticky\n toEnum 256 = PermUserRead\n toEnum 128 = PermUserWrite\n toEnum 64 = PermUserExec\n toEnum 448 = PermUserAll\n toEnum 32 = PermGroupRead\n toEnum 16 = PermGroupWrite\n toEnum 8 = PermGroupExec\n toEnum 56 = PermGroupAll\n toEnum 4 = PermOtherRead\n toEnum 2 = PermOtherWrite\n toEnum 1 = PermOtherExec\n toEnum 7 = PermOtherAll\n toEnum 65536 = PermAccessReadable\n toEnum 131072 = PermAccessWritable\n toEnum 262144 = PermAccessExecutable\n \n toEnum unmatched = error (\"FilePermissions.toEnum: Cannot match \" ++ show unmatched)\n\n--------------------------------------------------------------------\n\n-- | A 'URI' is a semi-textual representation of a uniform\n-- resource identifier. It contains the information about a resource\n-- location encoded as canononicalized text, but also holds extra\n-- information about the context in which the URI is used.\n{# pointer *GnomeVFSURI as URI foreign newtype #}\n\nnewURI :: Ptr URI\n -> IO URI\nnewURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr cURI cURIFinalizer\nwrapURI :: Ptr URI\n -> IO URI\nwrapURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr_ cURI\nforeign import ccall \"&gnome_vfs_uri_unref\"\n cURIFinalizer :: FunPtr (Ptr URI -> IO ())\n\nwithURI (URI cURI) = withForeignPtr cURI\n\n-- | The toplevel URI element used to access resources stored on a\n-- remote server.\n{# pointer *GnomeVFSToplevelURI as ToplevelURI foreign newtype #}\nwithToplevelURI (ToplevelURI cToplevelURI) = withForeignPtr cToplevelURI\nnewToplevelURI :: Ptr ToplevelURI\n -> IO ToplevelURI\nnewToplevelURI cToplevelURI = liftM ToplevelURI $ newForeignPtr_ cToplevelURI\n\n-- | Flags specifying which fields of a 'URI' should be hidden when\n-- converted to a string using 'uriToString'.\n{# enum GnomeVFSURIHideOptions as URIHideOptions {\n GNOME_VFS_URI_HIDE_NONE as URIHideNone,\n GNOME_VFS_URI_HIDE_USER_NAME as URIHideUserName,\n GNOME_VFS_URI_HIDE_PASSWORD as URIHidePassword,\n GNOME_VFS_URI_HIDE_HOST_NAME as URIHideHostName,\n GNOME_VFS_URI_HIDE_HOST_PORT as URIHideHostPort,\n GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD as URIHideToplevelMethod,\n GNOME_VFS_URI_HIDE_FRAGMENT_IDENTIFIER as URIHideFragmentIdentifier\n } deriving (Eq, Bounded, Show) #}\ninstance Flags URIHideOptions\n\n-- | A string that can be passed to 'uriFromString' to create a valid\n-- 'URI'.\ntype TextURI = String\n\n--------------------------------------------------------------------\n\n-- | A handle to an open directory.\n{# pointer *GnomeVFSDirectoryHandle as DirectoryHandle foreign newtype #}\nwithDirectoryHandle (DirectoryHandle cDirectoryHandle) = withForeignPtr cDirectoryHandle\n\n-- | Options controlling the way in which a directories are visited.\n{# enum GnomeVFSDirectoryVisitOptions as DirectoryVisitOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags DirectoryVisitOptions\n\n-- | A callback that will be called for each entry when passed to\n-- 'directoryVisit', 'directoryVisitURI', 'directoryVisitFiles', or\n-- 'directoryVisitFilesAtURI'.\ntype DirectoryVisitCallback = String -- ^ the path of the visited file, relative to the base directory\n -> FileInfo -- ^ the 'FileInfo' for the visited file\n -> Bool -- ^ 'True' if returning 'DirectoryVisitRecurse' will cause a loop\n -> IO DirectoryVisitResult -- ^ the next action to be taken\n\n-- | An enumerated value that must be returned from a\n-- 'DirectoryVisitCallback'. The 'directoryVisit' and related\n-- functions will perform the action specified.\ndata DirectoryVisitResult = DirectoryVisitStop -- ^ stop visiting files\n | DirectoryVisitContinue -- ^ continue as normal\n | DirectoryVisitRecurse -- ^ recursively visit the current entry\n deriving (Eq, Enum)\n\n-- | Specifies which kind of directory 'findDirectory' should look for.\n{# enum GnomeVFSFindDirectoryKind as FindDirectoryKind {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n-- | Flags that may be passed to 'makeURIFromInputWithDirs'. If the\n-- path passed is non-absolute (i.e., a relative path), the\n-- directories specified will be searched as well.\n{# enum GnomeVFSMakeURIDirs as MakeURIDirs {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags MakeURIDirs\n\n--------------------------------------------------------------------\n\n-- | A handle to a file-system monitor.\nnewtype MonitorHandle = MonitorHandle (ForeignPtr MonitorHandle, {# type GnomeVFSMonitorCallback #})\nwithMonitorHandle (MonitorHandle (monitorHandleForeignPtr, _)) = withForeignPtr monitorHandleForeignPtr\n\n-- | A callback that must be passed to 'monitorAdd'. It will be\n-- called any time a file or directory is changed.\ntype MonitorCallback = MonitorHandle -- ^ the handle to a filesystem monitor\n -> TextURI -- ^ the URI being monitored\n -> TextURI -- ^ the actual file that was modified\n -> MonitorEventType -- ^ the event that occured\n -> IO ()\n\n-- | The type of filesystem object that is to be monitored.\n{# enum GnomeVFSMonitorType as MonitorType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | The type of event that caused a 'MonitorCallback' to be called.\n{# enum GnomeVFSMonitorEventType as MonitorEventType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\nwrapMonitorHandle :: (Ptr MonitorHandle, {# type GnomeVFSMonitorCallback #})\n -> IO MonitorHandle\nwrapMonitorHandle (cMonitorHandle, cMonitorCallback) =\n do monitorHandleForeignPtr <- newForeignPtr_ cMonitorHandle\n return $ MonitorHandle (monitorHandleForeignPtr, cMonitorCallback)\n\n--------------------------------------------------------------------\n\n-- | Options controlling how the 'System.Gnome.VFS.Xfer.xferURI' and related functions behave.\n{# enum GnomeVFSXferOptions as XferOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags XferOptions\n\n{# enum GnomeVFSXferProgressStatus as XferProgressStatus {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteMode as XferOverwriteMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteAction as XferOverwriteAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorMode as XferErrorMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorAction as XferErrorAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferPhase as XferPhase {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ndata XferProgressInfo = XferProgressInfo {\n xferProgressInfoVFSStatus :: Result, -- ^ current VFS status\n xferProgressInfoPhase :: XferPhase, -- ^ phase of the transfer\n xferProgressInfoSourceName :: Maybe String, -- ^ currently transferring source URI\n xferProgressInfoTargetName :: Maybe String, -- ^ currently transferring target URI\n xferProgressInfoFileIndex :: Word, -- ^ index of the file currently being transferred\n xferProgressInfoFilesTotal :: Word, -- ^ total number of files being transferred\n xferProgressInfoBytesTotal :: FileSize, -- ^ total size of all files in bytes\n xferProgressInfoFileSize :: FileSize, -- ^ size of the file currently being transferred\n xferProgressInfoBytesCopied :: FileSize, -- ^ number of bytes already transferred in the current file\n xferProgressInfoTotalBytesCopied :: FileSize, -- ^ total number of bytes already transferred\n xferProgressInfoTopLevelItem :: Bool -- ^ 'True' if the file being transferred is a top-level item;\n -- 'False' if it is inside a directory\n } deriving (Eq)\n\n-- | The type of the first callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI' and related functions. This\n-- callback will be called periodically during transfers that are\n-- progressing normally.\ntype XferProgressCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO Bool -- ^ return 'Prelude.False' to abort the transfer, 'Prelude.True' otherwise.\n\n-- | The type of the second callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- whenever an error occurs.\ntype XferErrorCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferErrorAction -- ^ the action to be performed in response to the error\n\n-- | The type of the third callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a file would be overwritten.\ntype XferOverwriteCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferOverwriteAction -- ^ the action to be performed when the target file already exists\n\n-- | The type of the fourth callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a duplicate filename is found.\ntype XferDuplicateCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> String -- ^ @duplicateName@ - the name of the target file\n -> Int -- ^ @duplicateCount@ - the number of duplicates that exist\n -> IO (Maybe String) -- ^ the new filename that should be used, or 'Prelude.Nothing' to abort.\n\n--------------------------------------------------------------------\n\n-- | An object that can be used for signalling cancellation of an\n-- operation.\n{# pointer *GnomeVFSCancellation as Cancellation foreign newtype #}\n\nnewCancellation :: Ptr Cancellation\n -> IO Cancellation\nnewCancellation cCancellationPtr | cCancellationPtr \/= nullPtr =\n liftM Cancellation $ newForeignPtr cCancellationPtr cancellationFinalizer\nforeign import ccall unsafe \"&gnome_vfs_cancellation_destroy\"\n cancellationFinalizer :: FunPtr (Ptr Cancellation -> IO ())\nwithCancellation (Cancellation cCancellation) = withForeignPtr cCancellation\n\n--------------------------------------------------------------------\n\nwithVolume (Volume cVolume) = withForeignPtr cVolume\nnewVolume :: Ptr Volume\n -> IO Volume\nnewVolume cVolume | cVolume \/= nullPtr =\n liftM Volume $ newForeignPtr cVolume volumeFinalizer\nforeign import ccall unsafe \"&gnome_vfs_volume_unref\"\n volumeFinalizer :: FunPtr (Ptr Volume -> IO ())\n\n-- | An action to be performed when a volume operation completes successfully.\ntype VolumeOpSuccessCallback = IO ()\n-- | An action to be performed when a volume operation fails.\ntype VolumeOpFailureCallback = String\n -> String\n -> IO ()\n\n-- | Identifies the device type of a 'Volume' or 'Drive'.\n{#enum GnomeVFSDeviceType as DeviceType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n-- | Identifies the type of a 'Volume'.\n{#enum GnomeVFSVolumeType as VolumeType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ntype CVolumeOpCallback = {# type gboolean #}\n -> CString\n -> CString\n -> Ptr ()\n -> IO ()\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Drive'\ntype DriveID = {# type gulong #}\n\nwithDrive (Drive cDrive) = withForeignPtr cDrive\nnewDrive :: Ptr Drive\n -> IO Drive\nnewDrive cDrive | cDrive \/= nullPtr =\n liftM Drive $ newForeignPtr cDrive driveFinalizer\nforeign import ccall unsafe \"&gnome_vfs_drive_unref\"\n driveFinalizer :: FunPtr (Ptr Drive -> IO ())\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Volume'.\ntype VolumeID = {# type gulong #}\n\nwithVolumeMonitor (VolumeMonitor cVolumeMonitor) = withForeignPtr cVolumeMonitor\nwrapVolumeMonitor :: Ptr VolumeMonitor\n -> IO VolumeMonitor\nwrapVolumeMonitor cVolumeMonitor | cVolumeMonitor \/= nullPtr =\n liftM VolumeMonitor $ newForeignPtr_ cVolumeMonitor\n\n--------------------------------------------------------------------\n\n-- | A string that will be treated as a MIME-type.\ntype MIMEType = String\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"928416c24f88242ed79e48804d87c8fe7492f6f9","subject":"Generalized the type of safeGetPixel","message":"Generalized the type of safeGetPixel\n","repos":"BeautifulDestinations\/CV,aleator\/CV,aleator\/CV,TomMD\/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, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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 = 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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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":"d52ea73cf69249096b61b1313b299c94c38a3e56","subject":"Fixed connect(), for real this time","message":"Fixed connect(), for real this time\n","repos":"RyanGlScott\/bluetooth,bneijt\/bluetooth","old_file":"src\/Network\/Bluetooth\/Linux\/Socket.chs","new_file":"src\/Network\/Bluetooth\/Linux\/Socket.chs","new_contents":"{-# LANGUAGE ScopedTypeVariables #-}\nmodule Network.Bluetooth.Linux.Socket where\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport Data.Either\n\nimport Foreign.C.Error\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Exception\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Protocol\nimport Network.Bluetooth.Utils\nimport Network.Socket\nimport Network.Socket.Internal\n\n#include \n#include \n#include \"wr_l2cap.h\"\n#include \"wr_rfcomm.h\"\n\nbluetoothSocket :: BluetoothProtocol -> IO Socket\nbluetoothSocket proto = socket AF_BLUETOOTH sockType protoNum\n where\n sockType = case proto of\n L2CAP -> SeqPacket\n RFCOMM -> Stream\n protoNum = cFromEnum proto\n\nbluetoothBind :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothBind (MkSocket fd _ _ proto sockStatus) bdaddr portNum =\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n \"bind: can't peform bind on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n case protoEnum of\n L2CAP -> callBind $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> callBind . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n return Bound\n where\n callBind :: SockAddrBluetooth a => a -> IO ()\n callBind sockaddr = throwSocketErrorIfMinus1Retry_ \"bind\" $ c_bind fd sockaddr\n\nbluetoothBindAnyPort :: Socket -> BluetoothAddr -> IO BluetoothPort\nbluetoothBindAnyPort sock@(MkSocket _ _ _ proto _) bdaddr = do\n port <- bindAnyPort (cToEnum proto) bdaddr\n bluetoothBind sock bdaddr $ fromIntegral port\n return port\n\nbluetoothListen :: Socket -> Int -> IO ()\nbluetoothListen = listen\n\nbluetoothAccept :: Socket -> IO (Socket, BluetoothAddr)\nbluetoothAccept sock@(MkSocket _ family sockType proto sockStatus) = do\n currentStatus <- readMVar sockStatus\n when (currentStatus \/= Connected && currentStatus \/= Listening) . ioError . userError $\n \"accept: can't perform accept on socket (\" ++ show (family,sockType,proto) ++ \") in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callAccept :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO (Socket, BluetoothAddr)\n callAccept sock'@(MkSocket fd _ _ _ _) sockaddrPtr size = do\n newFd <- throwSocketErrorWaitRead sock' \"accept\" . fmap fst $ c_accept fd sockaddrPtr size\n bdaddr <- fmap sockAddrBluetoothAddr $ peek sockaddrPtr\n newStatus <- newMVar Connected\n return (MkSocket newFd family sockType proto newStatus, bdaddr)\n\nbluetoothConnect :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothConnect sock@(MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n status <- takeMVar sockStatus\n when (status \/= NotConnected && status \/= Bound) . ioError . userError $\n \"connect: can't peform connect on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n \n let connectLoop :: IO ()\n connectLoop = do\n r <- case protoEnum of\n L2CAP -> c_connect fd $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> c_connect fd . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n putMVar sockStatus Connected\n when (r == -1) $ do\n err <- getErrno\n case () of\n _ | err == eINTR -> connectLoop\n _ | err == eINPROGRESS -> connectBlocked\n _otherwise -> throwSocketError \"connect\"\n \n connectBlocked :: IO ()\n connectBlocked = do\n threadWaitWrite $ fromIntegral fd\n err <- getSocketOption sock SoError\n unless (err == 0) . throwSocketErrorCode \"connect\" $ fromIntegral err\n \n connectLoop `onException` close sock\n\nbluetoothSocketPort :: Socket -> IO BluetoothPort\nbluetoothSocketPort sock@(MkSocket _ _ _ proto status) = do\n currentStatus <- readMVar status\n when (currentStatus == NotConnected || currentStatus == Closed) . ioError . userError $\n \"getsockname: can't get name of socket in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callGetSockName :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO BluetoothPort\n callGetSockName (MkSocket fd _ _ _ _) sockaddrPtr size = do\n throwSocketErrorIfMinus1Retry_ \"getsockname\" . fmap fst $ c_getsockname fd sockaddrPtr size\n fmap sockAddrPort $ peek sockaddrPtr\n\n-------------------------------------------------------------------------------\n\nbindAnyPort :: BluetoothProtocol -> BluetoothAddr -> IO BluetoothPort\nbindAnyPort proto addr = do\n avails <- flip filterM (portRange proto) $ \\portNum -> do\n sock <- bluetoothSocket proto\n res <- try $ bluetoothBind sock addr portNum\n close sock\n return $ isRight (res :: Either IOError ())\n case avails of\n portNum:_ -> return portNum\n _ -> ioError $ userError \"Unable to find any available port\"\n where\n portRange L2CAP = [4097, 4099 .. 32767]\n portRange RFCOMM = [1 .. 30]\n\n{#fun unsafe bind as c_bind\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe accept as c_accept\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun unsafe connect as c_connect\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe getsockname as c_getsockname\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun pure wr_htobs as c_htobs\n `Integral i' =>\n { fromIntegral `i'\n } -> `i' fromIntegral #}","old_contents":"{-# LANGUAGE ScopedTypeVariables #-}\nmodule Network.Bluetooth.Linux.Socket where\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport Data.Either\n\nimport Foreign.C.Error\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Exception\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Protocol\nimport Network.Bluetooth.Utils\nimport Network.Socket\nimport Network.Socket.Internal\n\n#include \n#include \n#include \"wr_l2cap.h\"\n#include \"wr_rfcomm.h\"\n\nbluetoothSocket :: BluetoothProtocol -> IO Socket\nbluetoothSocket proto = socket AF_BLUETOOTH sockType protoNum\n where\n sockType = case proto of\n L2CAP -> SeqPacket\n RFCOMM -> Stream\n protoNum = cFromEnum proto\n-- bluetoothSocket proto = do\n-- let family = AF_BLUETOOTH\n-- sockType = case proto of\n-- L2CAP -> SeqPacket\n-- RFCOMM -> Stream\n-- fd <- throwSocketErrorIfMinus1Retry \"socket\" $ c_socket family sockType proto\n-- status <- newMVar NotConnected\n-- return $ MkSocket fd family sockType (cFromEnum proto) status\n\nbluetoothBind :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothBind (MkSocket fd _ _ proto sockStatus) bdaddr portNum =\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n \"bind: can't peform bind on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n case protoEnum of\n L2CAP -> callBind $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> callBind . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n return Bound\n where\n callBind :: SockAddrBluetooth a => a -> IO ()\n callBind sockaddr = throwSocketErrorIfMinus1Retry_ \"bind\" $ c_bind fd sockaddr\n\nbluetoothBindAnyPort :: Socket -> BluetoothAddr -> IO BluetoothPort\nbluetoothBindAnyPort sock@(MkSocket _ _ _ proto _) bdaddr = do\n port <- bindAnyPort (cToEnum proto) bdaddr\n bluetoothBind sock bdaddr $ fromIntegral port\n return port\n\nbluetoothListen :: Socket -> Int -> IO ()\nbluetoothListen = listen\n\nbluetoothAccept :: Socket -> IO (Socket, BluetoothAddr)\nbluetoothAccept sock@(MkSocket _ family sockType proto sockStatus) = do\n currentStatus <- readMVar sockStatus\n when (currentStatus \/= Connected && currentStatus \/= Listening) . ioError . userError $\n \"accept: can't perform accept on socket (\" ++ show (family,sockType,proto) ++ \") in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callAccept :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO (Socket, BluetoothAddr)\n callAccept sock'@(MkSocket fd _ _ _ _) sockaddrPtr size = do\n newFd <- throwSocketErrorWaitRead sock' \"accept\" . fmap fst $ c_accept fd sockaddrPtr size\n bdaddr <- fmap sockAddrBluetoothAddr $ peek sockaddrPtr\n newStatus <- newMVar Connected\n return (MkSocket newFd family sockType proto newStatus, bdaddr)\n\nbluetoothConnect :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothConnect sock@(MkSocket fd _ _ proto sockStatus) bdaddr portNum =\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n \"connect: can't peform connect on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n \n let connectLoop :: IO ()\n connectLoop = do\n r <- case protoEnum of\n L2CAP -> c_connect fd $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> c_connect fd . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n when (r == -1) $ do\n err <- getErrno\n case () of\n _ | err == eINTR -> connectLoop\n _ | err == eINPROGRESS -> connectBlocked\n _otherwise -> throwSocketError \"connect\"\n \n connectBlocked :: IO ()\n connectBlocked = do\n threadWaitWrite $ fromIntegral fd\n err <- getSocketOption sock SoError\n when (err == 0) . throwSocketErrorCode \"connect\" $ fromIntegral err\n \n attemptConnection :: IO SocketStatus\n attemptConnection = do\n connectLoop\n return Connected\n \n attemptConnection `onException` close sock\n\nbluetoothSocketPort :: Socket -> IO BluetoothPort\nbluetoothSocketPort sock@(MkSocket _ _ _ proto status) = do\n currentStatus <- readMVar status\n when (currentStatus == NotConnected || currentStatus == Closed) . ioError . userError $\n \"getsockname: can't get name of socket in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callGetSockName :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO BluetoothPort\n callGetSockName (MkSocket fd _ _ _ _) sockaddrPtr size = do\n throwSocketErrorIfMinus1Retry_ \"getsockname\" . fmap fst $ c_getsockname fd sockaddrPtr size\n fmap sockAddrPort $ peek sockaddrPtr\n\n-------------------------------------------------------------------------------\n\nbindAnyPort :: BluetoothProtocol -> BluetoothAddr -> IO BluetoothPort\nbindAnyPort proto addr = do\n avails <- flip filterM (portRange proto) $ \\portNum -> do\n sock <- bluetoothSocket proto\n res <- try $ bluetoothBind sock addr portNum\n close sock\n return $ isRight (res :: Either IOError ())\n case avails of\n portNum:_ -> return portNum\n _ -> ioError $ userError \"Unable to find any available port\"\n where\n portRange L2CAP = [4097, 4099 .. 32767]\n portRange RFCOMM = [1 .. 30]\n\n-- {#fun unsafe socket as c_socket\n-- { packFamily `Family'\n-- , packSocketType `SocketType'\n-- , cFromEnum `BluetoothProtocol'\n-- } -> `CInt' id #}\n\n{#fun unsafe bind as c_bind\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe accept as c_accept\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun unsafe connect as c_connect\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe getsockname as c_getsockname\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun pure wr_htobs as c_htobs\n `Integral i' =>\n { fromIntegral `i'\n } -> `i' fromIntegral #}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1434e39c11e1a0f6bea943cb41b07c796181760b","subject":"Scaffold out more stuff in the new knot tying function","message":"Scaffold out more stuff in the new knot tying function\n","repos":"wangxiayang\/llvm-analysis,travitch\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/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\n\nimport Data.LLVM.Private.C2HS\nimport Data.LLVM.Types\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 :: FilePath -> IO (Either String Module)\ntranslate bitcodefile = do\n m <- marshalLLVM bitcodefile\n let initialState = KnotState { valueMap = M.empty }\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 (ir, _) <- evalStateT (mfix (tieKnot m)) initialState\n\n disposeCModule m\n return $! Right ir\n\ntype KnotMonad = StateT KnotState IO\n\ntieKnot :: ModulePtr -> (Module, KnotState) -> KnotMonad (Module, KnotState)\ntieKnot m (_, finalState) = do\n s <- get\n return (undefined, s)","old_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)","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e74711a23ce9755ff9a5a2abdb547f7b067f1979","subject":"Fix types, remove key binding signals.","message":"Fix types, remove key binding signals.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"2d626bff39dc3a377b1a530e287e4ce17037fc7d","subject":"Add explicit export list for Error module","message":"Add explicit export list for Error module\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Error.chs","new_file":"Foreign\/CUDA\/Driver\/Error.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Error\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Error (\n\n -- * CUDA Errors\n Status(..), CUDAException(..),\n describe,\n cudaError, requireSDK,\n resultIfOk, nothingIfOk,\n\n) where\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Control.Exception\nimport Control.Monad\nimport Data.Typeable\nimport Foreign.C\nimport Foreign.Marshal\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Language.Haskell.TH\nimport System.IO.Unsafe\nimport Text.Printf\n\n\n#include \"cbits\/stubs.h\"\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 , CUDA_ERROR_INVALID_PTX as InvalidPTX\n , CUDA_ERROR_INVALID_PC as InvalidPC\n }\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\n#if CUDA_VERSION >= 6000\ndescribe status\n = unsafePerformIO $ resultIfOk =<< cuGetErrorString status\n\n{# fun unsafe cuGetErrorString\n { cFromEnum `Status'\n , alloca- `String' ppeek* } -> `Status' cToEnum #}\n where\n ppeek = peek >=> peekCString\n\n#else\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\"\n#endif\n#if CUDA_VERSION >= 3000 && CUDA_VERSION < 3020\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\n#if CUDA_VERSION >= 3010\ndescribe UnsupportedLimit = \"limits not supported by device\"\ndescribe SharedObjectSymbolNotFound = \"link to a shared object failed to resolve\"\ndescribe SharedObjectInitFailed = \"shared object initialisation failed\"\n#endif\n#if CUDA_VERSION >= 3020\ndescribe OperatingSystem = \"operating system call failed\"\n#endif\n#if CUDA_VERSION >= 4000\ndescribe ProfilerDisabled = \"profiling APIs disabled: application running with visual profiler\"\ndescribe ProfilerNotInitialized = \"profiler not initialised\"\ndescribe ProfilerAlreadyStarted = \"profiler already started\"\ndescribe ProfilerAlreadyStopped = \"profiler already stopped\"\ndescribe ContextAlreadyInUse = \"context is already bound to a thread and in use\"\ndescribe PeerAccessAlreadyEnabled = \"peer access already enabled\"\ndescribe PeerAccessNotEnabled = \"peer access has not been enabled\"\ndescribe PrimaryContextActive = \"primary context for this device has already been initialised\"\ndescribe ContextIsDestroyed = \"context already destroyed\"\n#endif\n#if CUDA_VERSION >= 4010\ndescribe Assert = \"device-side assert triggered\"\ndescribe TooManyPeers = \"peer mapping resources exhausted\"\ndescribe HostMemoryAlreadyRegistered = \"part or all of the requested memory range is already mapped\"\ndescribe HostMemoryNotRegistered = \"pointer does not correspond to a registered memory region\"\n#endif\n#if CUDA_VERSION >= 5000\ndescribe PeerAccessUnsupported = \"peer access is not supported across the given devices\"\ndescribe NotPermitted = \"not permitted\"\ndescribe NotSupported = \"not supported\"\n#endif\ndescribe Unknown = \"unknown error\"\n#endif\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-- A specially formatted error message\n--\nrequireSDK :: Name -> Double -> IO a\nrequireSDK n v = cudaError $ printf \"'%s' requires at least cuda-%3.1f\\n\" (show n) v\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\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--\n{-# INLINE resultIfOk #-}\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--\n{-# INLINE nothingIfOk #-}\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Error\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Error\n where\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Control.Exception\nimport Control.Monad\nimport Data.Typeable\nimport Foreign.C\nimport Foreign.Marshal\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Language.Haskell.TH\nimport System.IO.Unsafe\nimport Text.Printf\n\n\n#include \"cbits\/stubs.h\"\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 , CUDA_ERROR_INVALID_PTX as InvalidPTX\n , CUDA_ERROR_INVALID_PC as InvalidPC\n }\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\n#if CUDA_VERSION >= 6000\ndescribe status\n = unsafePerformIO $ resultIfOk =<< cuGetErrorString status\n\n{# fun unsafe cuGetErrorString\n { cFromEnum `Status'\n , alloca- `String' ppeek* } -> `Status' cToEnum #}\n where\n ppeek = peek >=> peekCString\n\n#else\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\"\n#endif\n#if CUDA_VERSION >= 3000 && CUDA_VERSION < 3020\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\n#if CUDA_VERSION >= 3010\ndescribe UnsupportedLimit = \"limits not supported by device\"\ndescribe SharedObjectSymbolNotFound = \"link to a shared object failed to resolve\"\ndescribe SharedObjectInitFailed = \"shared object initialisation failed\"\n#endif\n#if CUDA_VERSION >= 3020\ndescribe OperatingSystem = \"operating system call failed\"\n#endif\n#if CUDA_VERSION >= 4000\ndescribe ProfilerDisabled = \"profiling APIs disabled: application running with visual profiler\"\ndescribe ProfilerNotInitialized = \"profiler not initialised\"\ndescribe ProfilerAlreadyStarted = \"profiler already started\"\ndescribe ProfilerAlreadyStopped = \"profiler already stopped\"\ndescribe ContextAlreadyInUse = \"context is already bound to a thread and in use\"\ndescribe PeerAccessAlreadyEnabled = \"peer access already enabled\"\ndescribe PeerAccessNotEnabled = \"peer access has not been enabled\"\ndescribe PrimaryContextActive = \"primary context for this device has already been initialised\"\ndescribe ContextIsDestroyed = \"context already destroyed\"\n#endif\n#if CUDA_VERSION >= 4010\ndescribe Assert = \"device-side assert triggered\"\ndescribe TooManyPeers = \"peer mapping resources exhausted\"\ndescribe HostMemoryAlreadyRegistered = \"part or all of the requested memory range is already mapped\"\ndescribe HostMemoryNotRegistered = \"pointer does not correspond to a registered memory region\"\n#endif\n#if CUDA_VERSION >= 5000\ndescribe PeerAccessUnsupported = \"peer access is not supported across the given devices\"\ndescribe NotPermitted = \"not permitted\"\ndescribe NotSupported = \"not supported\"\n#endif\ndescribe Unknown = \"unknown error\"\n#endif\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-- A specially formatted error message\n--\nrequireSDK :: Name -> Double -> IO a\nrequireSDK n v = cudaError $ printf \"'%s' requires at least cuda-%3.1f\\n\" (show n) v\n\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\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--\n{-# INLINE resultIfOk #-}\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--\n{-# INLINE nothingIfOk #-}\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":"7412726ace0e3da0180461564b8496f8d54753b7","subject":"Implement pageGetAnnotMapping","message":"Implement pageGetAnnotMapping\n","repos":"YoEight\/poppler_bak","old_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n--\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n AnnotMapping,\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n -- pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageAddAnnot,\n pageRemoveAnnot,\n pageRectangleNew\n -- pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page =\n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\n{- pageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into\n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n-}\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page\n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n\n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page\npageGetIndex page =\n liftM fromIntegral $\n {#call poppler_page_get_index #} (toPage page)\n\n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success\n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n\n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile =\n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded)\n -> IO [PopplerRectangle]\npageFindText page text =\n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n\n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page =\n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n\n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1.\npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'.\npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'.\npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'.\npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'.\npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection =\n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #}\n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs\n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background\n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n\npageAddAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageAddAnnot page annot =\n {# call poppler_page_add_annot #} (toPage page) (toAnnot annot)\n\npageRemoveAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageRemoveAnnot page annot =\n {# call poppler_page_remove_annot #} (toPage page) (toAnnot annot)\n\npageRectangleNew :: IO PopplerRectangle\npageRectangleNew =\n (peekPopplerRectangle . castPtr) =<< {# call poppler_rectangle_new #}\n\n{#pointer *AnnotMapping foreign newtype #}\n\nmakeNewAnnotMapping :: Ptr AnnotMapping -> IO AnnotMapping\nmakeNewAnnotMapping rPtr = do\n annotMapping <- newForeignPtr rPtr poppler_annot_mapping_free\n return (AnnotMapping annotMapping)\n\npageGetAnnotMapping :: PageClass page => page -> IO [AnnotMapping]\npageGetAnnotMapping page = do\n glistPtr <- {# call poppler_page_get_annot_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewAnnotMapping list\n {#call unsafe poppler_page_free_form_field_mapping #} (castPtr glistPtr)\n return mappings\n\nforeign import ccall unsafe \"&poppler_annot_mapping_free\"\n poppler_annot_mapping_free :: FinalizerPtr AnnotMapping\n\n\n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\n{-\npageRenderSelectionToPixbuf :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> Color -- ^ @glyphColor@ color to use for drawing glyphs\n -> Color -- ^ @backgroundColor@ color to use for the selection background\n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor =\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n-}\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n--\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n -- pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageAddAnnot,\n pageRemoveAnnot,\n pageRectangleNew\n -- pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page =\n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\n{- pageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into\n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n-}\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page\n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n\n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page\npageGetIndex page =\n liftM fromIntegral $\n {#call poppler_page_get_index #} (toPage page)\n\n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success\n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n\n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile =\n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded)\n -> IO [PopplerRectangle]\npageFindText page text =\n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n\n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page =\n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n\n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1.\npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'.\npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'.\npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'.\npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'.\npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection =\n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #}\n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs\n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background\n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n\npageAddAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageAddAnnot page annot =\n {# call poppler_page_add_annot #} (toPage page) (toAnnot annot)\n\npageRemoveAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageRemoveAnnot page annot =\n {# call poppler_page_remove_annot #} (toPage page) (toAnnot annot)\n\npageRectangleNew :: IO PopplerRectangle\npageRectangleNew =\n (peekPopplerRectangle . castPtr) =<< {# call poppler_rectangle_new #}\n\n\n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\n{-\npageRenderSelectionToPixbuf :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> Color -- ^ @glyphColor@ color to use for drawing glyphs\n -> Color -- ^ @backgroundColor@ color to use for the selection background\n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor =\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n-}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"442e00f492752b9fcebe0b452145e208c2dc7b93","subject":"fixed comment that breaks haddock","message":"fixed comment that breaks haddock\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 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\nmodule GDAL.Internal.GDAL (\n GDALType\n , Datatype (..)\n , Geotransform (..)\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , registerAllDrivers\n , destroyDriverManager\n , setQuietErrorHandler\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n , newDerivedDatasetHandle\n) where\n\nimport Control.Applicative (Applicative, (<$>), (<*>))\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (bracket)\nimport Control.Monad (liftM, liftM2, when)\nimport Control.Monad.Catch (MonadThrow(throwM))\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Storable as St\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 (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.CPLString\nimport GDAL.Internal.Util\n\n\n#include \"gdal.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ninstance NFData Datatype where\n rnf a = a `seq`()\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset (Mutex, Ptr (Dataset s t a))\n\nunDataset :: Dataset s t a -> Ptr (Dataset s t a)\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t a -> (Ptr (Dataset s t a) -> 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 GDALRasterBandH as Band newtype nocode#}\n\nnewtype (Band s (t::DatasetMode) a)\n = Band (Mutex, Ptr (Band s t a))\n\nunBand :: Band s t a -> Ptr (Band s t a)\nunBand (Band (_,p)) = p\n\nwithLockedBandPtr\n :: Band s t a -> (Ptr (Band s t a) -> 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 GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = liftIO $\n throwIfError \"driverByName\" (c_driverByName (show s))\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> OptionList\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n (liftIO $ withCString p $ \\p' -> throwIfError \"open\" (open_ p' (fromEnumC m)))\n >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b\n | rt == bandDatatype b = return ()\n | otherwise = throwM GDALBindingError --throwM (InvalidType rt)\n where rt = datatype (Proxy :: Proxy a) \n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> OptionList\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n withLockedDatasetPtr ds $ \\dsPtr ->\n c_createCopy d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> OptionList\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = do\n registerFinalizer (safeCloseDataset p)\n m <- liftIO newMutex\n return $ Dataset (m,p)\n\nnewDerivedDatasetHandle\n :: Dataset s t a -> Ptr (Dataset s t b) -> GDAL s (Dataset s t b)\nnewDerivedDatasetHandle (Dataset (m,_)) p = do\n registerFinalizer (safeCloseDataset p)\n return $ Dataset (m,p)\n\nsafeCloseDataset :: Ptr (Dataset s t a) -> IO ()\nsafeCloseDataset p = do\n count <- c_dereferenceDataset p\n when (count < 1) $ (c_referenceDataset p >> c_closeDataset p)\n\nforeign import ccall \"gdal.h GDALReferenceDataset\"\n c_referenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALDereferenceDataset\"\n c_dereferenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> OptionList -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = let d = unDataset ds\n in (fromIntegral (getDatasetXSize_ d), fromIntegral (getDatasetYSize_ d)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ (unDataset d) >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError_ \"setDatasetProjection\" $\n withLockedDatasetPtr d $ withCString p . setProjection' \n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\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 a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ alloca $ \\p -> do\n throwIfError_ \"datasetGeotransform\" (getGeoTransform (unDataset d) p)\n peek (castPtr p)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n throwIfError_ \"setDatasetGeotransform\" $\n withLockedDatasetPtr ds $ \\dsPtr ->\n alloca $ \\p -> (poke p gt >> setGeoTransform dsPtr (castPtr p))\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_ . unDataset\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band (Dataset (m,dp)) = liftIO $ do\n p <- throwIfError \"getBand\" (c_getRasterBand dp (fromIntegral band))\n return (Band (m,p))\n\nforeign import ccall safe \"gdal.h GDALGetRasterBand\" c_getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO (Ptr (Band s t a))\n\n\nbandDatatype :: Band s t a -> Datatype\nbandDatatype = toEnumC . c_getRasterDataType . unBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" c_getRasterDataType\n :: Ptr (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ (unBand band) xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: Ptr (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ (unBand band))\n , fromIntegral (getBandYSize_ (unBand band)))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: Ptr (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: Ptr (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue = fmap (fmap fromNodata) . liftIO . c_bandNodataValue . unBand\n\nc_bandNodataValue :: Ptr (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: Ptr (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError_ \"setBandNodataValue\" $\n setNodata_ (unBand b) (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: Ptr (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError_ \"fillBand\" $\n fillRaster_ (unBand b) (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: Ptr (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\nreadBandPure band xoff yoff sx sy bx by = unsafePerformIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"readBandIO\" $ do\n e <- adviseRead_\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 rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- c_getMaskFlags 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 <- c_bandNodataValue bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- c_getMaskBand 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) (uToStValue uvec)\n if nElems \/= len\n then throwM GDALBindingError -- (InvalidRasterSize bx by)\n else withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"writeBand\" $\n rasterIO_\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\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr ()\n -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError_ \"readBandBlock\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: Ptr (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc band = liftIO $ do\n mNodata <- c_bandNodataValue (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n withLockedBandPtr band $ \\b ->\n throwIfError_ \"ifoldlM'\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount band\n (sx,sy) = bandBlockSize band\n (bx,by) = bandSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band x y uvec = do\n checkType band\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue 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 throwM GDALBindingError -- (InvalidBlockSize len)\n else withForeignPtr fp $ \\ptr ->\n throwIfError_ \"writeBandBlock\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: Ptr (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: Ptr (Band s t a) -> IO (Ptr (Band s t Word8))\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\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: Ptr (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n#ifdef STORABLE_COMPLEX\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\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\nmodule GDAL.Internal.GDAL (\n GDALType\n , Datatype (..)\n , Geotransform (..)\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , registerAllDrivers\n , destroyDriverManager\n , setQuietErrorHandler\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n , newDerivedDatasetHandle\n) where\n\nimport Control.Applicative (Applicative, (<$>), (<*>))\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (bracket)\nimport Control.Monad (liftM, liftM2, when)\nimport Control.Monad.Catch (MonadThrow(throwM))\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Storable as St\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 (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.CPLString\nimport GDAL.Internal.Util\n\n\n#include \"gdal.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ninstance NFData Datatype where\n rnf a = a `seq`()\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset (Mutex, Ptr (Dataset s t a))\n\nunDataset :: Dataset s t a -> Ptr (Dataset s t a)\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t a -> (Ptr (Dataset s t a) -> 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 GDALRasterBandH as Band newtype nocode#}\n\nnewtype (Band s (t::DatasetMode) a)\n = Band (Mutex, Ptr (Band s t a))\n\nunBand :: Band s t a -> Ptr (Band s t a)\nunBand (Band (_,p)) = p\n\nwithLockedBandPtr\n :: Band s t a -> (Ptr (Band s t a) -> 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 GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = liftIO $\n throwIfError \"driverByName\" (c_driverByName (show s))\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> OptionList\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n (liftIO $ withCString p $ \\p' -> throwIfError \"open\" (open_ p' (fromEnumC m)))\n >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b\n | rt == bandDatatype b = return ()\n | otherwise = throwM GDALBindingError --throwM (InvalidType rt)\n where rt = datatype (Proxy :: Proxy a) \n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> OptionList\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n withLockedDatasetPtr ds $ \\dsPtr ->\n c_createCopy d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> OptionList\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = do\n registerFinalizer (safeCloseDataset p)\n m <- liftIO newMutex\n return $ Dataset (m,p)\n\nnewDerivedDatasetHandle\n :: Dataset s t a -> Ptr (Dataset s t b) -> GDAL s (Dataset s t b)\nnewDerivedDatasetHandle (Dataset (m,_)) p = do\n registerFinalizer (safeCloseDataset p)\n return $ Dataset (m,p)\n\nsafeCloseDataset :: Ptr (Dataset s t a) -> IO ()\nsafeCloseDataset p = do\n count <- c_dereferenceDataset p\n when (count < 1) $ (c_referenceDataset p >> c_closeDataset p)\n\nforeign import ccall \"gdal.h GDALReferenceDataset\"\n c_referenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALDereferenceDataset\"\n c_dereferenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> OptionList -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = let d = unDataset ds\n in (fromIntegral (getDatasetXSize_ d), fromIntegral (getDatasetYSize_ d)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ (unDataset d) >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError_ \"setDatasetProjection\" $\n withLockedDatasetPtr d $ withCString p . setProjection' \n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\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 a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ alloca $ \\p -> do\n throwIfError_ \"datasetGeotransform\" (getGeoTransform (unDataset d) p)\n peek (castPtr p)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n throwIfError_ \"setDatasetGeotransform\" $\n withLockedDatasetPtr ds $ \\dsPtr ->\n alloca $ \\p -> (poke p gt >> setGeoTransform dsPtr (castPtr p))\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_ . unDataset\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band (Dataset (m,dp)) = liftIO $ do\n p <- throwIfError \"getBand\" (c_getRasterBand dp (fromIntegral band))\n return (Band (m,p))\n\nforeign import ccall safe \"gdal.h GDALGetRasterBand\" c_getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO (Ptr (Band s t a))\n\n\nbandDatatype :: Band s t a -> Datatype\nbandDatatype = toEnumC . c_getRasterDataType . unBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" c_getRasterDataType\n :: Ptr (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ (unBand band) xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: Ptr (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ (unBand band))\n , fromIntegral (getBandYSize_ (unBand band)))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: Ptr (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: Ptr (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue = fmap (fmap fromNodata) . liftIO . c_bandNodataValue . unBand\n\nc_bandNodataValue :: Ptr (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: Ptr (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError_ \"setBandNodataValue\" $\n setNodata_ (unBand b) (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: Ptr (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError_ \"fillBand\" $\n fillRaster_ (unBand b) (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: Ptr (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\nreadBandPure band xoff yoff sx sy bx by = unsafePerformIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"readBandIO\" $ do\n e <- adviseRead_\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 rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- c_getMaskFlags 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 <- c_bandNodataValue bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- c_getMaskBand 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) (uToStValue uvec)\n if nElems \/= len\n then throwM GDALBindingError -- $ InvalidRasterSize bx by\n else withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"writeBand\" $\n rasterIO_\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\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr ()\n -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError_ \"readBandBlock\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: Ptr (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc band = liftIO $ do\n mNodata <- c_bandNodataValue (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n withLockedBandPtr band $ \\b ->\n throwIfError_ \"ifoldlM'\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount band\n (sx,sy) = bandBlockSize band\n (bx,by) = bandSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band x y uvec = do\n checkType band\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue 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 throwM GDALBindingError -- (InvalidBlockSize len)\n else withForeignPtr fp $ \\ptr ->\n throwIfError_ \"writeBandBlock\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: Ptr (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: Ptr (Band s t a) -> IO (Ptr (Band s t Word8))\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\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: Ptr (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n#ifdef STORABLE_COMPLEX\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"52537575de3f667c4e3a58eb7229355fdb0dedfd","subject":"cleaned module namespace","message":"cleaned module namespace\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 , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , csInsnOffset\n , CsErr(..)\n , csSupport\n , csOpen\n , csClose\n , csOption\n , csErrno\n , csStrerror\n , csDisasm\n , csFree\n , csMalloc\n , csRegName\n , csInsnName\n , csGroupName\n , csInsnGroup\n , csRegRead\n , csRegWrite\n , csOpCount\n , csOpIndex\n ) where\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, withCString)\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-- TODO: what is this SKIPDATA business whose callback function\n-- we happily omitted?\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 ({#offsetof cs_detail.groups_count#} + 1)\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr p)\n CsArchArm64 -> Arm64 <$> peek (castPtr p)\n CsArchArm -> Arm <$> peek (castPtr p)\n CsArchMips -> Mips <$> peek (castPtr p)\n CsArchPpc -> Ppc <$> peek (castPtr p)\n CsArchSparc -> Sparc <$> peek (castPtr p)\n CsArchSysz -> SysZ <$> peek (castPtr p)\n CsArchXcore -> XCore <$> peek (castPtr p)\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 :: 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 =<< {#get cs_insn->mnemonic#} p)\n <*> (peekCString =<< {#get cs_insn->op_str#} p)\n <*> (castPtr <$> {#get cs_insn->detail#} p >>= peek)\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 withCString m ({#set cs_insn->mnemonic#} p)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else withCString o ({#set cs_insn->op_str#} p)\n csDetailPtr <- castPtr <$> ({#get cs_insn->detail#} p)\n poke csDetailPtr d\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 <- mapM (peek . plusPtr resPtr . ({#sizeof cs_insn#} *)) [0..resNum]\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-- TODO: decide whether we want cs_disasm_iter\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 where\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, withCString)\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-- TODO: what is this SKIPDATA business whose callback function\n-- we happily omitted?\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 ({#offsetof cs_detail.groups_count#} + 1)\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr p)\n CsArchArm64 -> Arm64 <$> peek (castPtr p)\n CsArchArm -> Arm <$> peek (castPtr p)\n CsArchMips -> Mips <$> peek (castPtr p)\n CsArchPpc -> Ppc <$> peek (castPtr p)\n CsArchSparc -> Sparc <$> peek (castPtr p)\n CsArchSysz -> SysZ <$> peek (castPtr p)\n CsArchXcore -> XCore <$> peek (castPtr p)\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 :: 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 =<< {#get cs_insn->mnemonic#} p)\n <*> (peekCString =<< {#get cs_insn->op_str#} p)\n <*> (castPtr <$> {#get cs_insn->detail#} p >>= peek)\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 withCString m ({#set cs_insn->mnemonic#} p)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else withCString o ({#set cs_insn->op_str#} p)\n csDetailPtr <- castPtr <$> ({#get cs_insn->detail#} p)\n poke csDetailPtr d\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 <- mapM (peek . plusPtr resPtr . ({#sizeof cs_insn#} *)) [0..resNum]\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-- TODO: decide whether we want cs_disasm_iter\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":"e98bb4ff7dc868705a53f37edd7cc295e45888a3","subject":"add build types","message":"add build types\n","repos":"IFCA\/opencl,Delan90\/opencl,Delan90\/opencl,IFCA\/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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n CLProgramInfo_, CLBuildStatus_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..),\n -- * Functions\n clSuccess, wrapPError, wrapCheckSuccess, wrapGetInfo, getCLValue, getEnumCL,\n getDeviceLocalMemType, bitmaskToFlags,\n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\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#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\n\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CL_SUCCESS\n then return $ Right v\n else return $ Left errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . toEnum . fromIntegral\n\nwrapGetInfo :: Storable a => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) \n -> IO (Either CLError b)\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap (Right . fconvert) $ peek dat\n else return . Left . toEnum . fromIntegral $ errcode\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . getEnumCL\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . getEnumCL\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . getEnumCL\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CL_EXEC_ERROR\n | otherwise = Just . getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes = bitmaskToFlags [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n -- * Functions\n clSuccess, wrapPError, wrapCheckSuccess, wrapGetInfo, getCLValue, getEnumCL,\n getDeviceLocalMemType, bitmaskToFlags,\n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\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\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CL_SUCCESS\n then return $ Right v\n else return $ Left errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . toEnum . fromIntegral\n\nwrapGetInfo :: Storable a => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) \n -> IO (Either CLError b)\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap (Right . fconvert) $ peek dat\n else return . Left . toEnum . fromIntegral $ errcode\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . getEnumCL\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . getEnumCL\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . getEnumCL\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CL_EXEC_ERROR\n | otherwise = Just . getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes = bitmaskToFlags [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e0c72501d949454ee972efc14d836cf1ff5241a4","subject":"peek and poke device arrays","message":"peek and poke device arrays\n\nIgnore-this: d7df1910df547ebe2513a955a823c08e\n\ndarcs-hash:20090722014939-115f9-5e66a5a919c72a2e3205784cb39af6a1198e39fa.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Data.Int\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Storable\n\nimport qualified Foreign.Marshal as F\n\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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\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\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [a']\n doPeek x = let bytes = fromIntegral n * (fromIntegral (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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\n doPoke x v = F.withArrayLen v $ \\n hptr ->\n withDevicePtr d $ \\dptr ->\n let bytes = (fromIntegral n) * (fromIntegral (sizeOf x)) in\n memcpy dptr hptr bytes HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream =\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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Data.Int\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Storable\n\nimport qualified Foreign.Marshal as F\n\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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\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\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream =\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":"8c0e0f3d711c2661f2dbf0d5277e725a5748649e","subject":"Version 0.3 of Image.chs. Not tested yet.","message":"Version 0.3 of Image.chs. Not tested yet.\n","repos":"aleator\/CV,aleator\/CV,BeautifulDestinations\/CV,TomMD\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, TypeFamilies #-}\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.ForeignPtr\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\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGBA\ndata LAB\n\n-- Bit Depths\ndata D8\ndata D32\ndata D64\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\nforeign 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 releaseImage 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 releaseImage iptr\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\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\nloadImage :: FilePath -> IO (Maybe (Image GrayScale Double))\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 Double))\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\n getSize = getSize . unS\n\n--loadColorImage 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 1)\n-- bw <- imageTo32F i\n-- return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB Double -> Image LAB Double\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB Double -> Image GrayScale Double\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale Double) where\n type P (Image GrayScale Double) = Double \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB Double) where\n type P (Image RGB Double) = (Double,Double,Double) \n getPixel (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\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\n\nemptyCopy img = 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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\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\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 = 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) | y <- [0..v-1] , x <- [0..u-1] | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, TypeFamilies #-}\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.ForeignPtr\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\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGBA\ndata LAB\n\n-- Bit Depths\ndata D8\ndata D32\ndata D64\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\nforeign 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 releaseImage 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 releaseImage iptr\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\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\nloadImage :: FilePath -> IO (Maybe (Image GrayScale Double))\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 Double))\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 SizeT a :: *\n getSize :: a -> SizeT a\n\ninstance Sized BareImage where\n type SizeT 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 SizeT (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n--loadColorImage 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 1)\n-- bw <- imageTo32F i\n-- return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB Double -> Image LAB Double\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB Double -> Image GrayScale Double\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale Double) where\n type P (Image GrayScale Double) = Double \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB Double) where\n type P (Image RGB Double) = (Double,Double,Double) \n getPixel (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\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\n\nemptyCopy img = create (getSize img) \n\nsaveImage :: FilePath -> Image c d -> IO ()\nsaveImage filename image = do\n fpi <- imageTo8Bit image\n withCString filename $ \\name -> \n withGenImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n--getSize image = unsafePerformIO $ withImage image $ \\i -> do\n-- w <- {#call getImageWidth#} i\n-- h <- {#call getImageHeight#} i\n-- return (fromIntegral w,fromIntegral h)\n\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Integral a) => (a,a) -> (a,a) -> 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 (width,height) = getSize image\n \ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withImage image $ \\i ->\n creatingImage ({#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 y 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 :: (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 (unS -> image1) (unS -> 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 img fun = do \n result <- cloneImage img\n fun result\n return result\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\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI no image\n cres <- {#call wrapCreateImage32F#} w 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 :: (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs = 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) 1\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) | y <- [0..v-1] , x <- [0..u-1] | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d8d7f6b0a315b20a00fdd3494bb3601316b5baa5","subject":"add rewireEdges","message":"add rewireEdges\n","repos":"kaizhang\/haskell-igraph,kaizhang\/haskell-igraph,kaizhang\/haskell-igraph","old_file":"src\/IGraph\/Algorithms\/Generators.chs","new_file":"src\/IGraph\/Algorithms\/Generators.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule IGraph.Algorithms.Generators\n ( full\n , star\n , ring\n , ErdosRenyiModel(..)\n , erdosRenyiGame\n , degreeSequenceGame\n , rewireEdges\n , rewire\n ) where\n\nimport Data.Serialize (Serialize)\nimport Data.Singletons (SingI, Sing, sing, fromSing)\nimport System.IO.Unsafe (unsafePerformIO)\nimport qualified Data.Map.Strict as M\nimport Control.Monad.Primitive (RealWorld)\n\nimport qualified Foreign.Ptr as C2HSImp\nimport Foreign\n\nimport IGraph\nimport IGraph.Mutable (MGraph(..))\n{#import IGraph.Internal #}\n{#import IGraph.Internal.Constants #}\n{# import IGraph.Internal.Initialization #}\n\n#include \"haskell_igraph.h\"\n\nfull :: forall d. SingI d\n => Int -- ^ The number of vertices in the graph.\n -> Bool -- ^ Whether to include self-edges (loops)\n -> Graph d () ()\nfull n hasLoop = unsafePerformIO $ do\n igraphInit\n gr <- igraphFull n directed hasLoop\n initializeNullAttribute gr\n return $ Graph gr M.empty\n where\n directed = case fromSing (sing :: Sing d) of\n D -> True\n U -> False\n{#fun igraph_full as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `Int', `Bool', `Bool'\n } -> `CInt' void- #}\n\n-- | Return the Star graph. The center node is always associated with id 0.\nstar :: Int -- ^ The number of nodes\n -> Graph 'U () ()\nstar n = unsafePerformIO $ do\n igraphInit\n gr <- igraphStar n IgraphStarUndirected 0\n initializeNullAttribute gr\n return $ Graph gr M.empty\n{#fun igraph_star as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `Int'\n , `StarMode'\n , `Int'\n } -> `CInt' void- #}\n\n-- | Creates a ring graph, a one dimensional lattice.\nring :: Int -> Graph 'U () ()\nring n = unsafePerformIO $ do\n igraphInit\n gr <- igraphRing n False False True\n initializeNullAttribute gr\n return $ Graph gr M.empty\n{#fun igraph_ring as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `Int'\n , `Bool'\n , `Bool'\n , `Bool'\n } -> `CInt' void- #}\n\ndata ErdosRenyiModel = GNP Int Double -- ^ G(n,p) graph, every possible edge is\n -- included in the graph with probability p.\n | GNM Int Int -- ^ G(n,m) graph, m edges are selected\n -- uniformly randomly in a graph with n\n -- vertices.\n\nerdosRenyiGame :: forall d. SingI d\n => ErdosRenyiModel\n -> Bool -- ^ self-loop\n -> IO (Graph d () ())\nerdosRenyiGame model self = do\n igraphInit\n gr <- case model of\n GNP n p -> igraphErdosRenyiGame IgraphErdosRenyiGnp n p directed self\n GNM n m -> igraphErdosRenyiGame IgraphErdosRenyiGnm n (fromIntegral m)\n directed self\n initializeNullAttribute gr\n return $ Graph gr M.empty\n where\n directed = case fromSing (sing :: Sing d) of\n D -> True\n U -> False\n{#fun igraph_erdos_renyi_game as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `ErdosRenyi', `Int', `Double', `Bool', `Bool'\n } -> `CInt' void- #}\n\n-- | Generates a random graph with a given degree sequence.\ndegreeSequenceGame :: [Int] -- ^ Out degree\n -> [Int] -- ^ In degree\n -> IO (Graph 'D () ())\ndegreeSequenceGame out_deg in_deg = do\n igraphInit\n withList out_deg $ \\out_deg' ->\n withList in_deg $ \\in_deg' -> do\n gr <- igraphDegreeSequenceGame out_deg' in_deg' IgraphDegseqSimple\n initializeNullAttribute gr\n return $ Graph gr M.empty\n{#fun igraph_degree_sequence_game as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , castPtr `Ptr Vector', castPtr `Ptr Vector', `Degseq'\n } -> `CInt' void- #}\n\n\n-- | Rewire the edges of a graph with constant probability.\nrewireEdges :: MGraph RealWorld d v e\n -> Double -- ^ The rewiring probability a constant between zero and\n -- one (inclusive).\n -> Bool -- ^ whether loop edges are allowed in the new graph, or not.\n -> Bool -- ^ whether multiple edges are allowed in the new graph.\n -> IO ()\nrewireEdges gr p loop multi = igraphRewireEdges (_mgraph gr) p loop multi\n{#fun igraph_rewire_edges as ^ \n { `IGraph'\n , `Double'\n , `Bool'\n , `Bool'\n } -> `CInt' void- #}\n\n-- | Randomly rewires a graph while preserving the degree distribution.\nrewire :: (Serialize v, Ord v, Serialize e)\n => Int -- ^ Number of rewiring trials to perform.\n -> Graph d v e\n -> IO (Graph d v e)\nrewire n gr = do\n gr' <- thaw gr\n igraphRewire (_mgraph gr') n IgraphRewiringSimple\n unsafeFreeze gr'\n{#fun igraph_rewire as ^ { `IGraph', `Int', `Rewiring' } -> `CInt' void-#}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule IGraph.Algorithms.Generators\n ( full\n , star\n , ring\n , ErdosRenyiModel(..)\n , erdosRenyiGame\n , degreeSequenceGame\n , rewire\n ) where\n\nimport Data.Serialize (Serialize)\nimport Data.Singletons (SingI, Sing, sing, fromSing)\nimport System.IO.Unsafe (unsafePerformIO)\nimport qualified Data.Map.Strict as M\n\nimport qualified Foreign.Ptr as C2HSImp\nimport Foreign\n\nimport IGraph\nimport IGraph.Mutable (MGraph(..))\n{#import IGraph.Internal #}\n{#import IGraph.Internal.Constants #}\n{# import IGraph.Internal.Initialization #}\n\n#include \"haskell_igraph.h\"\n\nfull :: forall d. SingI d\n => Int -- ^ The number of vertices in the graph.\n -> Bool -- ^ Whether to include self-edges (loops)\n -> Graph d () ()\nfull n hasLoop = unsafePerformIO $ do\n igraphInit\n gr <- igraphFull n directed hasLoop\n initializeNullAttribute gr\n return $ Graph gr M.empty\n where\n directed = case fromSing (sing :: Sing d) of\n D -> True\n U -> False\n{#fun igraph_full as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `Int', `Bool', `Bool'\n } -> `CInt' void- #}\n\n-- | Return the Star graph. The center node is always associated with id 0.\nstar :: Int -- ^ The number of nodes\n -> Graph 'U () ()\nstar n = unsafePerformIO $ do\n igraphInit\n gr <- igraphStar n IgraphStarUndirected 0\n initializeNullAttribute gr\n return $ Graph gr M.empty\n{#fun igraph_star as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `Int'\n , `StarMode'\n , `Int'\n } -> `CInt' void- #}\n\n-- | Creates a ring graph, a one dimensional lattice.\nring :: Int -> Graph 'U () ()\nring n = unsafePerformIO $ do\n igraphInit\n gr <- igraphRing n False False True\n initializeNullAttribute gr\n return $ Graph gr M.empty\n{#fun igraph_ring as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `Int'\n , `Bool'\n , `Bool'\n , `Bool'\n } -> `CInt' void- #}\n\ndata ErdosRenyiModel = GNP Int Double\n | GNM Int Int\n\nerdosRenyiGame :: forall d. SingI d\n => ErdosRenyiModel\n -> Bool -- ^ self-loop\n -> IO (Graph d () ())\nerdosRenyiGame model self = do\n igraphInit\n gr <- case model of\n GNP n p -> igraphErdosRenyiGame IgraphErdosRenyiGnp n p directed self\n GNM n m -> igraphErdosRenyiGame IgraphErdosRenyiGnm n (fromIntegral m)\n directed self\n initializeNullAttribute gr\n return $ Graph gr M.empty\n where\n directed = case fromSing (sing :: Sing d) of\n D -> True\n U -> False\n{#fun igraph_erdos_renyi_game as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , `ErdosRenyi', `Int', `Double', `Bool', `Bool'\n } -> `CInt' void- #}\n\n-- | Generates a random graph with a given degree sequence.\ndegreeSequenceGame :: [Int] -- ^ Out degree\n -> [Int] -- ^ In degree\n -> IO (Graph 'D () ())\ndegreeSequenceGame out_deg in_deg = do\n igraphInit\n withList out_deg $ \\out_deg' ->\n withList in_deg $ \\in_deg' -> do\n gr <- igraphDegreeSequenceGame out_deg' in_deg' IgraphDegseqSimple\n initializeNullAttribute gr\n return $ Graph gr M.empty\n{#fun igraph_degree_sequence_game as ^\n { allocaIGraph- `IGraph' addIGraphFinalizer*\n , castPtr `Ptr Vector', castPtr `Ptr Vector', `Degseq'\n } -> `CInt' void- #}\n\n-- | Randomly rewires a graph while preserving the degree distribution.\nrewire :: (Serialize v, Ord v, Serialize e)\n => Int -- ^ Number of rewiring trials to perform.\n -> Graph d v e\n -> IO (Graph d v e)\nrewire n gr = do\n gr' <- thaw gr\n igraphRewire (_mgraph gr') n IgraphRewiringSimple\n unsafeFreeze gr'\n{#fun igraph_rewire as ^ { `IGraph', `Int', `Rewiring' } -> `CInt' void-#}\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"6408ec3de225335719478d69b0937dce74369827","subject":"Write export list for Network.Grpc.Core.Call.","message":"Write export list for Network.Grpc.Core.Call.\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, NamedFieldPuns #-}\nmodule Network.Grpc.Core.Call\n ( Deadline(..)\n , ClientContext\n , CallOptions\n , withAbsoluteDeadline\n , withRelativeDeadlineSeconds\n , withRelativeDeadlineMillis\n , withParentContext\n , withParentContextPropagating\n , withMetadata\n , withCompression\n\n , newClientContext\n , destroyClientContext\n , MethodName\n , Arg\n\n , UnaryResult(..)\n , callUnary\n , callUpstream\n , callDownstream\n , callBidi\n , Client\n , Decoder\n , Encoder\n , Rpc\n , runRpc\n , joinReply\n\n , RpcReply(..)\n , RpcError(..)\n , RpcStatus(..)\n\n , initialMetadata\n , waitForStatus\n , sendMessage\n , receiveMessage\n , receiveAllMessages\n , closeCall\n , sendHalfClose\n , cancelCall\n , cancelCallWithStatus\n ) 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.Maybe (maybeToList)\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.ForeignPtr as C\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#} (Slice, CSlice, ByteBuffer)\nimport qualified Network.Grpc.Lib.ByteBuffer as BB\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 , coCompressionAlgo :: Maybe CompressionAlgorithm\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing [] Nothing\n mappend (CallOptions a b c d e) (CallOptions a' b' c' d' e') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n (getLast (Last e <> Last e'))\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\nwithCompression :: CompressionAlgorithm -> CallOptions\nwithCompression algo = mempty { coCompressionAlgo = Just algo }\n\ncompressionAsMetadata :: CompressionAlgorithm -> Metadata\ncompressionAsMetadata algo =\n Metadata\n compressionRequestAlgorithmMdKey\n (compressionAlgorithmName algo)\n 0\n\nmetadataToSend :: CallOptions -> [Metadata]\nmetadataToSend co =\n maybeToList (compressionAsMetadata <$> coCompressionAlgo co)\n ++ coMetadata co\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 <- completionQueueCreateForNext reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext ClientContext{ccCQ, ccWorker} = do\n completionQueueShutdown ccCQ\n CQ.waitWorkerTermination ccWorker\n\ntype MethodName = Slice\ntype Arg = B.ByteString\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{ccChannel, ccCQ} co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel ccChannel) C.nullPtr propagateDefaults ccCQ method (cHost ccChannel) deadline) grpcCallUnref $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (metadataToSend 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{ccChannel, ccCQ} co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel ccChannel) C.nullPtr propagateDefaults ccCQ method (cHost ccChannel) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n let client = RpcOk (Client crw defaultEncoder defaultDecoder)\n\n sendInitOp <- opSendInitialMetadata (metadataToSend co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> return client\n RpcError _ -> do\n clientCloseCall crw\n stat <- clientWaitForStatus crw\n case stat of\n RpcOk (RpcStatus _ code msg) -> return (RpcError (StatusError code msg))\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@ClientContext{ccChannel, ccCQ} co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel ccChannel) C.nullPtr propagateDefaults ccCQ method (cHost ccChannel) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n let client = RpcOk (Client crw defaultEncoder defaultDecoder)\n sendInitOp <- opSendInitialMetadata (metadataToSend co)\n res <- callBatch crw [ OpX sendInitOp ]\n\n case res of\n RpcOk _ -> return client\n RpcError _ -> do\n clientCloseCall crw\n stat <- clientWaitForStatus crw\n case stat of\n RpcOk (RpcStatus _ code msg) -> return (RpcError (StatusError code msg))\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@ClientContext{ccChannel, ccCQ} co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel ccChannel) C.nullPtr propagateDefaults ccCQ method (cHost ccChannel) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n let client = Client crw defaultEncoder defaultDecoder\n sendInitOp <- opSendInitialMetadata (metadataToSend co)\n res <- callBatch crw [ OpX sendInitOp ]\n\n case res of\n RpcOk _ -> return (RpcOk client)\n RpcError _ -> do\n clientCloseCall crw\n stat <- clientWaitForStatus crw\n case stat of\n RpcOk (RpcStatus _ code msg) -> return (RpcError (StatusError code msg))\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.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 <- 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 BB.byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr BB.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 <- BB.toLazyByteString bb\n BB.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\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n statusSlice <- BB.mallocSlice\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 C.withForeignPtr statusSlice $ \\statusSlice' -> {#set grpc_op->data.recv_status_on_client.status_details#} p statusSlice'\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- BB.toByteString statusSlice\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.finalizeForeignPtr statusSlice\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\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 = do\n prev <- tryReadMVar (statusFromServer crw)\n case prev of\n Just stat -> do\n return (RpcOk stat)\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX statusOp ]\n case res of\n RpcOk _ -> do\n status <- opRead statusOp\n return (RpcOk status)\n RpcError err ->\n return (RpcError err)\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 crw@ClientReaderWriter{..} = do\n _ <- clientWaitForStatus crw\n modifyMVar_ callMVar_ $ \\call -> do\n grpcCallUnref call\n return (error \"grpcCallUnref 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\nbranchOnClientStatus :: Client req resp\n -> Rpc a\n -> Rpc a\n -> (StatusCode -> B.ByteString -> Rpc a)\n -> Rpc a\nbranchOnClientStatus 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 branchOnClientStatus\n client\n (return ())\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\ninitialMetadata :: Client req resp -> Rpc [Metadata]\ninitialMetadata client = do\n joinClientRWOp client clientWaitForInitialMetadata\n\nwaitForStatus :: Client req resp -> Rpc RpcStatus\nwaitForStatus client = do\n _ <- clientRWOp client clientWaitForInitialMetadata\n joinClientRWOp client clientWaitForStatus\n\nreceiveMessage :: Client req resp -> Rpc (Maybe resp)\nreceiveMessage client = do\n throwIfErrorStatus client\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\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 status <- waitForStatus client\n clientRWOp client clientCloseCall\n case status of\n RpcStatus _ StatusOk _ -> return ()\n RpcStatus _ code detail -> throwE (StatusError code detail)\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 = do\n _ <- clientRWOp client clientCancelCall\n return ()\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 joinClientRWOp client (\\crw -> clientCancelCallWithStatus crw status details)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n 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","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.Maybe (maybeToList)\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.ForeignPtr as C\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#} (Slice, CSlice, ByteBuffer)\nimport qualified Network.Grpc.Lib.ByteBuffer as BB\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 , coCompressionAlgo :: Maybe CompressionAlgorithm\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing [] Nothing\n mappend (CallOptions a b c d e) (CallOptions a' b' c' d' e') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n (getLast (Last e <> Last e'))\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\nwithCompression :: CompressionAlgorithm -> CallOptions\nwithCompression algo = mempty { coCompressionAlgo = Just algo }\n\ncompressionAsMetadata :: CompressionAlgorithm -> Metadata\ncompressionAsMetadata algo =\n Metadata\n compressionRequestAlgorithmMdKey\n (compressionAlgorithmName algo)\n 0\n\nmetadataToSend :: CallOptions -> [Metadata]\nmetadataToSend co =\n maybeToList (compressionAsMetadata <$> coCompressionAlgo co)\n ++ coMetadata co\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 <- completionQueueCreateForNext 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 = Slice\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) grpcCallUnref $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (metadataToSend 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\n crw <- newClientReaderWriter ctx mcall\n let client = RpcOk (Client crw defaultEncoder defaultDecoder)\n\n sendInitOp <- opSendInitialMetadata (metadataToSend co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> return client\n RpcError _ -> do\n clientCloseCall crw\n stat <- clientWaitForStatus crw\n case stat of\n RpcOk (RpcStatus _ code msg) -> return (RpcError (StatusError code msg))\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\n crw <- newClientReaderWriter ctx mcall\n let client = RpcOk (Client crw defaultEncoder defaultDecoder)\n sendInitOp <- opSendInitialMetadata (metadataToSend co)\n res <- callBatch crw [ OpX sendInitOp ]\n\n case res of\n RpcOk _ -> return client\n RpcError _ -> do\n clientCloseCall crw\n stat <- clientWaitForStatus crw\n case stat of\n RpcOk (RpcStatus _ code msg) -> return (RpcError (StatusError code msg))\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 let client = Client crw defaultEncoder defaultDecoder\n sendInitOp <- opSendInitialMetadata (metadataToSend co)\n res <- callBatch crw [ OpX sendInitOp ]\n\n case res of\n RpcOk _ -> return (RpcOk client)\n RpcError _ -> do\n clientCloseCall crw\n stat <- clientWaitForStatus crw\n case stat of\n RpcOk (RpcStatus _ code msg) -> return (RpcError (StatusError code msg))\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.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 <- 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 BB.byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr BB.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 <- BB.toLazyByteString bb\n BB.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\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n statusSlice <- BB.mallocSlice\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 C.withForeignPtr statusSlice $ \\statusSlice' -> {#set grpc_op->data.recv_status_on_client.status_details#} p statusSlice'\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- BB.toByteString statusSlice\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.finalizeForeignPtr statusSlice\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 = do\n prev <- tryReadMVar (statusFromServer crw)\n case prev of\n Just stat -> do\n return (RpcOk stat)\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX statusOp ]\n case res of\n RpcOk _ -> do\n status <- opRead statusOp\n return (RpcOk status)\n RpcError err ->\n return (RpcError err)\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 crw@ClientReaderWriter{..} = do\n _ <- clientWaitForStatus crw\n modifyMVar_ callMVar_ $ \\call -> do\n grpcCallUnref call\n return (error \"grpcCallUnref 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\nbranchOnClientStatus :: Client req resp\n -> Rpc a\n -> Rpc a\n -> (StatusCode -> B.ByteString -> Rpc a)\n -> Rpc a\nbranchOnClientStatus 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 branchOnClientStatus\n client\n (return ())\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\ninitialMetadata :: Client req resp -> Rpc [Metadata]\ninitialMetadata client = do\n joinClientRWOp client clientWaitForInitialMetadata\n\nwaitForStatus :: Client req resp -> Rpc RpcStatus\nwaitForStatus client = do\n _ <- clientRWOp client clientWaitForInitialMetadata\n joinClientRWOp client clientWaitForStatus\n\nreceiveMessage :: Client req resp -> Rpc (Maybe resp)\nreceiveMessage client = do\n throwIfErrorStatus client\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\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 status <- waitForStatus client\n clientRWOp client clientCloseCall\n case status of\n RpcStatus _ StatusOk _ -> return ()\n RpcStatus _ code detail -> throwE (StatusError code detail)\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 = do\n _ <- clientRWOp client clientCancelCall\n return ()\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 joinClientRWOp client (\\crw -> clientCancelCallWithStatus crw status details)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n 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":"9a9024c41afdf787bb5c8a1bffeb37d9370583e8","subject":"Added webDataSourceGetData","message":"Added webDataSourceGetData\n\nThis requires a version of glib with GString patch applied.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content.The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\nwebDataSourceGetData :: WebDataSourceClass self => self\n -> IO (Maybe String)\nwebDataSourceGetData ds = do\n gstr <- {#call webkit_web_data_source_get_data #}\n (toWebDataSource ds)\n readGString gstr\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n -- webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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 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-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content.The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\n-- \n-- webDataSourceGetData :: WebDataSourceClass self => self\n-- -> IO (Maybe String)\n-- webDataSourceGetData ds = do\n-- ptr <- {#call webkit_web_data_source_get_data #}\n-- (toWebDataSource ds)\n-- if strPtr == nullPtr\n-- then return Nothing\n-- else liftM Just $ peekCStringLen (strPtr, strLen)\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7fd6845d60af418a2888702f3b42bda6afd69442","subject":"add the Dijkstra's algorithm","message":"add the Dijkstra's algorithm\n","repos":"kaizhang\/haskell-igraph,kaizhang\/haskell-igraph,kaizhang\/haskell-igraph","old_file":"src\/IGraph\/Algorithms\/Structure.chs","new_file":"src\/IGraph\/Algorithms\/Structure.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE DataKinds #-}\nmodule IGraph.Algorithms.Structure\n ( -- * Shortest Path Related Functions\n shortestPath\n , inducedSubgraph\n , isConnected\n , isStronglyConnected\n , decompose\n , isDag\n , topSort\n , topSortUnsafe\n ) where\n\nimport Control.Monad\nimport Data.Serialize (Serialize)\nimport Data.List (foldl')\nimport System.IO.Unsafe (unsafePerformIO)\nimport Data.Maybe\nimport Data.Singletons (SingI)\n\nimport Foreign\nimport Foreign.C.Types\n\nimport IGraph\nimport IGraph.Internal.C2HS\n{#import IGraph.Internal #}\n{#import IGraph.Internal.Constants #}\n\n#include \"haskell_igraph.h\"\n\n{#fun igraph_shortest_paths as ^\n { `IGraph'\n , castPtr `Ptr Matrix'\n , castPtr %`Ptr VertexSelector'\n , castPtr %`Ptr VertexSelector'\n , `Neimode'\n } -> `CInt' void- #}\n\n-- Calculates and returns a single unweighted shortest path from a given vertex\n-- to another one. If there are more than one shortest paths between the two\n-- vertices, then an arbitrary one is returned.\nshortestPath :: Serialize e\n => Graph d v e\n -> Node -- ^ The id of the source vertex.\n -> Node -- ^ The id of the target vertex.\n -> Maybe (e -> Double) -- ^ A function to retrieve edge weights. If provied,\n -- the Dijkstra's algorithm will be used.\n -> [Node]\nshortestPath gr s t getEdgeW = unsafePerformIO $ allocaVector $ \\path -> do\n case getEdgeW of\n Nothing -> igraphGetShortestPath (_graph gr) path nullPtr s t IgraphOut\n Just f -> withList (map (f . snd) $ labEdges gr) $ \\ws ->\n igraphGetShortestPathDijkstra (_graph gr) path nullPtr s t ws IgraphOut\n map truncate <$> toList path\n{#fun igraph_get_shortest_path as ^\n { `IGraph'\n , castPtr `Ptr Vector'\n , castPtr `Ptr Vector'\n , `Int'\n , `Int'\n , `Neimode'\n } -> `CInt' void- #}\n{#fun igraph_get_shortest_path_dijkstra as ^\n { `IGraph'\n , castPtr `Ptr Vector'\n , castPtr `Ptr Vector'\n , `Int'\n , `Int'\n , castPtr `Ptr Vector'\n , `Neimode'\n } -> `CInt' void- #}\n\ninducedSubgraph :: (Ord v, Serialize v)\n => Graph d v e\n -> [Int]\n -> Graph d v e\ninducedSubgraph gr nds = unsafePerformIO $ withVerticesList nds $ \\vs ->\n igraphInducedSubgraph (_graph gr) vs IgraphSubgraphCreateFromScratch >>=\n (\\g -> return $ Graph g $ mkLabelToId g)\n{#fun igraph_induced_subgraph as ^\n { `IGraph'\n , allocaIGraph- `IGraph' addIGraphFinalizer*\n , castPtr %`Ptr VertexSelector'\n , `SubgraphImplementation'\n } -> `CInt' void- #}\n\n-- | Decides whether the graph is weakly connected.\nisConnected :: Graph d v e -> Bool\nisConnected gr = igraphIsConnected (_graph gr) IgraphWeak\n\nisStronglyConnected :: Graph 'D v e -> Bool\nisStronglyConnected gr = igraphIsConnected (_graph gr) IgraphStrong\n\n{#fun pure igraph_is_connected as ^\n { `IGraph'\n , alloca- `Bool' peekBool*\n , `Connectedness'\n } -> `CInt' void- #}\n\n-- | Decompose a graph into connected components.\ndecompose :: (Ord v, Serialize v)\n => Graph d v e -> [Graph d v e]\ndecompose gr = unsafePerformIO $ allocaVectorPtr $ \\ptr -> do\n igraphDecompose (_graph gr) ptr IgraphWeak (-1) 1\n n <- igraphVectorPtrSize ptr\n forM [0..n-1] $ \\i -> do\n p <- igraphVectorPtrE ptr i\n addIGraphFinalizer (castPtr p) >>= (\\g -> return $ Graph g $ mkLabelToId g)\n{-# INLINE decompose #-}\n{#fun igraph_decompose as ^\n { `IGraph'\n , castPtr `Ptr VectorPtr'\n , `Connectedness'\n , `Int'\n , `Int'\n } -> `CInt' void- #}\n\n\n-- | Checks whether a graph is a directed acyclic graph (DAG) or not.\nisDag :: Graph d v e -> Bool\nisDag = igraphIsDag . _graph\n{#fun pure igraph_is_dag as ^\n { `IGraph'\n , alloca- `Bool' peekBool*\n } -> `CInt' void- #}\n\n-- | Calculate a possible topological sorting of the graph.\ntopSort :: Graph d v e -> [Node]\ntopSort gr | isDag gr = topSortUnsafe gr\n | otherwise = error \"the graph is not acyclic\"\n\n-- | Calculate a possible topological sorting of the graph. If the graph is not\n-- acyclic (it has at least one cycle), a partial topological sort is returned.\ntopSortUnsafe :: Graph d v e -> [Node]\ntopSortUnsafe gr = unsafePerformIO $ allocaVectorN n $ \\res -> do\n igraphTopologicalSorting (_graph gr) res IgraphOut\n map truncate <$> toList res\n where\n n = nNodes gr\n{#fun igraph_topological_sorting as ^\n { `IGraph'\n , castPtr `Ptr Vector'\n , `Neimode'\n } -> `CInt' void- #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE DataKinds #-}\nmodule IGraph.Algorithms.Structure\n ( -- * Shortest Path Related Functions\n getShortestPath\n , inducedSubgraph\n , isConnected\n , isStronglyConnected\n , decompose\n , isDag\n , topSort\n , topSortUnsafe\n ) where\n\nimport Control.Monad\nimport Data.Serialize (Serialize)\nimport Data.List (foldl')\nimport System.IO.Unsafe (unsafePerformIO)\nimport Data.Maybe\nimport Data.Singletons (SingI)\n\nimport Foreign\nimport Foreign.C.Types\n\nimport IGraph\nimport IGraph.Internal.C2HS\n{#import IGraph.Internal #}\n{#import IGraph.Internal.Constants #}\n\n#include \"haskell_igraph.h\"\n\n{#fun igraph_shortest_paths as ^\n { `IGraph'\n , castPtr `Ptr Matrix'\n , castPtr %`Ptr VertexSelector'\n , castPtr %`Ptr VertexSelector'\n , `Neimode'\n } -> `CInt' void- #}\n\n-- Calculates and returns a single unweighted shortest path from a given vertex\n-- to another one. If there are more than one shortest paths between the two\n-- vertices, then an arbitrary one is returned.\ngetShortestPath :: Graph d v e\n -> Node -- ^ The id of the source vertex.\n -> Node -- ^ The id of the target vertex.\n -> [Node]\ngetShortestPath gr s t = unsafePerformIO $ allocaVector $ \\path -> do\n igraphGetShortestPath (_graph gr) path nullPtr s t IgraphOut\n map truncate <$> toList path\n{#fun igraph_get_shortest_path as ^\n { `IGraph'\n , castPtr `Ptr Vector'\n , castPtr `Ptr Vector'\n , `Int'\n , `Int'\n , `Neimode'\n } -> `CInt' void- #}\n\ninducedSubgraph :: (Ord v, Serialize v)\n => Graph d v e\n -> [Int]\n -> Graph d v e\ninducedSubgraph gr nds = unsafePerformIO $ withVerticesList nds $ \\vs ->\n igraphInducedSubgraph (_graph gr) vs IgraphSubgraphCreateFromScratch >>=\n (\\g -> return $ Graph g $ mkLabelToId g)\n{#fun igraph_induced_subgraph as ^\n { `IGraph'\n , allocaIGraph- `IGraph' addIGraphFinalizer*\n , castPtr %`Ptr VertexSelector'\n , `SubgraphImplementation'\n } -> `CInt' void- #}\n\n-- | Decides whether the graph is weakly connected.\nisConnected :: Graph d v e -> Bool\nisConnected gr = igraphIsConnected (_graph gr) IgraphWeak\n\nisStronglyConnected :: Graph 'D v e -> Bool\nisStronglyConnected gr = igraphIsConnected (_graph gr) IgraphStrong\n\n{#fun pure igraph_is_connected as ^\n { `IGraph'\n , alloca- `Bool' peekBool*\n , `Connectedness'\n } -> `CInt' void- #}\n\n-- | Decompose a graph into connected components.\ndecompose :: (Ord v, Serialize v)\n => Graph d v e -> [Graph d v e]\ndecompose gr = unsafePerformIO $ allocaVectorPtr $ \\ptr -> do\n igraphDecompose (_graph gr) ptr IgraphWeak (-1) 1\n n <- igraphVectorPtrSize ptr\n forM [0..n-1] $ \\i -> do\n p <- igraphVectorPtrE ptr i\n addIGraphFinalizer (castPtr p) >>= (\\g -> return $ Graph g $ mkLabelToId g)\n{-# INLINE decompose #-}\n{#fun igraph_decompose as ^\n { `IGraph'\n , castPtr `Ptr VectorPtr'\n , `Connectedness'\n , `Int'\n , `Int'\n } -> `CInt' void- #}\n\n\n-- | Checks whether a graph is a directed acyclic graph (DAG) or not.\nisDag :: Graph d v e -> Bool\nisDag = igraphIsDag . _graph\n{#fun pure igraph_is_dag as ^\n { `IGraph'\n , alloca- `Bool' peekBool*\n } -> `CInt' void- #}\n\n-- | Calculate a possible topological sorting of the graph.\ntopSort :: Graph d v e -> [Node]\ntopSort gr | isDag gr = topSortUnsafe gr\n | otherwise = error \"the graph is not acyclic\"\n\n-- | Calculate a possible topological sorting of the graph. If the graph is not\n-- acyclic (it has at least one cycle), a partial topological sort is returned.\ntopSortUnsafe :: Graph d v e -> [Node]\ntopSortUnsafe gr = unsafePerformIO $ allocaVectorN n $ \\res -> do\n igraphTopologicalSorting (_graph gr) res IgraphOut\n map truncate <$> toList res\n where\n n = nNodes gr\n{#fun igraph_topological_sorting as ^\n { `IGraph'\n , castPtr `Ptr Vector'\n , `Neimode'\n } -> `CInt' void- #}\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"4fc7f5633f26ca8d3bf1808aace84fb4918bf775","subject":"Remove unnecessary OverlappingInstances pragma.","message":"Remove unnecessary OverlappingInstances pragma.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Spinner.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Spinner.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Spinner\n (\n -- * Constructor\n spinnerNew,\n SpinnerType(..)\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $Spinnerfunctions\n --\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_SpinnerC.h\"\n#include \"Fl_WidgetC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\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\nimport Graphics.UI.FLTK.LowLevel.Dispatch\n#c\nenum SpinnerType {\n IntSpinnerType = FL_INT_INPUTC,\n FloatSpinnerType = FL_FLOAT_INPUTC\n};\n#endc\n{#enum SpinnerType {} deriving (Show, Eq) #}\n{# fun Fl_Spinner_New as spinnerNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Spinner_New_WithLabel as spinnerNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\nspinnerNew :: Rectangle -> Maybe String -> IO (Ref Spinner)\nspinnerNew rectangle l'=\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case l' of\n Nothing -> spinnerNew' x_pos y_pos width height >>=\n toRef\n Just l -> spinnerNewWithLabel' x_pos y_pos width height l >>=\n toRef\n\n{#fun Fl_Spinner_handle as spinnerHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO Int)) => Op (Handle ()) Spinner orig impl where\n runOp _ _ spinner event = withRef spinner (\\p -> spinnerHandle' p (fromIntegral . fromEnum $ event))\n{# fun Fl_Spinner_set_textfont as setTextfont' { id `Ptr ()',cFromFont `Font' } -> `()' #}\ninstance (impl ~ (Font -> IO ())) => Op (SetTextfont ()) Spinner orig impl where\n runOp _ _ spinner text = withRef spinner $ \\spinnerPtr -> setTextfont' spinnerPtr text\n{# fun Fl_Spinner_textfont as textfont' { id `Ptr ()' } -> `Font' cToFont #}\ninstance (impl ~ ( IO (Font))) => Op (GetTextfont ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> textfont' spinnerPtr\n{# fun Fl_Spinner_set_textsize as setTextsize' { id `Ptr ()', id `CInt' } -> `()' #}\ninstance (impl ~ (FontSize -> IO ())) => Op (SetTextsize ()) Spinner orig impl where\n runOp _ _ spinner (FontSize text) = withRef spinner $ \\spinnerPtr -> setTextsize' spinnerPtr text\n{# fun Fl_Spinner_textsize as textsize' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ ( IO (FontSize))) => Op (GetTextsize ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> textsize' spinnerPtr >>= return . FontSize\n{# fun Fl_Spinner_set_textcolor as setTextcolor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ninstance (impl ~ (Color -> IO ())) => Op (SetTextcolor ()) Spinner orig impl where\n runOp _ _ spinner text = withRef spinner $ \\spinnerPtr -> setTextcolor' spinnerPtr text\n{# fun Fl_Spinner_textcolor as textcolor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ ( IO (Color))) => Op (GetTextcolor ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> textcolor' spinnerPtr\n{# fun Fl_Spinner_set_type as setType' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (SpinnerType -> IO ())) => Op (SetType ()) Spinner orig impl where\n runOp _ _ widget t = withRef widget $ \\widgetPtr -> setType' widgetPtr (fromInteger $ toInteger $ fromEnum t)\n{# fun Fl_Spinner_type as type' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ IO (SpinnerType)) => Op (GetType_ ()) Spinner orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr >>= return . toEnum . fromInteger . toInteger\n{# fun Fl_Spinner_set_format as set_format' { id `Ptr ()', `String' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (String -> IO ())) => Op (SetFormat ()) Spinner orig impl where\n runOp _ _ spinner f = withRef spinner $ \\spinnerPtr -> set_format' spinnerPtr f\n{# fun Fl_Spinner_format as format' { id `Ptr ()' } -> `String' unsafeFromCString #}\ninstance (impl ~ ( IO (Maybe String))) => Op (GetFormat ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> format' spinnerPtr >>= \\s ->\n if (null s) then return Nothing else return (Just s)\n{# fun Fl_Spinner_value as value' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetValue ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> value' spinnerPtr\n{# fun Fl_Spinner_set_value as setValue' { id `Ptr ()',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetValue ()) Spinner orig impl where\n runOp _ _ spinner v = withRef spinner $ \\spinnerPtr -> setValue' spinnerPtr v\n{# fun Fl_Spinner_set_step as setStep' { id `Ptr ()', `Double'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetStep ()) Spinner orig impl where\n runOp _ _ spinner r = withRef spinner $ \\spinnerPtr -> setStep' spinnerPtr r\n{# fun Fl_Spinner_step as step' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetStep ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> step' spinnerPtr\n{# fun Fl_Spinner_maximum as maximum' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetMaximum ()) Spinner orig impl where\n runOp _ _ valuator = withRef valuator $ \\valuatorPtr -> maximum' valuatorPtr\n{# fun Fl_Spinner_set_maximum as setMaximum' { id `Ptr ()',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetMaximum ()) Spinner orig impl where\n runOp _ _ valuator a = withRef valuator $ \\valuatorPtr -> setMaximum' valuatorPtr a\n{# fun Fl_Spinner_minimum as minimum' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetMinimum ()) Spinner orig impl where\n runOp _ _ valuator = withRef valuator $ \\valuatorPtr -> minimum' valuatorPtr\n{# fun Fl_Spinner_set_minimum as setMinimum' { id `Ptr ()',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetMinimum ()) Spinner orig impl where\n runOp _ _ valuator a = withRef valuator $ \\valuatorPtr -> setMinimum' valuatorPtr a\n{# fun Fl_Spinner_range as range' { id `Ptr ()',`Double',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> Double -> IO ())) => Op (Range ()) Spinner orig impl where\n runOp _ _ valuator a b = withRef valuator $ \\valuatorPtr -> range' valuatorPtr a b\n\n-- $hierarchy\n-- @\n--\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Spinner\"\n--\n-- @\n\n-- $functions\n-- @\n-- getFormat :: 'Ref' 'Spinner' -> 'IO' ('Maybe' 'String')\n--\n-- getMaximum :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- getMinimum :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- getStep :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- getTextcolor :: 'Ref' 'Spinner' -> 'IO' ('Color')\n--\n-- getTextfont :: 'Ref' 'Spinner' -> 'IO' ('Font')\n--\n-- getTextsize :: 'Ref' 'Spinner' -> 'IO' ('FontSize')\n--\n-- getType_ :: 'Ref' 'Spinner' -> 'IO' ('SpinnerType')\n--\n-- getValue :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- handle :: 'Ref' 'Spinner' -> 'Event' -> 'IO' 'Int'\n--\n-- range :: 'Ref' 'Spinner' -> 'Double' -> 'Double' -> 'IO' ()\n--\n-- setFormat :: 'Ref' 'Spinner' -> 'String' -> 'IO' ()\n--\n-- setMaximum :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- setMinimum :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- setStep :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- setTextcolor :: 'Ref' 'Spinner' -> 'Color' -> 'IO' ()\n--\n-- setTextfont :: 'Ref' 'Spinner' -> 'Font' -> 'IO' ()\n--\n-- setTextsize :: 'Ref' 'Spinner' -> 'FontSize' -> 'IO' ()\n--\n-- setType :: 'Ref' 'Spinner' -> 'SpinnerType' -> 'IO' ()\n--\n-- setValue :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- @\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables, OverlappingInstances #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Spinner\n (\n -- * Constructor\n spinnerNew,\n SpinnerType(..)\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $Spinnerfunctions\n --\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_SpinnerC.h\"\n#include \"Fl_WidgetC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\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\nimport Graphics.UI.FLTK.LowLevel.Dispatch\n#c\nenum SpinnerType {\n IntSpinnerType = FL_INT_INPUTC,\n FloatSpinnerType = FL_FLOAT_INPUTC\n};\n#endc\n{#enum SpinnerType {} deriving (Show, Eq) #}\n{# fun Fl_Spinner_New as spinnerNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Spinner_New_WithLabel as spinnerNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String'} -> `Ptr ()' id #}\nspinnerNew :: Rectangle -> Maybe String -> IO (Ref Spinner)\nspinnerNew rectangle l'=\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case l' of\n Nothing -> spinnerNew' x_pos y_pos width height >>=\n toRef\n Just l -> spinnerNewWithLabel' x_pos y_pos width height l >>=\n toRef\n\n{#fun Fl_Spinner_handle as spinnerHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO Int)) => Op (Handle ()) Spinner orig impl where\n runOp _ _ spinner event = withRef spinner (\\p -> spinnerHandle' p (fromIntegral . fromEnum $ event))\n{# fun Fl_Spinner_set_textfont as setTextfont' { id `Ptr ()',cFromFont `Font' } -> `()' #}\ninstance (impl ~ (Font -> IO ())) => Op (SetTextfont ()) Spinner orig impl where\n runOp _ _ spinner text = withRef spinner $ \\spinnerPtr -> setTextfont' spinnerPtr text\n{# fun Fl_Spinner_textfont as textfont' { id `Ptr ()' } -> `Font' cToFont #}\ninstance (impl ~ ( IO (Font))) => Op (GetTextfont ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> textfont' spinnerPtr\n{# fun Fl_Spinner_set_textsize as setTextsize' { id `Ptr ()', id `CInt' } -> `()' #}\ninstance (impl ~ (FontSize -> IO ())) => Op (SetTextsize ()) Spinner orig impl where\n runOp _ _ spinner (FontSize text) = withRef spinner $ \\spinnerPtr -> setTextsize' spinnerPtr text\n{# fun Fl_Spinner_textsize as textsize' { id `Ptr ()' } -> `CInt' id #}\ninstance (impl ~ ( IO (FontSize))) => Op (GetTextsize ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> textsize' spinnerPtr >>= return . FontSize\n{# fun Fl_Spinner_set_textcolor as setTextcolor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ninstance (impl ~ (Color -> IO ())) => Op (SetTextcolor ()) Spinner orig impl where\n runOp _ _ spinner text = withRef spinner $ \\spinnerPtr -> setTextcolor' spinnerPtr text\n{# fun Fl_Spinner_textcolor as textcolor' { id `Ptr ()' } -> `Color' cToColor #}\ninstance (impl ~ ( IO (Color))) => Op (GetTextcolor ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> textcolor' spinnerPtr\n{# fun Fl_Spinner_set_type as setType' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (SpinnerType -> IO ())) => Op (SetType ()) Spinner orig impl where\n runOp _ _ widget t = withRef widget $ \\widgetPtr -> setType' widgetPtr (fromInteger $ toInteger $ fromEnum t)\n{# fun Fl_Spinner_type as type' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ IO (SpinnerType)) => Op (GetType_ ()) Spinner orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr >>= return . toEnum . fromInteger . toInteger\n{# fun Fl_Spinner_set_format as set_format' { id `Ptr ()', `String' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (String -> IO ())) => Op (SetFormat ()) Spinner orig impl where\n runOp _ _ spinner f = withRef spinner $ \\spinnerPtr -> set_format' spinnerPtr f\n{# fun Fl_Spinner_format as format' { id `Ptr ()' } -> `String' unsafeFromCString #}\ninstance (impl ~ ( IO (Maybe String))) => Op (GetFormat ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> format' spinnerPtr >>= \\s ->\n if (null s) then return Nothing else return (Just s)\n{# fun Fl_Spinner_value as value' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetValue ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> value' spinnerPtr\n{# fun Fl_Spinner_set_value as setValue' { id `Ptr ()',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetValue ()) Spinner orig impl where\n runOp _ _ spinner v = withRef spinner $ \\spinnerPtr -> setValue' spinnerPtr v\n{# fun Fl_Spinner_set_step as setStep' { id `Ptr ()', `Double'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetStep ()) Spinner orig impl where\n runOp _ _ spinner r = withRef spinner $ \\spinnerPtr -> setStep' spinnerPtr r\n{# fun Fl_Spinner_step as step' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetStep ()) Spinner orig impl where\n runOp _ _ spinner = withRef spinner $ \\spinnerPtr -> step' spinnerPtr\n{# fun Fl_Spinner_maximum as maximum' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetMaximum ()) Spinner orig impl where\n runOp _ _ valuator = withRef valuator $ \\valuatorPtr -> maximum' valuatorPtr\n{# fun Fl_Spinner_set_maximum as setMaximum' { id `Ptr ()',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetMaximum ()) Spinner orig impl where\n runOp _ _ valuator a = withRef valuator $ \\valuatorPtr -> setMaximum' valuatorPtr a\n{# fun Fl_Spinner_minimum as minimum' { id `Ptr ()' } -> `Double' #}\ninstance (impl ~ ( IO (Double))) => Op (GetMinimum ()) Spinner orig impl where\n runOp _ _ valuator = withRef valuator $ \\valuatorPtr -> minimum' valuatorPtr\n{# fun Fl_Spinner_set_minimum as setMinimum' { id `Ptr ()',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> IO ())) => Op (SetMinimum ()) Spinner orig impl where\n runOp _ _ valuator a = withRef valuator $ \\valuatorPtr -> setMinimum' valuatorPtr a\n{# fun Fl_Spinner_range as range' { id `Ptr ()',`Double',`Double' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Double -> Double -> IO ())) => Op (Range ()) Spinner orig impl where\n runOp _ _ valuator a b = withRef valuator $ \\valuatorPtr -> range' valuatorPtr a b\n\n-- $hierarchy\n-- @\n--\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Spinner\"\n--\n-- @\n\n-- $functions\n-- @\n-- getFormat :: 'Ref' 'Spinner' -> 'IO' ('Maybe' 'String')\n--\n-- getMaximum :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- getMinimum :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- getStep :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- getTextcolor :: 'Ref' 'Spinner' -> 'IO' ('Color')\n--\n-- getTextfont :: 'Ref' 'Spinner' -> 'IO' ('Font')\n--\n-- getTextsize :: 'Ref' 'Spinner' -> 'IO' ('FontSize')\n--\n-- getType_ :: 'Ref' 'Spinner' -> 'IO' ('SpinnerType')\n--\n-- getValue :: 'Ref' 'Spinner' -> 'IO' ('Double')\n--\n-- handle :: 'Ref' 'Spinner' -> 'Event' -> 'IO' 'Int'\n--\n-- range :: 'Ref' 'Spinner' -> 'Double' -> 'Double' -> 'IO' ()\n--\n-- setFormat :: 'Ref' 'Spinner' -> 'String' -> 'IO' ()\n--\n-- setMaximum :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- setMinimum :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- setStep :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- setTextcolor :: 'Ref' 'Spinner' -> 'Color' -> 'IO' ()\n--\n-- setTextfont :: 'Ref' 'Spinner' -> 'Font' -> 'IO' ()\n--\n-- setTextsize :: 'Ref' 'Spinner' -> 'FontSize' -> 'IO' ()\n--\n-- setType :: 'Ref' 'Spinner' -> 'SpinnerType' -> 'IO' ()\n--\n-- setValue :: 'Ref' 'Spinner' -> 'Double' -> 'IO' ()\n--\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"24eae2b5e65fa41aae95602bfc23419b9353d9d6","subject":"more documentation","message":"more documentation\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 getModulus,\n getPublicExponent,\n getDecryptFlag,\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_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\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\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\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 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_KEY_TYPE as KeyTypeType,\n CKA_LABEL as LabelType,\n CKA_MODULUS_BITS as ModulusBitsType,\n CKA_MODULUS as ModulusType,\n CKA_PUBLIC_EXPONENT as PublicExponentType,\n CKA_PRIVATE_EXPONENT as PrivateExponentType,\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 CKA_TOKEN as TokenType,\n CKA_DECRYPT as DecryptType\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 | 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\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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\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","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 getModulus,\n getPublicExponent,\n getDecryptFlag,\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_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\n\npeekInfo :: Ptr Info -> IO Info\npeekInfo ptr = peek ptr\n\n\ndata SlotInfo = SlotInfo {\n slotInfoDescription :: String,\n slotInfoManufacturerId :: String,\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\n\ndata TokenInfo = TokenInfo {\n tokenInfoLabel :: String,\n tokenInfoManufacturerId :: String,\n tokenInfoModel :: String,\n tokenInfoSerialNumber :: String,\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\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 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_KEY_TYPE as KeyTypeType,\n CKA_LABEL as LabelType,\n CKA_MODULUS_BITS as ModulusBitsType,\n CKA_MODULUS as ModulusType,\n CKA_PUBLIC_EXPONENT as PublicExponentType,\n CKA_PRIVATE_EXPONENT as PrivateExponentType,\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 CKA_TOKEN as TokenType,\n CKA_DECRYPT as DecryptType\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 | 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\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\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\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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\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\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-- | Retrieves mechanism info\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":"86af5e5567bb68b8411f89651b3020c1e670d484","subject":"haddock fix","message":"haddock fix\n","repos":"flowbox-public\/cufft","old_file":"Foreign\/CUDA\/FFT\/Plan.chs","new_file":"Foreign\/CUDA\/FFT\/Plan.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.FFT.Plan (\n\n -- * Context\n Handle(..),\n Type(..),\n plan1D,\n plan2D,\n plan3D,\n destroy,\n\n) where\n\n-- Friends\nimport Foreign.CUDA.FFT.Error\nimport Foreign.CUDA.FFT.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\n\n#include \n{# context lib=\"cufft\" #}\n\n\n-- | Operations handle\n--\nnewtype Handle = Handle { useHandle :: {# type cufftHandle #}}\n\n{# enum cufftType as Type\n {}\n with prefix=\"CUFFT\" deriving (Eq, Show) #}\n\n-- Context management ----------------------------------------------------------\n--\n\n-- | Creates a 1D FFT plan configuration for a specified signal size and data type.\n-- The third argument tells CUFFT how many 1D transforms to configure.\n--\nplan1D :: Int -> Type -> Int -> IO Handle\nplan1D nx t batch = resultIfOk =<< cufftPlan1d nx t batch\n\n{# fun unsafe cufftPlan1d\n { alloca- `Handle' peekHdl*\n , `Int'\n , cFromEnum `Type'\n , `Int' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 2D FFT plan configuration for a specified signal size and data type.\n--\nplan2D :: Int -> Int -> Type -> IO Handle\nplan2D nx ny t = resultIfOk =<< cufftPlan2d nx ny t\n\n{# fun unsafe cufftPlan2d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 3D FFT plan configuration for a specified signal size and data type.\n--\nplan3D :: Int -> Int -> Int -> Type -> IO Handle\nplan3D nx ny nz t = resultIfOk =<< cufftPlan3d nx ny nz t\n\n{# fun unsafe cufftPlan3d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | This function releases hardware resources used by the CUFFT plan. The\n-- release of GPU resources may be deferred until the application exits. This\n-- function is usually the last call with a particular handle to the CUFFT\n-- plan.\n--\ndestroy :: Handle -> IO ()\ndestroy ctx = nothingIfOk =<< cufftDestroy ctx\n\n{# fun unsafe cufftDestroy\n { useHandle `Handle' } -> `Result' cToEnum #}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.FFT.Plan (\n\n -- * Context\n Handle(..),\n Type(..),\n plan1D,\n plan2D,\n plan3D,\n destroy,\n\n) where\n\n-- Friends\nimport Foreign.CUDA.FFT.Error\nimport Foreign.CUDA.FFT.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\n\n#include \n{# context lib=\"cufft\" #}\n\n\n-- | Operations handle\n--\nnewtype Handle = Handle { useHandle :: {# type cufftHandle #}}\n\n{# enum cufftType as Type\n {}\n with prefix=\"CUFFT\" deriving (Eq, Show) #}\n\n-- Context management ----------------------------------------------------------\n--\n\n-- | Creates a 1D FFT plan configuration for a specified signal size and data type.\n-- The third argument tells CUFFT how many 1D transforms to configure.\n--\nplan1D :: Int -> Type -> Int -> IO Handle\nplan1D nx t batch = resultIfOk =<< cufftPlan1d nx t batch\n\n{# fun unsafe cufftPlan1d\n { alloca- `Handle' peekHdl*\n , `Int'\n , cFromEnum `Type'\n , `Int' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 2D FFT plan configuration for a specified signal size and data type.\n--\nplan2D :: Int -> Int -> Type -> IO Handle\nplan2D nx ny t = resultIfOk =<< cufftPlan2d nx ny t\n\n{# fun unsafe cufftPlan2d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n -- | Creates a 3D FFT plan configuration for a specified signal size and data type.\n--\nplan3D :: Int -> Int -> Int -> Type -> IO Handle\nplan3D nx ny nz t = resultIfOk =<< cufftPlan3d nx ny nz t\n\n{# fun unsafe cufftPlan3d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | This function releases hardware resources used by the CUFFT plan. The\n-- release of GPU resources may be deferred until the application exits. This\n-- function is usually the last call with a particular handle to the CUFFT\n-- plan.\n--\ndestroy :: Handle -> IO ()\ndestroy ctx = nothingIfOk =<< cufftDestroy ctx\n\n{# fun unsafe cufftDestroy\n { useHandle `Handle' } -> `Result' cToEnum #}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"72e18bd3f78b87d7815035409e48ebbb5f9f8d4d","subject":"[project @ 2002-07-17 15:59:19 by juhp] (treeViewColumnNewWithAttributes): Haskell implementation to avoid binding to original variad function. (treeViewColumnAddAttributes): New convenience function. (treeViewColumnSetAttributes): Haskell implementation to avoid binding to original variad function. (treeViewColumnClearAttributes): Add binding.","message":"[project @ 2002-07-17 15:59:19 by juhp]\n(treeViewColumnNewWithAttributes): Haskell implementation to\navoid binding to original variad function.\n(treeViewColumnAddAttributes): New convenience function.\n(treeViewColumnSetAttributes): Haskell implementation to\navoid binding to original variad function.\n(treeViewColumnClearAttributes): Add binding.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gtk\/treeList\/TreeViewColumn.chs","new_file":"gtk\/treeList\/TreeViewColumn.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget TreeViewColumn@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 May 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 15:59:19 $\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--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * tree_view_column_new_with_attributes and tree_view_column_set_attributes \n-- are variadic and the funcitonality can be achieved through other \n-- functions.\n--\n-- * tree_view_column_set_cell_data and tree_view_column_cell_get_size are not\n-- bound because I am not sure what they do and when they are useful\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * treeViewColumnSetCellData is not bound. With this function the user has\n-- control over how data in the store is mapped to the attributes of a\n-- cell renderer. This functin should be bound in the future to allow the\n-- user to insert Haskell data types into the store and convert these\n-- values to attributes of cell renderers.\n--\nmodule TreeViewColumn(\n TreeViewColumn,\n TreeViewColumnClass,\n castToTreeViewColumn,\n treeViewColumnNew,\n treeViewColumnNewWithAttributes,\n treeViewColumnPackStart,\n treeViewColumnPackEnd,\n treeViewColumnClear,\n treeViewColumnGetCellRenderers,\n treeViewColumnAddAttribute,\n treeViewColumnAddAttributes,\n treeViewColumnSetAttributes,\n treeViewColumnClearAttributes,\n treeViewColumnSetSpacing,\n treeViewColumnGetSpacing,\n treeViewColumnSetVisible,\n treeViewColumnGetVisible,\n treeViewColumnSetResizable,\n treeViewColumnGetResizable,\n TreeViewColumnSizing(..),\n treeViewColumnSetSizing,\n treeViewColumnGetSizing,\n treeViewColumnGetWidth,\n treeViewColumnSetFixedWidth,\n treeViewColumnSetMinWidth,\n treeViewColumnGetMinWidth,\n treeViewColumnSetMaxWidth,\n treeViewColumnGetMaxWidth,\n treeViewColumnClicked,\n treeViewColumnSetTitle,\n treeViewColumnGetTitle,\n treeViewColumnSetClickable,\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 onColClicked,\n afterColClicked\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(TreeViewColumnSizing(..), SortType(..))\n{#import TreeModel#}\nimport CellRenderer (Attribute(..))\n{#import GList#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- TreeViewColumn type declaration\n\n-- methods\n\n-- @constructor treeViewColumnNew@ Generate a new TreeViewColumn widget.\n--\ntreeViewColumnNew :: IO TreeViewColumn\ntreeViewColumnNew = makeNewObject mkTreeViewColumn \n {#call tree_view_column_new#}\n\n-- @method treeViewColumnNewWithAttributes@ Returns a new TreeViewColumn with\n-- title @ref arg title@, cell renderer @ref arg cr@, and attributes\n-- @ref arg attribs@.\n--\ntreeViewColumnNewWithAttributes :: CellRendererClass cr => String -> cr -> \n\t\t\t\t [(String, Int)] -> IO TreeViewColumn\ntreeViewColumnNewWithAttributes title cr attribs =\n do\n tvc <- treeViewColumnNew\n treeViewColumnSetTitle tvc title\n treeViewColumnPackStart tvc cr True\n treeViewColumnAddAttributes tvc cr attribs\n return tvc\n\n-- @method treeViewColumnPackStart@ Add a cell renderer at the beginning of\n-- a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackStart :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackStart tvc cr expand = \n {#call unsafe tree_view_column_pack_start#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnPackEnd@ Add a cell renderer at the end of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackEnd :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackEnd tvc cr expand = \n {#call unsafe tree_view_column_pack_end#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnClear@ Remove the associations of attributes\n-- to a store for all @ref type CellRenderers@.\n--\ntreeViewColumnClear :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClear tvc = \n {#call tree_view_column_clear#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetCellRenderers@ Retrieve all \n-- @ref type CellRenderer@s that are contained in this column.\n--\ntreeViewColumnGetCellRenderers :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> IO [CellRenderer]\ntreeViewColumnGetCellRenderers tvc = do\n glist <- {#call unsafe tree_view_column_get_cell_renderers#} \n\t (toTreeViewColumn tvc)\n crs <- fromGList glist\n mapM (makeNewObject mkCellRenderer) (map return crs)\n\n-- @method treeViewColumnAddAttribute@ Insert an attribute to change the\n-- behaviour of the column's cell renderer.\n--\n-- * The @ref type CellRenderer@ @ref arg cr@ must already be in \n-- @ref type TreeViewColumn@.\n--\ntreeViewColumnAddAttribute :: (TreeViewColumnClass tvc, CellRendererClass cr)\n\t\t\t => tvc -> cr -> String -> Int -> IO ()\ntreeViewColumnAddAttribute tvc cr attr col = \n withCString attr $ \\cstr -> {#call unsafe tree_view_column_add_attribute#} \n (toTreeViewColumn tvc) (toCellRenderer cr) cstr (fromIntegral col)\n\n-- @method treeViewColumnAddAttributes@ Insert attributes @ref arg attribs@\n-- to change the behaviour of column @ref arg tvc@'s cell renderer\n-- @ref arg cr@.\n--\ntreeViewColumnAddAttributes :: \n (TreeViewColumnClass tvc, CellRendererClass cr) => \n tvc -> cr -> [(String,Int)] -> IO ()\ntreeViewColumnAddAttributes tvc cr attribs = \n mapM_ (\\ (attr, col) -> treeViewColumnAddAttribute tvc cr attr col) attribs\n\n-- @method treeViewColumnSetAttributes@ Set the attributes of\n-- the cell renderer @ref arg cr@ in the tree column @ref arg tvc@\n-- be @red arg attribs@.\n-- The attributes are given as a list of attribute\/column pairs.\n-- All existing attributes are removed, and replaced with the new attributes.\n--\ntreeViewColumnSetAttributes :: \n (TreeViewColumnClass tvc, CellRendererClass cr) =>\n tvc -> cr -> [(String, Int)] -> IO ()\ntreeViewColumnSetAttributes tvc cr attribs =\n do\n treeViewColumnClearAttributes tvc cr\n treeViewColumnAddAttributes tvc cr attribs\n\n-- @method treeViewColumnClearAttributes@ Clears all existing attributes\n-- of the column @ref arg tvc@.\n--\ntreeViewColumnClearAttributes :: \n (TreeViewColumnClass tvc, CellRendererClass cr) =>\n tvc -> cr -> IO ()\ntreeViewColumnClearAttributes tvc cr =\n {#call tree_view_column_clear_attributes#} (toTreeViewColumn tvc)\n (toCellRenderer cr)\n\n\n-- @method treeViewColumnSetSpacing@ Set the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnSetSpacing :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetSpacing tvc vis =\n {#call tree_view_column_set_spacing#} (toTreeViewColumn tvc) \n (fromIntegral vis)\n\n\n-- @method treeViewColumnGetSpacing@ Get the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnGetSpacing :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSpacing tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_spacing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetVisible@ Set the visibility of a given column.\n--\ntreeViewColumnSetVisible :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetVisible tvc vis =\n {#call tree_view_column_set_visible#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetVisible@ Get the visibility of a given column.\n--\ntreeViewColumnGetVisible :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetVisible tvc = liftM toBool $\n {#call unsafe tree_view_column_get_visible#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetResizable@ Set if a given column is resizable\n-- by the user.\n--\ntreeViewColumnSetResizable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetResizable tvc vis =\n {#call tree_view_column_set_resizable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetResizable@ Get if a given column is resizable\n-- by the user.\n--\ntreeViewColumnGetResizable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetResizable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_resizable#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetSizing@ Set wether the column can be resized.\n--\ntreeViewColumnSetSizing :: TreeViewColumnClass tvc => tvc ->\n TreeViewColumnSizing -> IO ()\ntreeViewColumnSetSizing tvc size = {#call tree_view_column_set_sizing#} \n (toTreeViewColumn tvc) ((fromIntegral.fromEnum) size)\n\n\n-- @method treeViewColumnGetSizing@ Return the resizing type of the column.\n--\ntreeViewColumnGetSizing :: TreeViewColumnClass tvc => tvc ->\n IO TreeViewColumnSizing\ntreeViewColumnGetSizing tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sizing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnGetWidth@ Query the current width of the column.\n--\ntreeViewColumnGetWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_width#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetFixedWidth@ Set the width of the column.\n--\n-- * This is meaningful only if the sizing type is\n-- @ref type TreeViewColumnFixed@.\n--\ntreeViewColumnSetFixedWidth :: TreeViewColumnClass tvc => Int -> tvc -> IO ()\ntreeViewColumnSetFixedWidth width tvc = \n {#call tree_view_column_set_fixed_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n\n-- @method treeViewColumnSetMinWidth@ Set minimum width of the column.\n--\ntreeViewColumnSetMinWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMinWidth tvc width = {#call tree_view_column_set_min_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMinWidth@ Get the minimum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMinWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMinWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_min_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetMaxWidth@ Set maximum width of the column.\n--\ntreeViewColumnSetMaxWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMaxWidth tvc width = {#call tree_view_column_set_max_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMaxWidth@ Get the maximum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMaxWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMaxWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_max_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnClicked@ Emit the @ref arg clicked@ signal on the\n-- column.\n--\ntreeViewColumnClicked :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClicked tvc =\n {#call tree_view_column_clicked#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetTitle@ Set the widget's title if a custom widget\n-- has not been set.\n--\ntreeViewColumnSetTitle :: TreeViewColumnClass tvc => tvc -> String -> IO ()\ntreeViewColumnSetTitle tvc title = withCString title $\n {#call tree_view_column_set_title#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetTitle@ Get the widget's title.\n--\ntreeViewColumnGetTitle :: TreeViewColumnClass tvc => tvc -> IO (Maybe String)\ntreeViewColumnGetTitle tvc = do\n strPtr <- {#call unsafe tree_view_column_get_title#} (toTreeViewColumn tvc)\n if strPtr==nullPtr then return Nothing else liftM Just $ peekCString strPtr\n\n-- @method treeViewColumnSetClickable@ Set if the column should be sensitive\n-- to mouse clicks.\n--\ntreeViewColumnSetClickable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetClickable tvc click = {#call tree_view_column_set_clickable#} \n (toTreeViewColumn tvc) (fromBool click)\n\n-- @method treeViewColumnSetWidget@ Set the column's title to this widget.\n--\ntreeViewColumnSetWidget :: (TreeViewColumnClass tvc, WidgetClass w) => tvc ->\n w -> IO ()\ntreeViewColumnSetWidget tvc w =\n {#call tree_view_column_set_widget#} (toTreeViewColumn tvc) (toWidget w)\n\n-- @method treeViewColumnGetWidget@ Retrieve the widget responsible for\n-- showing the column title. In case only a text title was set this will be a\n-- @ref arg Alignment@ widget with a @ref arg Label@ inside.\n--\ntreeViewColumnGetWidget :: TreeViewColumnClass tvc => tvc -> IO Widget\ntreeViewColumnGetWidget tvc = makeNewObject mkWidget $\n {#call unsafe tree_view_column_get_widget#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetAlignment@ Set the alignment of the title.\n--\ntreeViewColumnSetAlignment :: TreeViewColumnClass tvc => tvc -> Float -> IO ()\ntreeViewColumnSetAlignment tvc align = {#call tree_view_column_set_alignment#}\n (toTreeViewColumn tvc) (realToFrac align)\n\n-- @method treeViewColumnGetAlignment@ Get the alignment of the titlte.\n--\ntreeViewColumnGetAlignment :: TreeViewColumnClass tvc => tvc -> IO Float\ntreeViewColumnGetAlignment tvc = liftM realToFrac $\n {#call unsafe tree_view_column_get_alignment#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetReorderable@ Set if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnSetReorderable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetReorderable tvc vis =\n {#call tree_view_column_set_reorderable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n-- @method treeViewColumnGetReorderable@ Get if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnGetReorderable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetReorderable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_reorderable#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortColumnId@ Set the column by which to sort.\n--\n-- * Sets the logical @ref arg 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 column in\n-- the @ref type TreeModel@.\n--\ntreeViewColumnSetSortColumnId :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Int -> IO ()\ntreeViewColumnSetSortColumnId tvc columnId = \n {#call tree_view_column_set_sort_column_id#} \n (toTreeViewColumn tvc) (fromIntegral columnId)\n\n-- @method treeViewColumnGetSortColumnId@ Get the column by which to sort.\n--\n-- * Retrieves the logical @ref arg columnId@ that the model sorts on when\n-- this column is selected for sorting.\n--\n-- * Returns -1 if this column can't be used for sorting.\n--\ntreeViewColumnGetSortColumnId :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSortColumnId tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_sort_column_id#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortIndicator@ Set if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnSetSortIndicator :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Bool -> IO ()\ntreeViewColumnSetSortIndicator tvc sort =\n {#call tree_view_column_set_sort_indicator#} (toTreeViewColumn tvc) \n (fromBool sort)\n\n-- @method treeViewColumnGetSortIndicator@ Query if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnGetSortIndicator :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetSortIndicator tvc = liftM toBool $\n {#call unsafe tree_view_column_get_sort_indicator#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortOrder@ Set if a given column is sorted\n-- in ascending or descending order.\n--\n-- * In order for sorting to work, it is necessary to either use automatic\n-- sorting via @ref method treeViewColumnSetSortColumnId@ or to use a\n-- user defined sorting on the elements in a @ref type TreeModel@.\n--\ntreeViewColumnSetSortOrder :: TreeViewColumnClass tvc => \n\t\t\t tvc -> SortType -> IO ()\ntreeViewColumnSetSortOrder tvc sort =\n {#call tree_view_column_set_sort_order#} (toTreeViewColumn tvc) \n ((fromIntegral.fromEnum) sort)\n\n-- @method treeViewColumnGetSortOrder@ Query if a given column is sorted\n-- in ascending or descending order.\n--\ntreeViewColumnGetSortOrder :: TreeViewColumnClass tvc => tvc -> IO SortType\ntreeViewColumnGetSortOrder tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sort_order#} (toTreeViewColumn tvc)\n\n-- @signal colClicked@ Emitted when the header of this column has been\n-- clicked on.\n--\nonColClicked, afterColClicked :: TreeViewColumnClass tvc => tvc -> IO () -> \n\t\t\t\t\t\t\t IO (ConnectId tvc)\nonColClicked = connect_NONE__NONE \"clicked\" False\nafterColClicked = connect_NONE__NONE \"clicked\" True\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget TreeViewColumn@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:15:09 $\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--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * tree_view_column_new_with_attributes and tree_view_column_set_attributes \n-- are variadic and the funcitonality can be achieved through other \n-- functions.\n--\n-- * tree_view_column_set_cell_data and tree_view_column_cell_get_size are not\n-- bound because I am not sure what they do and when they are useful\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * treeViewColumnSetCellData is not bound. With this function the user has\n-- control over how data in the store is mapped to the attributes of a\n-- cell renderer. This functin should be bound in the future to allow the\n-- user to insert Haskell data types into the store and convert these\n-- values to attributes of cell renderers.\n--\nmodule TreeViewColumn(\n TreeViewColumn,\n TreeViewColumnClass,\n castToTreeViewColumn,\n treeViewColumnNew,\n treeViewColumnPackStart,\n treeViewColumnPackEnd,\n treeViewColumnClear,\n treeViewColumnGetCellRenderers,\n treeViewColumnAddAttribute,\n treeViewColumnSetSpacing,\n treeViewColumnGetSpacing,\n treeViewColumnSetVisible,\n treeViewColumnGetVisible,\n treeViewColumnSetResizable,\n treeViewColumnGetResizable,\n TreeViewColumnSizing(..),\n treeViewColumnSetSizing,\n treeViewColumnGetSizing,\n treeViewColumnGetWidth,\n treeViewColumnSetFixedWidth,\n treeViewColumnSetMinWidth,\n treeViewColumnGetMinWidth,\n treeViewColumnSetMaxWidth,\n treeViewColumnGetMaxWidth,\n treeViewColumnClicked,\n treeViewColumnSetTitle,\n treeViewColumnGetTitle,\n treeViewColumnSetClickable,\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 onColClicked,\n afterColClicked\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(TreeViewColumnSizing(..), SortType(..))\n{#import TreeModel#}\nimport CellRenderer (Attribute(..))\n{#import GList#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- TreeViewColumn type declaration\n\n-- methods\n\n-- @constructor treeViewColumnNew@ Generate a new TreeViewColumn widget.\n--\ntreeViewColumnNew :: IO TreeViewColumn\ntreeViewColumnNew = makeNewObject mkTreeViewColumn \n {#call tree_view_column_new#}\n\n-- @method treeViewColumnPackStart@ Add a cell renderer at the beginning of\n-- a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackStart :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackStart tvc cr expand = \n {#call unsafe tree_view_column_pack_start#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnPackEnd@ Add a cell renderer at the end of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackEnd :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackEnd tvc cr expand = \n {#call unsafe tree_view_column_pack_end#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnClear@ Remove the associations of attributes\n-- to a store for all @ref type CellRenderers@.\n--\ntreeViewColumnClear :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClear tvc = \n {#call tree_view_column_clear#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetCellRenderers@ Retrieve all \n-- @ref type CellRenderer@s that are contained in this column.\n--\ntreeViewColumnGetCellRenderers :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> IO [CellRenderer]\ntreeViewColumnGetCellRenderers tvc = do\n glist <- {#call unsafe tree_view_column_get_cell_renderers#} \n\t (toTreeViewColumn tvc)\n crs <- fromGList glist\n mapM (makeNewObject mkCellRenderer) (map return crs)\n\n-- @method treeViewColumnAddAttribute@ Insert an attribute to change the\n-- behaviour of the column's cell renderer.\n--\n-- * The @ref type CellRenderer@ @ref arg cr@ must already be in \n-- @ref type TreeViewColumn@.\n--\ntreeViewColumnAddAttribute :: (TreeViewColumnClass tvc, CellRendererClass cr)\n\t\t\t => tvc -> cr -> String -> Int -> IO ()\ntreeViewColumnAddAttribute tvc cr attr col = \n withCString attr $ \\cstr -> {#call unsafe tree_view_column_add_attribute#} \n (toTreeViewColumn tvc) (toCellRenderer cr) cstr (fromIntegral col)\n\n\n-- @method treeViewColumnSetSpacing@ Set the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnSetSpacing :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetSpacing tvc vis =\n {#call tree_view_column_set_spacing#} (toTreeViewColumn tvc) \n (fromIntegral vis)\n\n\n-- @method treeViewColumnGetSpacing@ Get the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnGetSpacing :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSpacing tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_spacing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetVisible@ Set the visibility of a given column.\n--\ntreeViewColumnSetVisible :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetVisible tvc vis =\n {#call tree_view_column_set_visible#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetVisible@ Get the visibility of a given column.\n--\ntreeViewColumnGetVisible :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetVisible tvc = liftM toBool $\n {#call unsafe tree_view_column_get_visible#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetResizable@ Set if a given column is resizable\n-- by the user.\n--\ntreeViewColumnSetResizable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetResizable tvc vis =\n {#call tree_view_column_set_resizable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetResizable@ Get if a given column is resizable\n-- by the user.\n--\ntreeViewColumnGetResizable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetResizable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_resizable#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetSizing@ Set wether the column can be resized.\n--\ntreeViewColumnSetSizing :: TreeViewColumnClass tvc => tvc ->\n TreeViewColumnSizing -> IO ()\ntreeViewColumnSetSizing tvc size = {#call tree_view_column_set_sizing#} \n (toTreeViewColumn tvc) ((fromIntegral.fromEnum) size)\n\n\n-- @method treeViewColumnGetSizing@ Return the resizing type of the column.\n--\ntreeViewColumnGetSizing :: TreeViewColumnClass tvc => tvc ->\n IO TreeViewColumnSizing\ntreeViewColumnGetSizing tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sizing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnGetWidth@ Query the current width of the column.\n--\ntreeViewColumnGetWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_width#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetFixedWidth@ Set the width of the column.\n--\n-- * This is meaningful only if the sizing type is\n-- @ref type TreeViewColumnFixed@.\n--\ntreeViewColumnSetFixedWidth :: TreeViewColumnClass tvc => Int -> tvc -> IO ()\ntreeViewColumnSetFixedWidth width tvc = \n {#call tree_view_column_set_fixed_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n\n-- @method treeViewColumnSetMinWidth@ Set minimum width of the column.\n--\ntreeViewColumnSetMinWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMinWidth tvc width = {#call tree_view_column_set_min_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMinWidth@ Get the minimum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMinWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMinWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_min_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetMaxWidth@ Set maximum width of the column.\n--\ntreeViewColumnSetMaxWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMaxWidth tvc width = {#call tree_view_column_set_max_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMaxWidth@ Get the maximum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMaxWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMaxWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_max_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnClicked@ Emit the @ref arg clicked@ signal on the\n-- column.\n--\ntreeViewColumnClicked :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClicked tvc =\n {#call tree_view_column_clicked#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetTitle@ Set the widget's title if a custom widget\n-- has not been set.\n--\ntreeViewColumnSetTitle :: TreeViewColumnClass tvc => tvc -> String -> IO ()\ntreeViewColumnSetTitle tvc title = withCString title $\n {#call tree_view_column_set_title#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetTitle@ Get the widget's title.\n--\ntreeViewColumnGetTitle :: TreeViewColumnClass tvc => tvc -> IO (Maybe String)\ntreeViewColumnGetTitle tvc = do\n strPtr <- {#call unsafe tree_view_column_get_title#} (toTreeViewColumn tvc)\n if strPtr==nullPtr then return Nothing else liftM Just $ peekCString strPtr\n\n-- @method treeViewColumnSetClickable@ Set if the column should be sensitive\n-- to mouse clicks.\n--\ntreeViewColumnSetClickable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetClickable tvc click = {#call tree_view_column_set_clickable#} \n (toTreeViewColumn tvc) (fromBool click)\n\n-- @method treeViewColumnSetWidget@ Set the column's title to this widget.\n--\ntreeViewColumnSetWidget :: (TreeViewColumnClass tvc, WidgetClass w) => tvc ->\n w -> IO ()\ntreeViewColumnSetWidget tvc w =\n {#call tree_view_column_set_widget#} (toTreeViewColumn tvc) (toWidget w)\n\n-- @method treeViewColumnGetWidget@ Retrieve the widget responsible for\n-- showing the column title. In case only a text title was set this will be a\n-- @ref arg Alignment@ widget with a @ref arg Label@ inside.\n--\ntreeViewColumnGetWidget :: TreeViewColumnClass tvc => tvc -> IO Widget\ntreeViewColumnGetWidget tvc = makeNewObject mkWidget $\n {#call unsafe tree_view_column_get_widget#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetAlignment@ Set the alignment of the title.\n--\ntreeViewColumnSetAlignment :: TreeViewColumnClass tvc => tvc -> Float -> IO ()\ntreeViewColumnSetAlignment tvc align = {#call tree_view_column_set_alignment#}\n (toTreeViewColumn tvc) (realToFrac align)\n\n-- @method treeViewColumnGetAlignment@ Get the alignment of the titlte.\n--\ntreeViewColumnGetAlignment :: TreeViewColumnClass tvc => tvc -> IO Float\ntreeViewColumnGetAlignment tvc = liftM realToFrac $\n {#call unsafe tree_view_column_get_alignment#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetReorderable@ Set if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnSetReorderable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetReorderable tvc vis =\n {#call tree_view_column_set_reorderable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n-- @method treeViewColumnGetReorderable@ Get if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnGetReorderable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetReorderable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_reorderable#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortColumnId@ Set the column by which to sort.\n--\n-- * Sets the logical @ref arg 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 column in\n-- the @ref type TreeModel@.\n--\ntreeViewColumnSetSortColumnId :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Int -> IO ()\ntreeViewColumnSetSortColumnId tvc columnId = \n {#call tree_view_column_set_sort_column_id#} \n (toTreeViewColumn tvc) (fromIntegral columnId)\n\n-- @method treeViewColumnGetSortColumnId@ Get the column by which to sort.\n--\n-- * Retrieves the logical @ref arg columnId@ that the model sorts on when\n-- this column is selected for sorting.\n--\n-- * Returns -1 if this column can't be used for sorting.\n--\ntreeViewColumnGetSortColumnId :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSortColumnId tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_sort_column_id#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortIndicator@ Set if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnSetSortIndicator :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Bool -> IO ()\ntreeViewColumnSetSortIndicator tvc sort =\n {#call tree_view_column_set_sort_indicator#} (toTreeViewColumn tvc) \n (fromBool sort)\n\n-- @method treeViewColumnGetSortIndicator@ Query if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnGetSortIndicator :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetSortIndicator tvc = liftM toBool $\n {#call unsafe tree_view_column_get_sort_indicator#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortOrder@ Set if a given column is sorted\n-- in ascending or descending order.\n--\n-- * In order for sorting to work, it is necessary to either use automatic\n-- sorting via @ref method treeViewColumnSetSortColumnId@ or to use a\n-- user defined sorting on the elements in a @ref type TreeModel@.\n--\ntreeViewColumnSetSortOrder :: TreeViewColumnClass tvc => \n\t\t\t tvc -> SortType -> IO ()\ntreeViewColumnSetSortOrder tvc sort =\n {#call tree_view_column_set_sort_order#} (toTreeViewColumn tvc) \n ((fromIntegral.fromEnum) sort)\n\n-- @method treeViewColumnGetSortOrder@ Query if a given column is sorted\n-- in ascending or descending order.\n--\ntreeViewColumnGetSortOrder :: TreeViewColumnClass tvc => tvc -> IO SortType\ntreeViewColumnGetSortOrder tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sort_order#} (toTreeViewColumn tvc)\n\n-- @signal colClicked@ Emitted when the header of this column has been\n-- clicked on.\n--\nonColClicked, afterColClicked :: TreeViewColumnClass tvc => tvc -> IO () -> \n\t\t\t\t\t\t\t IO (ConnectId tvc)\nonColClicked = connect_NONE__NONE \"clicked\" False\nafterColClicked = connect_NONE__NONE \"clicked\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"afca3cbaf3ee272135fa2b0eb39b2d634fae98f2","subject":"\/int2bool\/cint2bool\/","message":"\/int2bool\/cint2bool\/\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\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\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {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","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\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\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {int2cint `Int',\n int2cint `Int',\n int2cint `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 (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":"b620542b1818bffa57cfca6f9bca96c4bda5c8c8","subject":"added stubs for methods to silence warnings","message":"added stubs for methods to silence warnings\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 getModulus,\n getPublicExponent,\n getDecryptFlag,\n getSignFlag,\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_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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\n\ngetSignFlag :: Session -> ObjectHandle -> IO Bool\ngetSignFlag sess objHandle = do\n (Sign v) <- getObjectAttr sess objHandle SignType\n return v\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","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 getModulus,\n getPublicExponent,\n getDecryptFlag,\n getSignFlag,\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_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\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\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\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 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\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\ngetDecryptFlag :: Session -> ObjectHandle -> IO Bool\ngetDecryptFlag sess objHandle = do\n (Decrypt v) <- getObjectAttr sess objHandle DecryptType\n return v\n\ngetSignFlag :: Session -> ObjectHandle -> IO Bool\ngetSignFlag sess objHandle = do\n (Sign v) <- getObjectAttr sess objHandle SignType\n return v\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":"a8980f128b39b87e92b93533db441d23f033bd9e","subject":"add 2D data transfers to the runtime API","message":"add 2D data transfers to the runtime API\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/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 : (c) [2009..2012] 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 \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 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 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 unsafe 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 unsafe 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 unsafe 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 : (c) [2009..2012] 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, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArray, copyArrayAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset\n\n) where\n\n#include \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 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 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-- 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 is a synchronous\n-- operation.\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 host, but will never overlap with kernel\n-- execution.\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-- 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 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 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 (maybe defaultStream id mst)\n\n{-# INLINE cudaMemcpyAsync #-}\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream' } -> `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":"d4cafb95a7fcd6f7302bb68e10dee2fa888743e2","subject":"Correct arguments of a finally statement. This code has obviously never been tested. Thanks to Bertram Felgenhauer to spot this.","message":"Correct arguments of a finally statement.\nThis code has obviously never been tested. Thanks to Bertram Felgenhauer to spot this.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gnomevfs\/System\/Gnome\/VFS\/Marshal.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Marshal.chs","new_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- 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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Marshal (\n \n cToEnum,\n cFromEnum,\n cToBool,\n cFromBool,\n cToFlags,\n cFromFlags,\n genericResultMarshal,\n voidResultMarshal,\n newObjectResultMarshal,\n volumeOpCallbackMarshal\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport Data.Dynamic\nimport System.Glib.FFI\nimport System.Glib.Flags (Flags, toFlags, fromFlags)\nimport System.Glib.UTFString (peekUTFString)\n{#import System.Gnome.VFS.Types#}\nimport System.Gnome.VFS.Error\nimport Prelude hiding (error)\n\ncToEnum :: (Integral a, Enum b) => a -> b\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum a, Integral b) => a -> b\ncFromEnum = fromIntegral . fromEnum\n\ncToBool :: Integral a => a -> Bool\ncToBool = toBool . fromIntegral\n\ncFromBool :: Integral a => Bool -> a\ncFromBool = fromIntegral . fromBool\n\ncToFlags :: (Integral a, Flags b) => a -> [b]\ncToFlags = toFlags . fromIntegral\n\ncFromFlags :: (Flags a, Integral b) => [a] -> b\ncFromFlags = fromIntegral . fromFlags\n\ngenericResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO a\n -> IO b\n -> IO a\ngenericResultMarshal cAction cSuccessAction cFailureAction =\n do result <- liftM cToEnum $ cAction\n case result of\n Ok -> cSuccessAction\n errorCode -> do cFailureAction\n error result\n\nvoidResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO ()\nvoidResultMarshal cAction =\n genericResultMarshal cAction (return ()) (return ())\n\nnewObjectResultMarshal :: (ForeignPtr obj -> obj)\n -> (Ptr (Ptr obj) -> IO {# type GnomeVFSResult #})\n -> IO obj\nnewObjectResultMarshal objConstructor cNewObj =\n alloca $ \\cObjPtr ->\n do poke cObjPtr nullPtr\n genericResultMarshal (cNewObj cObjPtr)\n (do cObj <- peek cObjPtr\n assert (cObj \/= nullPtr) $ return ()\n newObj <- newForeignPtr_ cObj\n return $ objConstructor newObj)\n (do cObj <- peek cObjPtr\n assert (cObj == nullPtr) $ return ())\n\nvolumeOpCallbackMarshal :: VolumeOpSuccessCallback\n -> VolumeOpFailureCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\nvolumeOpCallbackMarshal successCallback failureCallback =\n let cCallback :: CVolumeOpCallback\n cCallback cSucceeded cError cDetailedError cUserData =\n let succeeded = cToBool cSucceeded\n cCallbackFunPtr = castPtrToFunPtr cUserData\n in (flip finally) (freeHaskellFunPtr cCallbackFunPtr) $\n if succeeded\n then assert (and [cError == nullPtr, cDetailedError == nullPtr]) $\n successCallback\n else assert (and [cError \/= nullPtr, cDetailedError \/= nullPtr]) $\n do error <- peekUTFString cError\n detailedError <- peekUTFString cDetailedError\n failureCallback error detailedError\n in makeVolumeOpCallback cCallback\nforeign import ccall safe \"wrapper\"\n makeVolumeOpCallback :: CVolumeOpCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\n","old_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- 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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Marshal (\n \n cToEnum,\n cFromEnum,\n cToBool,\n cFromBool,\n cToFlags,\n cFromFlags,\n genericResultMarshal,\n voidResultMarshal,\n newObjectResultMarshal,\n volumeOpCallbackMarshal\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport Data.Dynamic\nimport System.Glib.FFI\nimport System.Glib.Flags (Flags, toFlags, fromFlags)\nimport System.Glib.UTFString (peekUTFString)\n{#import System.Gnome.VFS.Types#}\nimport System.Gnome.VFS.Error\nimport Prelude hiding (error)\n\ncToEnum :: (Integral a, Enum b) => a -> b\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum a, Integral b) => a -> b\ncFromEnum = fromIntegral . fromEnum\n\ncToBool :: Integral a => a -> Bool\ncToBool = toBool . fromIntegral\n\ncFromBool :: Integral a => Bool -> a\ncFromBool = fromIntegral . fromBool\n\ncToFlags :: (Integral a, Flags b) => a -> [b]\ncToFlags = toFlags . fromIntegral\n\ncFromFlags :: (Flags a, Integral b) => [a] -> b\ncFromFlags = fromIntegral . fromFlags\n\ngenericResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO a\n -> IO b\n -> IO a\ngenericResultMarshal cAction cSuccessAction cFailureAction =\n do result <- liftM cToEnum $ cAction\n case result of\n Ok -> cSuccessAction\n errorCode -> do cFailureAction\n error result\n\nvoidResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO ()\nvoidResultMarshal cAction =\n genericResultMarshal cAction (return ()) (return ())\n\nnewObjectResultMarshal :: (ForeignPtr obj -> obj)\n -> (Ptr (Ptr obj) -> IO {# type GnomeVFSResult #})\n -> IO obj\nnewObjectResultMarshal objConstructor cNewObj =\n alloca $ \\cObjPtr ->\n do poke cObjPtr nullPtr\n genericResultMarshal (cNewObj cObjPtr)\n (do cObj <- peek cObjPtr\n assert (cObj \/= nullPtr) $ return ()\n newObj <- newForeignPtr_ cObj\n return $ objConstructor newObj)\n (do cObj <- peek cObjPtr\n assert (cObj == nullPtr) $ return ())\n\nvolumeOpCallbackMarshal :: VolumeOpSuccessCallback\n -> VolumeOpFailureCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\nvolumeOpCallbackMarshal successCallback failureCallback =\n let cCallback :: CVolumeOpCallback\n cCallback cSucceeded cError cDetailedError cUserData =\n let succeeded = cToBool cSucceeded\n cCallbackFunPtr = castPtrToFunPtr cUserData\n in finally (freeHaskellFunPtr cCallbackFunPtr) $\n if succeeded\n then assert (and [cError == nullPtr, cDetailedError == nullPtr]) $\n successCallback\n else assert (and [cError \/= nullPtr, cDetailedError \/= nullPtr]) $\n do error <- peekUTFString cError\n detailedError <- peekUTFString cDetailedError\n failureCallback error detailedError\n in makeVolumeOpCallback cCallback\nforeign import ccall safe \"wrapper\"\n makeVolumeOpCallback :: CVolumeOpCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"2e7ad7646aa9e7324a0dc336f48db44b46b650c1","subject":"Fix CPP errors for OpenGL inclusion.","message":"Fix CPP errors for OpenGL inclusion.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Enumerations.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Enumerations.chs","new_contents":"{-# LANGUAGE CPP #-}\n#include \"Fl_C.h\"\n#include \"Fl_EnumerationsC.h\"\nmodule Graphics.UI.FLTK.LowLevel.Fl_Enumerations\n (\n -- * Events\n Event(..),\n When(..),\n FdWhen(..),\n -- * Tree Attributes\n TreeSort(..),\n TreeConnector(..),\n TreeSelect(..),\n SearchDirection(..),\n#if FLTK_ABI_VERSION >= 10302\n TreeItemReselectMode(..),\n TreeItemDrawMode(..),\n#endif\n -- * Keyboard and mouse codes\n SpecialKey(..),\n allSpecialKeys,\n allShortcutSpecialKeys,\n MouseButton(..),\n EventState(..),\n KeyboardKeyMask(..),\n MouseButtonsMask(..),\n allEventStates,\n kb_CommandState, kb_ControlState, kb_KpLast,\n -- * Widget damage types\n Damage(..),\n -- * Cursor type\n Cursor(..),\n#ifdef GLSUPPORT\n -- * Glut attributes\n GlutDraw(..),\n GlutMouseCodes(..),\n GlutUpDown(..),\n GlutVisibility(..),\n GlutMenuProperties(..),\n GlutEnteredLeft(..),\n GlutKeyboardCodes(..),\n GlutConstants(..),\n GlutWindowProperties(..),\n GlutCursor(..),\n glutCursorFullCrossHair,\n#endif\n -- * Various modes\n Mode(..),\n Modes(..),\n single,\n allModes,\n -- * Alignment\n Alignments(..),\n AlignType(..),\n alignCenter,\n alignTop,\n alignBottom,\n alignLeft,\n alignRight,\n alignInside,\n alignTextOverImage,\n alignClip,\n alignWrap,\n alignImageNextToText,\n alignTextNextToImage,\n alignImageBackdrop,\n alignLeftTop,\n alignRightTop,\n alignLeftBottom,\n alignRightBottom,\n alignPositionMask,\n alignImageMask,\n alignNoWrap,\n alignImageOverText,\n alignTopLeft,\n alignTopRight,\n alignBottomLeft,\n alignBottomRight,\n allAlignTypes,\n allWhen,\n -- * Box types\n Boxtype(..),\n frame,frameBox, circleBox, diamondBox,\n -- * Box functions\n defineRoundUpBox,\n defineShadowBox,\n defineRoundedBox,\n defineRflatBox,\n defineRshadowBox,\n defineDiamondBox,\n defineOvalBox,\n definePlasticUpBox,\n defineGtkUpBox,\n -- * Fonts\n Font(..),\n FontAttribute(..),\n -- ** (Un-)marshalling\n cFromFont,\n cToFont,\n cFromFontAttribute,\n cToFontAttribute,\n -- ** Font Names\n helvetica,\n helveticaBold,\n helveticaItalic,\n helveticaBoldItalic,\n courier,\n courierBold,\n courierItalic,\n courierBoldItalic,\n times,\n timesBold,\n timesItalic,\n timesBoldItalic,\n symbol,\n screen,\n screenBold,\n zapfDingbats,\n freeFont,\n\n -- * Colors\n Color(..),\n -- ** (Un-)marshalling\n cFromColor,\n cToColor,\n -- ** Various Color Functions\n inactive,\n contrast,\n color_average,\n lighter,\n darker,\n rgbColorWithRgb,\n rgbColorWithGrayscale,\n grayRamp,\n colorCube,\n -- ** Color Names\n foregroundColor,\n background2Color,\n inactiveColor,\n selectionColor,\n gray0Color,\n dark3Color,\n dark2Color,\n dark1Color,\n backgroundColor,\n light1Color,\n light2Color,\n light3Color,\n blackColor,\n redColor,\n greenColor,\n yellowColor,\n blueColor,\n magentaColor,\n cyanColor,\n darkRedColor,\n darkGreenColor,\n darkYellowColor,\n darkBlueColor,\n darkMagentaColor,\n darkCyanColor,\n whiteColor,\n freeColor,\n numFreeColor,\n grayRampColor,\n numGray,\n grayColor,\n colorCubeColor,\n numRed,\n numGreen,\n numBlue,\n -- * Labels\n Labeltype(..),\n symbolLabel,\n defineShadowLabel,\n defineEngravedLabel,\n defineEmbossedLabel,\n -- * Color\n RGB\n )\nwhere\nimport C2HS\n#c\nenum VersionInfo {\n MajorVersion = FL_MAJOR_VERSION,\n MinorVersion = FL_MINOR_VERSION,\n PatchVersion = FL_PATCH_VERSION,\n Version = FL_VERSION\n};\nenum Event {\n NoEvent = FL_NO_EVENT,\n Push = FL_PUSH,\n Release = FL_RELEASE,\n Enter = FL_ENTER,\n Leave = FL_LEAVE,\n Drag = FL_DRAG,\n Focus = FL_FOCUS,\n Unfocus = FL_UNFOCUS,\n Keydown = FL_KEYDOWN,\n \/\/ FL_KEYBOARD same as above,\n Keyup = FL_KEYUP,\n Close = FL_CLOSE,\n Move = FL_MOVE,\n Shortcut = FL_SHORTCUT,\n Deactivate = FL_DEACTIVATE,\n Activate = FL_ACTIVATE,\n Hide = FL_HIDE,\n Show = FL_SHOW,\n Paste = FL_PASTE,\n Selectionclear = FL_SELECTIONCLEAR,\n Mousewheel = FL_MOUSEWHEEL,\n DndEnter = FL_DND_ENTER,\n DndDrag = FL_DND_DRAG,\n DndLeave = FL_DND_LEAVE,\n DndRelease = FL_DND_RELEASE,\n ScreenConfigurationChanged = FL_SCREEN_CONFIGURATION_CHANGED,\n Fullscreen = FL_FULLSCREEN\n};\nenum When {\n WhenNever = FL_WHEN_NEVER,\n WhenChanged = FL_WHEN_CHANGED,\n WhenNotChanged = FL_WHEN_NOT_CHANGED,\n WhenRelease = FL_WHEN_RELEASE,\n WhenReleaseAlways= FL_WHEN_RELEASE_ALWAYS,\n WhenEnterKey = FL_WHEN_ENTER_KEY,\n WhenEnterKeyAlways = FL_WHEN_ENTER_KEY_ALWAYS,\n WhenEnterKeyChanged = FL_WHEN_ENTER_KEY_CHANGED\n};\n\nenum TabsWhen {\n TabsWhenNever = FL_WHEN_NEVER,\n TabsWhenChanged = FL_WHEN_CHANGED,\n TabsWhenNotChanged = FL_WHEN_NOT_CHANGED,\n TabsWhenRelease = FL_WHEN_RELEASE\n};\n\nenum FdWhen {\n CanRead = FL_READ,\n CanWrite = FL_WRITE,\n OnExcept = FL_EXCEPT\n};\nenum TreeSort{\n TreeSortNone = FL_TREE_SORT_NONE,\n TreeSortAscending = FL_TREE_SORT_ASCENDING,\n TreeSortDescending = FL_TREE_SORT_DESCENDING\n};\nenum TreeConnector{\n TreeConnectorNone = FL_TREE_CONNECTOR_NONE,\n TreeConnectorDotted = FL_TREE_CONNECTOR_DOTTED,\n TreeConnectorSolid = FL_TREE_CONNECTOR_SOLID\n};\nenum TreeSelect{\n TreeSelectNone = FL_TREE_SELECT_NONE,\n TreeSelectSingle = FL_TREE_SELECT_SINGLE,\n TreeSelectMulti = FL_TREE_SELECT_MULTI,\n TreeSelectSingleDraggable = FL_TREE_SELECT_SINGLE_DRAGGABLE\n};\nenum SearchDirection {\n SearchDirectionDown = FL_Down,\n SearchDirectionUp = FL_Up\n};\n#if FLTK_ABI_VERSION >= 10302\nenum TreeItemReselectMode{\n TreeSelectableOnce = FL_TREE_SELECTABLE_ONCE,\n TreeSelectableAlways = FL_TREE_SELECTABLE_ALWAYS\n};\nenum TreeItemDrawMode{\n TreeItemDrawDefault = FL_TREE_ITEM_DRAW_DEFAULT,\n TreeItemDrawLabelAndWidget = FL_TREE_ITEM_DRAW_LABEL_AND_WIDGET,\n TreeItemHeightFromWidget = FL_TREE_ITEM_HEIGHT_FROM_WIDGET\n};\n#endif\nenum SpecialKey {\n Button = FL_Button,\n Kb_Clear = FL_Clear,\n Kb_Backspace = FL_BackSpace,\n Kb_Tab = FL_Tab,\n Kb_IsoKey = FL_Iso_Key,\n Kb_Enter = FL_Enter,\n Kb_Pause = FL_Pause,\n Kb_Escape = FL_Escape,\n Kb_Kana = FL_Kana,\n Kb_Eisu = FL_Eisu,\n Kb_Yen = FL_Yen,\n Kb_JisUnderscore = FL_JIS_Underscore,\n Kb_Home = FL_Home,\n Kb_Left = FL_Left,\n Kb_Up = FL_Up,\n Kb_Right = FL_Right,\n Kb_Down = FL_Down,\n Kb_PageUp = FL_Page_Up,\n Kb_PageDown = FL_Page_Down,\n Kb_End = FL_End,\n Kb_Print = FL_Print,\n Kb_Insert = FL_Insert,\n Kb_Menu = FL_Menu,\n Kb_Help = FL_Help,\n Kb_Kp = FL_KP,\n Kb_KpEnter = FL_KP_Enter,\n Kb_F = FL_F,\n Kb_Flast = FL_F_Last,\n Kb_ShiftL = FL_Shift_L,\n Kb_ShiftR = FL_Shift_R,\n Kb_ControlL = FL_Control_L,\n Kb_ControlR = FL_Control_R,\n Kb_CapsLock = FL_Caps_Lock,\n Kb_MetaL = FL_Meta_L,\n Kb_MetaR = FL_Meta_R,\n Kb_AltL = FL_Alt_L,\n Kb_AltR = FL_Alt_R,\n Kb_Delete = FL_Delete,\n Kb_VolumeDown = FL_Volume_Down,\n Kb_VolumeMute = FL_Volume_Mute,\n Kb_VolumeUp = FL_Volume_Up,\n Kb_MediaPlay = FL_Media_Play,\n Kb_MediaStop = FL_Media_Stop,\n Kb_MediaPrev = FL_Media_Prev,\n Kb_MediaNext = FL_Media_Next,\n Kb_HomePage = FL_Home_Page,\n Kb_Mail = FL_Mail,\n Kb_Search = FL_Search,\n Kb_Back = FL_Back,\n Kb_Forward = FL_Forward,\n Kb_Stop = FL_Stop,\n Kb_Refresh = FL_Refresh,\n Kb_Sleep = FL_Sleep,\n Kb_Favorites = FL_Favorites,\n};\nenum MouseButton {\n Mouse_Left = FL_LEFT_MOUSE,\n Mouse_Middle = FL_MIDDLE_MOUSE,\n Mouse_Right = FL_RIGHT_MOUSE,\n};\nenum EventState {\n Kb_ShiftState = FL_SHIFT,\n Kb_CapsLockState = FL_CAPS_LOCK,\n Kb_CtrlState = FL_CTRL,\n Kb_AltState = FL_ALT,\n Kb_NumLockState = FL_NUM_LOCK,\n Kb_MetaState = FL_META,\n Kb_ScrollLockState = FL_SCROLL_LOCK,\n Mouse_Button1State = FL_BUTTON1,\n Mouse_Button2State = FL_BUTTON2,\n Mouse_Button3State= FL_BUTTON3,\n};\nenum KeyboardKeyMask {\n Kb_KeyMask = FL_KEY_MASK\n};\nenum MouseButtonsMask {\n Mouse_ButtonsMask = FL_BUTTONS,\n};\nenum Damage {\n DamageChild = FL_DAMAGE_CHILD,\n DamageExpose = FL_DAMAGE_EXPOSE,\n DamageScroll = FL_DAMAGE_SCROLL,\n DamageOverlay = FL_DAMAGE_OVERLAY,\n DamageUser1 = FL_DAMAGE_USER1,\n DamageUser2 = FL_DAMAGE_USER2,\n DamageAll = FL_DAMAGE_ALL\n};\n#ifdef GLSUPPORT\nenum GlutDraw {\n GlutNormal = GLUT_NORMAL,\n GlutOverlay = GLUT_OVERLAY\n};\nenum GlutMouseCodes {\n GlutLeftButton = GLUT_LEFT_BUTTON,\n GlutRightButton = GLUT_RIGHT_BUTTON,\n GlutMiddleButton = GLUT_MIDDLE_BUTTON\n};\nenum GlutUpDown {\n GlutUp = GLUT_UP,\n GlutDown = GLUT_DOWN\n};\nenum GlutVisibility {\n GlutVisible = GLUT_VISIBLE,\n GlutNotVisible = GLUT_NOT_VISIBLE\n};\nenum GlutMenuProperties {\n GlutMenuNotInUse = GLUT_MENU_NOT_IN_USE,\n GlutMenuInUse = GLUT_MENU_IN_USE,\n GlutMenuNumItems = GLUT_MENU_NUM_ITEMS\n};\nenum GlutEnteredLeft {\n GlutEntered = GLUT_ENTERED,\n GlutLeft = GLUT_LEFT\n};\nenum GlutKeyboardCodes {\n GlutKeyF1 = GLUT_KEY_F1,\n GlutKeyF2 = GLUT_KEY_F2,\n GlutKeyF3 = GLUT_KEY_F3,\n GlutKeyF4 = GLUT_KEY_F4,\n GlutKeyF5 = GLUT_KEY_F5,\n GlutKeyF6 = GLUT_KEY_F6,\n GlutKeyF7 = GLUT_KEY_F7,\n GlutKeyF8 = GLUT_KEY_F8,\n GlutKeyF9 = GLUT_KEY_F9,\n GlutKeyF10 = GLUT_KEY_F10,\n GlutKeyF11 = GLUT_KEY_F11,\n GlutKeyF12 = GLUT_KEY_F12,\n GlutKeyLeft = GLUT_KEY_LEFT,\n GlutKeyUp = GLUT_KEY_UP,\n GlutKeyRight = GLUT_KEY_RIGHT,\n GlutKeyDown = GLUT_KEY_DOWN,\n GlutKeyPageUp = GLUT_KEY_PAGE_UP,\n GlutKeyPageDown = GLUT_KEY_PAGE_DOWN,\n GlutKeyHome = GLUT_KEY_HOME,\n GlutKeyEnd = GLUT_KEY_END,\n GlutKeyInsert = GLUT_KEY_INSERT,\n GlutActiveShift = GLUT_ACTIVE_SHIFT,\n GlutActiveCtrl = GLUT_ACTIVE_CTRL,\n GlutActiveAlt = GLUT_ACTIVE_ALT\n};\nenum GlutConstants {\n GlutReturnZero = GLUT_RETURN_ZERO,\n GlutDisplayModePossible = GLUT_DISPLAY_MODE_POSSIBLE,\n GlutVersion = GLUT_VERSION,\n GlutOverlayPossible = GLUT_OVERLAY_POSSIBLE,\n GlutTransparentIndex = GLUT_TRANSPARENT_INDEX,\n GlutNormalDamaged = GLUT_NORMAL_DAMAGED,\n GlutOverlayDamaged = GLUT_OVERLAY_DAMAGED\n};\nenum GlutWindowProperties {\n GlutWindowX = GLUT_WINDOW_X,\n GlutWindowY = GLUT_WINDOW_Y,\n GlutWindowWidth = GLUT_WINDOW_WIDTH,\n GlutWindowHeight = GLUT_WINDOW_HEIGHT,\n GlutWindowParent = GLUT_WINDOW_PARENT,\n GlutScreenWidth = GLUT_SCREEN_WIDTH,\n GlutScreenHeight = GLUT_SCREEN_HEIGHT,\n GlutInitWindowX = GLUT_INIT_WINDOW_X,\n GlutInitWindowY = GLUT_INIT_WINDOW_Y,\n GlutInitWindowWidth = GLUT_INIT_WINDOW_WIDTH,\n GlutInitWindowHeight = GLUT_INIT_WINDOW_HEIGHT,\n GlutInitDisplayMode = GLUT_INIT_DISPLAY_MODE,\n GlutWindowBufferSize = GLUT_WINDOW_BUFFER_SIZE,\n GlutWindowStencilSize = GLUT_WINDOW_STENCIL_SIZE,\n GlutWindowDepthSize = GLUT_WINDOW_DEPTH_SIZE,\n GlutWindowRedSize = GLUT_WINDOW_RED_SIZE,\n GlutWindowGreenSize = GLUT_WINDOW_GREEN_SIZE,\n GlutWindowBlueSize = GLUT_WINDOW_BLUE_SIZE,\n GlutWindowAlphaSize = GLUT_WINDOW_ALPHA_SIZE,\n GlutWindowAccumRedSize = GLUT_WINDOW_ACCUM_RED_SIZE,\n GlutWindowAccumGreenSize = GLUT_WINDOW_ACCUM_GREEN_SIZE,\n GlutWindowAccumBlueSize = GLUT_WINDOW_ACCUM_BLUE_SIZE,\n GlutWindowAccumAlphaSize = GLUT_WINDOW_ACCUM_ALPHA_SIZE,\n GlutWindowDoublebuffer = GLUT_WINDOW_DOUBLEBUFFER,\n GlutWindowRgba = GLUT_WINDOW_RGBA,\n GlutWindowColormapSize = GLUT_WINDOW_COLORMAP_SIZE,\n GlutWindowNumSamples = GLUT_WINDOW_NUM_SAMPLES,\n GlutWindowStereo = GLUT_WINDOW_STEREO\n};\nenum GlutCursor {\n GlutCursorRightArrow = 2,\n GlutCursorLeftArrow = 67,\n GlutCursorDestroy = 45,\n GlutCursorCycle = 26,\n GlutCursorSpray = 63,\n GlutCursorInfo = FL_CURSOR_HAND,\n GlutCursorHelp = FL_CURSOR_HELP,\n GlutCursorWait = FL_CURSOR_WAIT,\n GlutCursorText = FL_CURSOR_INSERT,\n GlutCursorLeftRight = FL_CURSOR_WE,\n GlutCursorTopSide = FL_CURSOR_N,\n GlutCursorBottomSide = FL_CURSOR_S,\n GlutCursorLeftSide = FL_CURSOR_W,\n GlutCursorRightSide = FL_CURSOR_E,\n GlutCursorTopLeftCorner = FL_CURSOR_NW,\n GlutCursorTopRightCorner = FL_CURSOR_NE,\n GlutCursorBottomRightCorner = FL_CURSOR_SE,\n GlutCursorBottomLeftCorner = FL_CURSOR_SW,\n GlutCursorInherit = FL_CURSOR_DEFAULT,\n GlutCursorNone = FL_CURSOR_NONE,\n GlutCursorUpDown = FL_CURSOR_NS,\n GlutCursorCrosshair = FL_CURSOR_CROSS\n};\n#endif\nenum Cursor {\n CursorDefault = FL_CURSOR_DEFAULT,\n CursorArrow = FL_CURSOR_ARROW,\n CursorCross = FL_CURSOR_CROSS,\n CursorWait = FL_CURSOR_WAIT,\n CursorInsert = FL_CURSOR_INSERT,\n CursorHand = FL_CURSOR_HAND,\n CursorHelp = FL_CURSOR_HELP,\n CursorMove = FL_CURSOR_MOVE,\n CursorNS = FL_CURSOR_NS,\n CursorWE = FL_CURSOR_WE,\n CursorNWSE = FL_CURSOR_NWSE,\n CursorNesw = FL_CURSOR_NESW,\n CursorNone = FL_CURSOR_NONE,\n CursorN = FL_CURSOR_N,\n CursorNE = FL_CURSOR_NE,\n CursorE = FL_CURSOR_E,\n CursorSE = FL_CURSOR_SE,\n CursorS = FL_CURSOR_S,\n CursorSW = FL_CURSOR_SW,\n CursorW = FL_CURSOR_W,\n CursorNW = FL_CURSOR_NW\n};\nenum Mode {\n ModeRGB = FL_RGB,\n ModeRGB8 = FL_RGB8,\n ModeIndex = FL_INDEX,\n ModeDouble = FL_DOUBLE,\n ModeAccum = FL_ACCUM,\n ModeAlpha = FL_ALPHA,\n ModeDepth = FL_DEPTH,\n ModeStencil = FL_STENCIL,\n ModeMultisample = FL_MULTISAMPLE,\n ModeStereo = FL_STEREO,\n ModeFakeSingle = FL_FAKE_SINGLE\n#ifdef GLSUPPORT\n#if FLTK_API_VERSION >= 10304\n , ModeOpenGL3 = FL_OPENGL3\n#endif\n#endif\n};\nenum AlignType {\n AlignTypeCenter = 0,\n AlignTypeTop = 1,\n AlignTypeBottom = 2,\n AlignTypeLeft = 4,\n AlignTypeRight = 8,\n AlignTypeInside = 16,\n AlignTypeTextOverImage = 0x0020,\n AlignTypeClip = 64,\n AlignTypeWrap = 128,\n AlignTypeImageNextToText = 0x0100,\n AlignTypeTextNextToImage = 0x0120,\n AlignTypeImageBackdrop = 0x0200,\n AlignTypeLeftTop = 0x0007,\n AlignTypeRightTop = 0x000b,\n AlignTypeLeftBottom = 0x000d,\n AlignTypeRightBottom = 0x000e,\n};\n#endc\n{#enum Event {} deriving (Show, Eq) #}\n{#enum When {} deriving (Show, Eq, Ord) #}\n{#enum FdWhen {} deriving (Show, Eq, Ord) #}\n{#enum TreeSort {} deriving (Show, Eq) #}\n{#enum TreeConnector {} deriving (Show, Eq) #}\n{#enum TreeSelect {} deriving (Show, Eq) #}\n{#enum SearchDirection {} deriving (Show, Eq) #}\n#if FLTK_ABI_VERSION >= 10302\n{#enum TreeItemReselectMode {} deriving (Show, Eq) #}\n{#enum TreeItemDrawMode {} deriving (Show, Eq) #}\n#endif\n{#enum SpecialKey {} deriving (Show, Eq) #}\n\nallShortcutSpecialKeys :: [CInt]\nallShortcutSpecialKeys = [\n fromIntegral $ fromEnum (Kb_Backspace),\n fromIntegral $ fromEnum (Kb_Tab),\n fromIntegral $ fromEnum (Kb_Clear),\n fromIntegral $ fromEnum (Kb_Enter),\n fromIntegral $ fromEnum (Kb_Pause),\n fromIntegral $ fromEnum (Kb_ScrollLockState),\n fromIntegral $ fromEnum (Kb_Escape),\n fromIntegral $ fromEnum (Kb_Home),\n fromIntegral $ fromEnum (Kb_Left),\n fromIntegral $ fromEnum (Kb_Up),\n fromIntegral $ fromEnum (Kb_Right),\n fromIntegral $ fromEnum (Kb_Down),\n fromIntegral $ fromEnum (Kb_PageUp),\n fromIntegral $ fromEnum (Kb_PageDown),\n fromIntegral $ fromEnum (Kb_End),\n fromIntegral $ fromEnum (Kb_Print),\n fromIntegral $ fromEnum (Kb_Insert),\n fromIntegral $ fromEnum (Kb_Menu),\n fromIntegral $ fromEnum (Kb_NumLockState),\n fromIntegral $ fromEnum (Kb_KpEnter),\n fromIntegral $ fromEnum (Kb_ShiftL),\n fromIntegral $ fromEnum (Kb_ShiftR),\n fromIntegral $ fromEnum (Kb_ControlL),\n fromIntegral $ fromEnum (Kb_ControlR),\n fromIntegral $ fromEnum (Kb_CapsLock),\n fromIntegral $ fromEnum (Kb_MetaL),\n fromIntegral $ fromEnum (Kb_MetaR),\n fromIntegral $ fromEnum (Kb_AltL),\n fromIntegral $ fromEnum (Kb_AltR),\n fromIntegral $ fromEnum (Kb_Delete)\n ]\n\nallSpecialKeys :: [SpecialKey]\nallSpecialKeys = [\n Button,\n Kb_Backspace,\n Kb_Clear,\n Kb_Tab,\n Kb_IsoKey,\n Kb_Enter,\n Kb_Pause,\n Kb_Escape,\n Kb_Kana,\n Kb_Eisu,\n Kb_Yen,\n Kb_JisUnderscore,\n Kb_Home,\n Kb_Left,\n Kb_Up,\n Kb_Right,\n Kb_Down,\n Kb_PageUp,\n Kb_PageDown,\n Kb_End,\n Kb_Print,\n Kb_Insert,\n Kb_Menu,\n Kb_Help,\n Kb_Kp,\n Kb_KpEnter,\n Kb_F,\n Kb_Flast,\n Kb_ShiftL,\n Kb_ShiftR,\n Kb_ControlL,\n Kb_ControlR,\n Kb_CapsLock,\n Kb_MetaL,\n Kb_MetaR,\n Kb_AltL,\n Kb_AltR,\n Kb_Delete,\n Kb_VolumeDown,\n Kb_VolumeMute,\n Kb_VolumeUp,\n Kb_MediaPlay,\n Kb_MediaStop,\n Kb_MediaPrev,\n Kb_MediaNext,\n Kb_HomePage,\n Kb_Mail,\n Kb_Search,\n Kb_Back,\n Kb_Forward,\n Kb_Stop,\n Kb_Refresh,\n Kb_Sleep,\n Kb_Favorites\n ]\n\n{#enum MouseButton {} deriving (Show, Eq) #}\n{#enum EventState {} deriving (Show, Eq, Ord) #}\n{#enum KeyboardKeyMask {} deriving (Show, Eq, Ord) #}\n{#enum MouseButtonsMask {} deriving (Show, Eq, Ord) #}\nkb_CommandState, kb_ControlState :: EventState\n#ifdef __APPLE__\nkb_CommandState = Kb_MetaState\nkb_ControlState = Kb_CtrlState\n#else\nkb_CommandState = Kb_CtrlState\nkb_ControlState = Kb_MetaState\n#endif\nkb_KpLast :: SpecialKey\nkb_KpLast = Kb_F\n{#enum Damage {} deriving (Show) #}\n{#enum Cursor {} deriving (Show) #}\n#ifdef GLSUPPORT\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutDraw {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutMouseCodes {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutUpDown {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutVisibility {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutMenuProperties {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutEnteredLeft {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutKeyboardCodes {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutConstants {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutWindowProperties {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutCursor {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\nglutCursorFullCrossHair :: GlutCursor\nglutCursorFullCrossHair = GlutCursorCrosshair\n#endif \/* GLSUPPORT *\/\n{#enum Mode {} deriving (Show,Eq,Ord) #}\n-- Fl_Mode Aliases\nsingle :: Mode\nsingle = ModeRGB\nnewtype Modes = Modes [Mode] deriving (Show,Eq,Ord)\nallModes :: [Mode]\nallModes =\n [\n ModeRGB,\n ModeIndex,\n ModeDouble,\n ModeAccum,\n ModeAlpha,\n ModeDepth,\n ModeStencil,\n ModeRGB8,\n ModeMultisample,\n ModeStereo,\n ModeFakeSingle\n#if FLTK_API_VERSION >= 10304\n#ifdef GLSUPPORT\n , ModeOpenGL3\n#endif\n#endif\n ]\n\n{#enum AlignType {} deriving (Show, Eq, Ord) #}\nnewtype Alignments = Alignments [AlignType] deriving Show\nalignCenter :: Alignments\nalignCenter = Alignments [AlignTypeCenter]\nalignTop :: Alignments\nalignTop = Alignments [AlignTypeTop]\nalignBottom :: Alignments\nalignBottom = Alignments [AlignTypeBottom]\nalignLeft :: Alignments\nalignLeft = Alignments [AlignTypeLeft]\nalignRight :: Alignments\nalignRight = Alignments [AlignTypeRight]\nalignInside :: Alignments\nalignInside = Alignments [AlignTypeInside]\nalignTextOverImage :: Alignments\nalignTextOverImage = Alignments [AlignTypeTextOverImage]\nalignClip :: Alignments\nalignClip = Alignments [AlignTypeClip]\nalignWrap :: Alignments\nalignWrap = Alignments [AlignTypeWrap]\nalignImageNextToText :: Alignments\nalignImageNextToText = Alignments [AlignTypeImageNextToText]\nalignTextNextToImage :: Alignments\nalignTextNextToImage = Alignments [AlignTypeTextNextToImage]\nalignImageBackdrop :: Alignments\nalignImageBackdrop = Alignments [AlignTypeImageBackdrop]\nalignLeftTop :: Alignments\nalignLeftTop = Alignments [AlignTypeLeftTop]\nalignRightTop :: Alignments\nalignRightTop = Alignments [AlignTypeRightTop]\nalignLeftBottom :: Alignments\nalignLeftBottom = Alignments [AlignTypeLeftBottom]\nalignRightBottom :: Alignments\nalignRightBottom = Alignments [AlignTypeRightBottom]\nalignPositionMask :: Alignments\nalignPositionMask = Alignments [AlignTypeLeft, AlignTypeRight, AlignTypeTop, AlignTypeBottom]\nalignImageMask :: Alignments\nalignImageMask = Alignments [AlignTypeImageBackdrop, AlignTypeImageNextToText, AlignTypeTextOverImage]\nalignNoWrap :: Alignments\nalignNoWrap = alignCenter\nalignImageOverText :: Alignments\nalignImageOverText = alignCenter\nalignTopLeft :: Alignments\nalignTopLeft = Alignments [AlignTypeTop, AlignTypeLeft]\nalignTopRight :: Alignments\nalignTopRight = Alignments [AlignTypeTop, AlignTypeRight]\nalignBottomLeft :: Alignments\nalignBottomLeft = Alignments [AlignTypeBottom, AlignTypeLeft]\nalignBottomRight :: Alignments\nalignBottomRight = Alignments [AlignTypeBottom, AlignTypeRight]\nallAlignTypes :: [AlignType]\nallAlignTypes = [\n AlignTypeCenter,\n AlignTypeTop,\n AlignTypeBottom,\n AlignTypeLeft,\n AlignTypeRight,\n AlignTypeInside,\n AlignTypeTextOverImage,\n AlignTypeClip,\n AlignTypeWrap,\n AlignTypeImageNextToText,\n AlignTypeTextNextToImage,\n AlignTypeImageBackdrop,\n AlignTypeLeftTop,\n AlignTypeRightTop,\n AlignTypeLeftBottom,\n AlignTypeRightBottom\n ]\nallWhen :: [When]\nallWhen = [\n WhenNever,\n WhenChanged,\n WhenNotChanged,\n WhenRelease,\n WhenReleaseAlways,\n WhenEnterKey,\n WhenEnterKeyAlways,\n WhenEnterKeyChanged\n ]\n\nallEventStates :: [EventState]\nallEventStates = [\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 ]\ndata Boxtype = NoBox\n | FlatBox\n | UpBox\n | DownBox\n | UpFrame\n | DownFrame\n | ThinUpBox\n | ThinDownBox\n | ThinUpFrame\n | ThinDownFrame\n | EngravedBox\n | EmbossedBox\n | EngravedFrame\n | EmbossedFrame\n | BorderBox\n | ShadowBox\n | BorderFrame\n | ShadowFrame\n | RoundedBox\n | RshadowBox\n | RoundedFrame\n | RFlatBox\n | RoundUpBox\n | RoundDownBox\n | DiamondUpBox\n | DiamondDownBox\n | OvalBox\n | OshadowBox\n | OvalFrame\n | FloatBox\n | PlasticUpBox\n | PlasticDownBox\n | PlasticUpFrame\n | PlasticDownFrame\n | PlasticThinUpBox\n | PlasticThinDownBox\n | PlasticRoundUpBox\n | PlasticRoundDownBox\n | GtkUpBox\n | GtkDownBox\n | GtkUpFrame\n | GtkDownFrame\n | GtkThinUpBox\n | GtkThinDownBox\n | GtkThinUpFrame\n | GtkThinDownFrame\n | GtkRoundUpBox\n | GtkRoundDownBox\n | GleamUpBox\n | GleamDownBox\n | GleamUpFrame\n | GleamDownFrame\n | GleamThinUpBox\n | GleamThinDownBox\n | GleamRoundUpBox\n | GleamRoundDownBox\n | FreeBoxtype\n deriving (Show)\ninstance Enum Boxtype where\n fromEnum NoBox = 0\n fromEnum FlatBox = 1\n fromEnum UpBox = 2\n fromEnum DownBox = 3\n fromEnum UpFrame = 4\n fromEnum DownFrame = 5\n fromEnum ThinUpBox = 6\n fromEnum ThinDownBox = 7\n fromEnum ThinUpFrame = 8\n fromEnum ThinDownFrame = 9\n fromEnum EngravedBox = 10\n fromEnum EmbossedBox = 11\n fromEnum EngravedFrame = 12\n fromEnum EmbossedFrame = 13\n fromEnum BorderBox = 14\n fromEnum ShadowBox = defineShadowBox_\n fromEnum BorderFrame = 16\n fromEnum ShadowFrame = defineShadowBox_ + 2\n fromEnum RoundedBox = defineRoundedBox_\n fromEnum RshadowBox = defineRshadowBox_\n fromEnum RoundedFrame = defineRoundedBox_ + 2\n fromEnum RFlatBox = defineRflatBox_\n fromEnum RoundUpBox = defineRoundUpBox_\n fromEnum RoundDownBox = defineRoundUpBox_ + 1\n fromEnum DiamondUpBox = defineDiamondBox_\n fromEnum DiamondDownBox = defineDiamondBox_ + 1\n fromEnum OvalBox = defineOvalBox_\n fromEnum OshadowBox = defineOvalBox_ + 1\n fromEnum OvalFrame = defineOvalBox_ + 2\n fromEnum FloatBox = defineOvalBox_ + 3\n fromEnum PlasticUpBox = definePlasticUpBox_\n fromEnum PlasticDownBox = definePlasticUpBox_ + 1\n fromEnum PlasticUpFrame = definePlasticUpBox_ + 2\n fromEnum PlasticDownFrame = definePlasticUpBox_ + 3\n fromEnum PlasticThinUpBox = definePlasticUpBox_ + 4\n fromEnum PlasticThinDownBox = definePlasticUpBox_ + 5\n fromEnum PlasticRoundUpBox = definePlasticUpBox_ + 6\n fromEnum PlasticRoundDownBox = definePlasticUpBox_ + 7\n fromEnum GtkUpBox = defineGtkUpBox_\n fromEnum GtkDownBox = defineGtkUpBox_ + 1\n fromEnum GtkUpFrame = defineGtkUpBox_ + 2\n fromEnum GtkDownFrame = defineGtkUpBox_ + 3\n fromEnum GtkThinUpBox = defineGtkUpBox_ + 4\n fromEnum GtkThinDownBox = defineGtkUpBox_ + 5\n fromEnum GtkThinUpFrame = defineGtkUpBox_ + 6\n fromEnum GtkThinDownFrame = defineGtkUpBox_ + 7\n fromEnum GtkRoundUpBox = defineGtkUpBox_ + 8\n fromEnum GtkRoundDownBox = defineGtkUpBox_ + 9\n fromEnum GleamUpBox = defineGleamUpBox_\n fromEnum GleamDownBox = defineGleamUpBox_ + 1\n fromEnum GleamUpFrame = defineGleamUpBox_ + 2\n fromEnum GleamDownFrame = defineGleamUpBox_ + 3\n fromEnum GleamThinUpBox = defineGleamUpBox_ + 4\n fromEnum GleamThinDownBox = defineGleamUpBox_ + 5\n fromEnum GleamRoundUpBox = defineGleamUpBox_ + 6\n fromEnum GleamRoundDownBox = defineGleamUpBox_ + 7\n fromEnum FreeBoxtype = 48\n\n toEnum 0 = NoBox\n toEnum 1 = FlatBox\n toEnum 2 = UpBox\n toEnum 3 = DownBox\n toEnum 4 = UpFrame\n toEnum 5 = DownFrame\n toEnum 6 = ThinUpBox\n toEnum 7 = ThinDownBox\n toEnum 8 = ThinUpFrame\n toEnum 9 = ThinDownFrame\n toEnum 10 = EngravedBox\n toEnum 11 = EmbossedBox\n toEnum 12 = EngravedFrame\n toEnum 13 = EmbossedFrame\n toEnum 14 = BorderBox\n toEnum 16 = BorderFrame\n toEnum 48 = FreeBoxtype\n toEnum x | x == defineShadowBox_ = ShadowBox\n | x == defineShadowBox_ + 2 = ShadowFrame\n | x == defineRoundedBox_ = RoundedBox\n | x == defineRshadowBox_ = RshadowBox\n | x == defineRoundedBox_ + 2 = RoundedFrame\n | x == defineRflatBox_ = RFlatBox\n | x == defineRoundUpBox_ = RoundUpBox\n | x == defineRoundUpBox_ + 1 = RoundDownBox\n | x == defineDiamondBox_ = DiamondUpBox\n | x == defineDiamondBox_ + 1 = DiamondDownBox\n | x == defineOvalBox_ = OvalBox\n | x == defineOvalBox_ + 1 = OshadowBox\n | x == defineOvalBox_ + 2 = OvalFrame\n | x == defineOvalBox_ + 3 = FloatBox\n | x == definePlasticUpBox_ = PlasticUpBox\n | x == definePlasticUpBox_ + 1 = PlasticDownBox\n | x == definePlasticUpBox_ + 2 = PlasticUpFrame\n | x == definePlasticUpBox_ + 3 = PlasticDownFrame\n | x == definePlasticUpBox_ + 4 = PlasticThinUpBox\n | x == definePlasticUpBox_ + 5 = PlasticThinDownBox\n | x == definePlasticUpBox_ + 6 = PlasticRoundUpBox\n | x == definePlasticUpBox_ + 7 = PlasticRoundDownBox\n | x == defineGtkUpBox_ = GtkUpBox\n | x == defineGtkUpBox_ + 1 = GtkDownBox\n | x == defineGtkUpBox_ + 2 = GtkUpFrame\n | x == defineGtkUpBox_ + 3 = GtkDownFrame\n | x == defineGtkUpBox_ + 4 = GtkThinUpBox\n | x == defineGtkUpBox_ + 5 = GtkThinDownBox\n | x == defineGtkUpBox_ + 6 = GtkThinUpFrame\n | x == defineGtkUpBox_ + 7 = GtkThinDownFrame\n | x == defineGtkUpBox_ + 8 = GtkRoundUpBox\n | x == defineGtkUpBox_ + 9 = GtkRoundDownBox\n | x == defineGleamUpBox_ = GleamUpBox\n | x == defineGleamUpBox_ + 1 = GleamDownBox\n | x == defineGleamUpBox_ + 2 = GleamUpFrame\n | x == defineGleamUpBox_ + 3 = GleamDownFrame\n | x == defineGleamUpBox_ + 4 = GleamThinUpBox\n | x == defineGleamUpBox_ + 5 = GleamThinDownBox\n | x == defineGleamUpBox_ + 6 = GleamRoundUpBox\n | x == defineGleamUpBox_ + 7 = GleamRoundDownBox\n | otherwise = error (\"Boxtype.toEnum: Cannot match \" ++ show otherwise)\nframe,frameBox, circleBox, diamondBox :: Boxtype\nframe = EngravedFrame\nframeBox = EngravedBox\ncircleBox = RoundDownBox\ndiamondBox = DiamondDownBox\n\n\n-- Fonts\nnewtype Font = Font Int deriving Show\ndata FontAttribute = Bold | Italic | BoldItalic deriving (Show, Enum)\ncFromFont :: Font -> CInt\ncFromFont (Font f) = fromIntegral f\ncToFont :: CInt -> Font\ncToFont f = Font (fromIntegral f)\n\ncFromFontAttribute :: FontAttribute -> CInt\ncFromFontAttribute Bold = cFromFont helveticaBold\ncFromFontAttribute Italic = cFromFont helveticaItalic\ncFromFontAttribute BoldItalic = cFromFont helveticaBoldItalic\n\ncToFontAttribute :: CInt -> Maybe FontAttribute\ncToFontAttribute attributeCode =\n case (attributeCode `has` helveticaBold, attributeCode `has` helveticaItalic) of\n (True,True) -> Just BoldItalic\n (True,False) -> Just Bold\n (False,True) -> Just Italic\n (False,False) -> Nothing\n where\n has :: CInt -> Font -> Bool\n has code (Font f) = code .&. (fromIntegral f) \/= 0\nhelvetica :: Font\nhelvetica = Font 0\nhelveticaBold :: Font\nhelveticaBold = Font 1\nhelveticaItalic :: Font\nhelveticaItalic = Font 2\nhelveticaBoldItalic :: Font\nhelveticaBoldItalic = Font 3\ncourier :: Font\ncourier = Font 4\ncourierBold :: Font\ncourierBold = Font 5\ncourierItalic :: Font\ncourierItalic = Font 6\ncourierBoldItalic :: Font\ncourierBoldItalic = Font 7\ntimes :: Font\ntimes = Font 8\ntimesBold :: Font\ntimesBold = Font 9\ntimesItalic :: Font\ntimesItalic = Font 10\ntimesBoldItalic :: Font\ntimesBoldItalic = Font 11\nsymbol :: Font\nsymbol = Font 12\nscreen :: Font\nscreen = Font 13\nscreenBold :: Font\nscreenBold = Font 14\nzapfDingbats :: Font\nzapfDingbats = Font 15\nfreeFont :: Font\nfreeFont = Font 16\n\n-- Colors\n\nnewtype Color = Color CUInt deriving Show\nforegroundColor :: Color\nforegroundColor = Color 0\nbackground2Color :: Color\nbackground2Color = Color 7\ninactiveColor :: Color\ninactiveColor = Color 8\nselectionColor :: Color\nselectionColor = Color 15\ngray0Color :: Color\ngray0Color = Color 32\ndark3Color :: Color\ndark3Color = Color 39\ndark2Color :: Color\ndark2Color = Color 45\ndark1Color :: Color\ndark1Color = Color 47\nbackgroundColor :: Color\nbackgroundColor = Color 49\nlight1Color :: Color\nlight1Color = Color 50\nlight2Color :: Color\nlight2Color = Color 52\nlight3Color :: Color\nlight3Color = Color 54\nblackColor :: Color\nblackColor = Color 56\nredColor :: Color\nredColor = Color 88\ngreenColor :: Color\ngreenColor = Color 63\nyellowColor :: Color\nyellowColor = Color 95\nblueColor :: Color\nblueColor = Color 216\nmagentaColor :: Color\nmagentaColor = Color 248\ncyanColor :: Color\ncyanColor = Color 223\ndarkRedColor :: Color\ndarkRedColor = Color 72\ndarkGreenColor :: Color\ndarkGreenColor = Color 60\ndarkYellowColor :: Color\ndarkYellowColor = Color 76\ndarkBlueColor :: Color\ndarkBlueColor = Color 136\ndarkMagentaColor :: Color\ndarkMagentaColor = Color 152\ndarkCyanColor :: Color\ndarkCyanColor = Color 140\nwhiteColor :: Color\nwhiteColor = Color 255\nfreeColor :: Color\nfreeColor = Color 16\nnumFreeColor :: Color\nnumFreeColor =Color 16\ngrayRampColor :: Color\ngrayRampColor = Color 32\nnumGray:: Color\nnumGray= Color 24\ngrayColor :: Color\ngrayColor = backgroundColor\ncolorCubeColor :: Color\ncolorCubeColor = Color 56\nnumRed :: Color\nnumRed = Color 5\nnumGreen :: Color\nnumGreen = Color 8\nnumBlue :: Color\nnumBlue = Color 5\n\n-- Fl_LabelType\n\ndata Labeltype = NormalLabel\n | NoLabel\n | ShadowLabel\n | EngravedLabel\n | EmbossedLabel\n | FreeLabelType deriving Show\n\ninstance Enum Labeltype where\n fromEnum NormalLabel = 0\n fromEnum NoLabel = 1\n fromEnum ShadowLabel = defineShadowLabel_\n fromEnum EngravedLabel = defineEngravedLabel_\n fromEnum EmbossedLabel = defineEmbossedLabel_\n fromEnum FreeLabelType = 8\n\n toEnum 0 = NormalLabel\n toEnum 1 = NoLabel\n toEnum x | x == defineShadowLabel_ = ShadowLabel\n | x == defineEngravedLabel_ = EngravedLabel\n | x == defineEmbossedLabel_ = EmbossedLabel\n toEnum 8 = FreeLabelType\n\nsymbolLabel :: Labeltype\nsymbolLabel = NormalLabel\n\ndefineRoundUpBox_ :: (Num a) => a\ndefineRoundUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_ROUND_UP_BOXC #}\n\ndefineRoundUpBox :: Boxtype\ndefineRoundUpBox =\n toEnum defineRoundUpBox_\n\ndefineShadowBox_ :: (Num a) => a\ndefineShadowBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_SHADOW_BOXC #}\n\ndefineShadowBox :: Boxtype\ndefineShadowBox =\n toEnum defineShadowBox_\n\ndefineRoundedBox_ :: (Num a) => a\ndefineRoundedBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_ROUNDED_BOXC #}\ndefineRoundedBox :: Boxtype\ndefineRoundedBox = toEnum defineRoundedBox_\n\ndefineRflatBox_ :: (Num a) => a\ndefineRflatBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_RFLAT_BOXC #}\ndefineRflatBox :: Boxtype\ndefineRflatBox = toEnum defineRflatBox_\n\ndefineRshadowBox_ :: (Num a) => a\ndefineRshadowBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_RSHADOW_BOXC #}\ndefineRshadowBox :: Boxtype\ndefineRshadowBox = toEnum defineRshadowBox_\n\ndefineDiamondBox_ :: (Num a) => a\ndefineDiamondBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_DIAMOND_BOXC #}\ndefineDiamondBox :: Boxtype\ndefineDiamondBox = toEnum defineDiamondBox_\n\ndefineOvalBox_ :: (Num a) => a\ndefineOvalBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_OVAL_BOXC #}\ndefineOvalBox :: Boxtype\ndefineOvalBox = toEnum defineOvalBox_\n\ndefinePlasticUpBox_ :: (Num a) => a\ndefinePlasticUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_PLASTIC_UP_BOXC #}\ndefinePlasticUpBox :: Boxtype\ndefinePlasticUpBox = toEnum definePlasticUpBox_\n\ndefineGtkUpBox_ :: (Num a) => a\ndefineGtkUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_GTK_UP_BOXC #}\ndefineGtkUpBox :: Boxtype\ndefineGtkUpBox = toEnum defineGtkUpBox_\n\ndefineGleamUpBox_ :: (Num a ) => a\ndefineGleamUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_GLEAM_UP_BOXC #}\n\ndefineShadowLabel_ :: (Num a) => a\ndefineShadowLabel_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_SHADOW_LABELC #}\ndefineShadowLabel :: Labeltype\ndefineShadowLabel = toEnum defineShadowLabel_\n\ndefineEngravedLabel_ :: (Num a) => a\ndefineEngravedLabel_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_ENGRAVED_LABELC #}\n\ndefineEngravedLabel :: Labeltype\ndefineEngravedLabel = toEnum defineEngravedLabel_\n\ndefineEmbossedLabel_ :: (Num a) => a\ndefineEmbossedLabel_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_EMBOSSED_LABELC #}\n\ndefineEmbossedLabel :: Labeltype\ndefineEmbossedLabel = toEnum defineEmbossedLabel_\n\ncFromColor :: Color -> CUInt\ncFromColor (Color c) = fromIntegral c\ncToColor :: CUInt-> Color\ncToColor c = Color (fromIntegral c)\n\ntype RGB = (CUChar, CUChar, CUChar)\n\n{#fun pure fl_inactiveC as\n inactive {cFromColor `Color' } -> `Color' cToColor#}\n{#fun pure fl_contrastC as\n contrast {cFromColor `Color',cFromColor `Color'}\n -> `Color' cToColor#}\n{#fun pure fl_color_averageC as\n color_average {cFromColor `Color',\n cFromColor `Color',\n realToFrac `Double'}\n -> `Color' cToColor#}\n{#fun pure fl_lighterC as\n lighter {cFromColor `Color'} -> `Color' cToColor#}\n{#fun pure fl_darkerC as\n darker {cFromColor `Color'} -> `Color' cToColor#}\n{#fun fl_rgb_color_with_rgbC as\n rgbColorWithRgb' {id `CUChar',\n id `CUChar',\n id `CUChar'}\n -> `CUInt' #}\nrgbColorWithRgb :: RGB -> IO Color\nrgbColorWithRgb (r,g,b) = rgbColorWithRgb' r g b >>= return . Color\n\n{#fun pure fl_rgb_color_with_grayscaleC as\n rgbColorWithGrayscale {castCharToCUChar `Char'}\n -> `Color' cToColor#}\n{#fun pure fl_gray_rampC as grayRamp {`Int'} -> `Color' cToColor#}\n{#fun pure fl_color_cubeC as colorCube {`Int',`Int',`Int'}\n -> `Color' cToColor#}\n","old_contents":"{-# LANGUAGE CPP #-}\n#include \"Fl_C.h\"\n#include \"Fl_EnumerationsC.h\"\nmodule Graphics.UI.FLTK.LowLevel.Fl_Enumerations\n (\n -- * Events\n Event(..),\n When(..),\n FdWhen(..),\n -- * Tree Attributes\n TreeSort(..),\n TreeConnector(..),\n TreeSelect(..),\n SearchDirection(..),\n#if FLTK_ABI_VERSION >= 10302\n TreeItemReselectMode(..),\n TreeItemDrawMode(..),\n#endif\n -- * Keyboard and mouse codes\n SpecialKey(..),\n allSpecialKeys,\n allShortcutSpecialKeys,\n MouseButton(..),\n EventState(..),\n KeyboardKeyMask(..),\n MouseButtonsMask(..),\n allEventStates,\n kb_CommandState, kb_ControlState, kb_KpLast,\n -- * Widget damage types\n Damage(..),\n -- * Cursor type\n Cursor(..),\n#ifdef GLSUPPORT\n -- * Glut attributes\n GlutDraw(..),\n GlutMouseCodes(..),\n GlutUpDown(..),\n GlutVisibility(..),\n GlutMenuProperties(..),\n GlutEnteredLeft(..),\n GlutKeyboardCodes(..),\n GlutConstants(..),\n GlutWindowProperties(..),\n GlutCursor(..),\n glutCursorFullCrossHair,\n -- * Various modes\n Mode(..),\n Modes(..),\n single,\n allModes,\n#endif\n -- * Alignment\n Alignments(..),\n AlignType(..),\n alignCenter,\n alignTop,\n alignBottom,\n alignLeft,\n alignRight,\n alignInside,\n alignTextOverImage,\n alignClip,\n alignWrap,\n alignImageNextToText,\n alignTextNextToImage,\n alignImageBackdrop,\n alignLeftTop,\n alignRightTop,\n alignLeftBottom,\n alignRightBottom,\n alignPositionMask,\n alignImageMask,\n alignNoWrap,\n alignImageOverText,\n alignTopLeft,\n alignTopRight,\n alignBottomLeft,\n alignBottomRight,\n allAlignTypes,\n allWhen,\n -- * Box types\n Boxtype(..),\n frame,frameBox, circleBox, diamondBox,\n -- * Box functions\n defineRoundUpBox,\n defineShadowBox,\n defineRoundedBox,\n defineRflatBox,\n defineRshadowBox,\n defineDiamondBox,\n defineOvalBox,\n definePlasticUpBox,\n defineGtkUpBox,\n -- * Fonts\n Font(..),\n FontAttribute(..),\n -- ** (Un-)marshalling\n cFromFont,\n cToFont,\n cFromFontAttribute,\n cToFontAttribute,\n -- ** Font Names\n helvetica,\n helveticaBold,\n helveticaItalic,\n helveticaBoldItalic,\n courier,\n courierBold,\n courierItalic,\n courierBoldItalic,\n times,\n timesBold,\n timesItalic,\n timesBoldItalic,\n symbol,\n screen,\n screenBold,\n zapfDingbats,\n freeFont,\n\n -- * Colors\n Color(..),\n -- ** (Un-)marshalling\n cFromColor,\n cToColor,\n -- ** Various Color Functions\n inactive,\n contrast,\n color_average,\n lighter,\n darker,\n rgbColorWithRgb,\n rgbColorWithGrayscale,\n grayRamp,\n colorCube,\n -- ** Color Names\n foregroundColor,\n background2Color,\n inactiveColor,\n selectionColor,\n gray0Color,\n dark3Color,\n dark2Color,\n dark1Color,\n backgroundColor,\n light1Color,\n light2Color,\n light3Color,\n blackColor,\n redColor,\n greenColor,\n yellowColor,\n blueColor,\n magentaColor,\n cyanColor,\n darkRedColor,\n darkGreenColor,\n darkYellowColor,\n darkBlueColor,\n darkMagentaColor,\n darkCyanColor,\n whiteColor,\n freeColor,\n numFreeColor,\n grayRampColor,\n numGray,\n grayColor,\n colorCubeColor,\n numRed,\n numGreen,\n numBlue,\n -- * Labels\n Labeltype(..),\n symbolLabel,\n defineShadowLabel,\n defineEngravedLabel,\n defineEmbossedLabel,\n -- * Color\n RGB\n )\nwhere\nimport C2HS\n#c\nenum VersionInfo {\n MajorVersion = FL_MAJOR_VERSION,\n MinorVersion = FL_MINOR_VERSION,\n PatchVersion = FL_PATCH_VERSION,\n Version = FL_VERSION\n};\nenum Event {\n NoEvent = FL_NO_EVENT,\n Push = FL_PUSH,\n Release = FL_RELEASE,\n Enter = FL_ENTER,\n Leave = FL_LEAVE,\n Drag = FL_DRAG,\n Focus = FL_FOCUS,\n Unfocus = FL_UNFOCUS,\n Keydown = FL_KEYDOWN,\n \/\/ FL_KEYBOARD same as above,\n Keyup = FL_KEYUP,\n Close = FL_CLOSE,\n Move = FL_MOVE,\n Shortcut = FL_SHORTCUT,\n Deactivate = FL_DEACTIVATE,\n Activate = FL_ACTIVATE,\n Hide = FL_HIDE,\n Show = FL_SHOW,\n Paste = FL_PASTE,\n Selectionclear = FL_SELECTIONCLEAR,\n Mousewheel = FL_MOUSEWHEEL,\n DndEnter = FL_DND_ENTER,\n DndDrag = FL_DND_DRAG,\n DndLeave = FL_DND_LEAVE,\n DndRelease = FL_DND_RELEASE,\n ScreenConfigurationChanged = FL_SCREEN_CONFIGURATION_CHANGED,\n Fullscreen = FL_FULLSCREEN\n};\nenum When {\n WhenNever = FL_WHEN_NEVER,\n WhenChanged = FL_WHEN_CHANGED,\n WhenNotChanged = FL_WHEN_NOT_CHANGED,\n WhenRelease = FL_WHEN_RELEASE,\n WhenReleaseAlways= FL_WHEN_RELEASE_ALWAYS,\n WhenEnterKey = FL_WHEN_ENTER_KEY,\n WhenEnterKeyAlways = FL_WHEN_ENTER_KEY_ALWAYS,\n WhenEnterKeyChanged = FL_WHEN_ENTER_KEY_CHANGED\n};\n\nenum TabsWhen {\n TabsWhenNever = FL_WHEN_NEVER,\n TabsWhenChanged = FL_WHEN_CHANGED,\n TabsWhenNotChanged = FL_WHEN_NOT_CHANGED,\n TabsWhenRelease = FL_WHEN_RELEASE\n};\n\nenum FdWhen {\n CanRead = FL_READ,\n CanWrite = FL_WRITE,\n OnExcept = FL_EXCEPT\n};\nenum TreeSort{\n TreeSortNone = FL_TREE_SORT_NONE,\n TreeSortAscending = FL_TREE_SORT_ASCENDING,\n TreeSortDescending = FL_TREE_SORT_DESCENDING\n};\nenum TreeConnector{\n TreeConnectorNone = FL_TREE_CONNECTOR_NONE,\n TreeConnectorDotted = FL_TREE_CONNECTOR_DOTTED,\n TreeConnectorSolid = FL_TREE_CONNECTOR_SOLID\n};\nenum TreeSelect{\n TreeSelectNone = FL_TREE_SELECT_NONE,\n TreeSelectSingle = FL_TREE_SELECT_SINGLE,\n TreeSelectMulti = FL_TREE_SELECT_MULTI,\n TreeSelectSingleDraggable = FL_TREE_SELECT_SINGLE_DRAGGABLE\n};\nenum SearchDirection {\n SearchDirectionDown = FL_Down,\n SearchDirectionUp = FL_Up\n};\n#if FLTK_ABI_VERSION >= 10302\nenum TreeItemReselectMode{\n TreeSelectableOnce = FL_TREE_SELECTABLE_ONCE,\n TreeSelectableAlways = FL_TREE_SELECTABLE_ALWAYS\n};\nenum TreeItemDrawMode{\n TreeItemDrawDefault = FL_TREE_ITEM_DRAW_DEFAULT,\n TreeItemDrawLabelAndWidget = FL_TREE_ITEM_DRAW_LABEL_AND_WIDGET,\n TreeItemHeightFromWidget = FL_TREE_ITEM_HEIGHT_FROM_WIDGET\n};\n#endif\nenum SpecialKey {\n Button = FL_Button,\n Kb_Clear = FL_Clear,\n Kb_Backspace = FL_BackSpace,\n Kb_Tab = FL_Tab,\n Kb_IsoKey = FL_Iso_Key,\n Kb_Enter = FL_Enter,\n Kb_Pause = FL_Pause,\n Kb_Escape = FL_Escape,\n Kb_Kana = FL_Kana,\n Kb_Eisu = FL_Eisu,\n Kb_Yen = FL_Yen,\n Kb_JisUnderscore = FL_JIS_Underscore,\n Kb_Home = FL_Home,\n Kb_Left = FL_Left,\n Kb_Up = FL_Up,\n Kb_Right = FL_Right,\n Kb_Down = FL_Down,\n Kb_PageUp = FL_Page_Up,\n Kb_PageDown = FL_Page_Down,\n Kb_End = FL_End,\n Kb_Print = FL_Print,\n Kb_Insert = FL_Insert,\n Kb_Menu = FL_Menu,\n Kb_Help = FL_Help,\n Kb_Kp = FL_KP,\n Kb_KpEnter = FL_KP_Enter,\n Kb_F = FL_F,\n Kb_Flast = FL_F_Last,\n Kb_ShiftL = FL_Shift_L,\n Kb_ShiftR = FL_Shift_R,\n Kb_ControlL = FL_Control_L,\n Kb_ControlR = FL_Control_R,\n Kb_CapsLock = FL_Caps_Lock,\n Kb_MetaL = FL_Meta_L,\n Kb_MetaR = FL_Meta_R,\n Kb_AltL = FL_Alt_L,\n Kb_AltR = FL_Alt_R,\n Kb_Delete = FL_Delete,\n Kb_VolumeDown = FL_Volume_Down,\n Kb_VolumeMute = FL_Volume_Mute,\n Kb_VolumeUp = FL_Volume_Up,\n Kb_MediaPlay = FL_Media_Play,\n Kb_MediaStop = FL_Media_Stop,\n Kb_MediaPrev = FL_Media_Prev,\n Kb_MediaNext = FL_Media_Next,\n Kb_HomePage = FL_Home_Page,\n Kb_Mail = FL_Mail,\n Kb_Search = FL_Search,\n Kb_Back = FL_Back,\n Kb_Forward = FL_Forward,\n Kb_Stop = FL_Stop,\n Kb_Refresh = FL_Refresh,\n Kb_Sleep = FL_Sleep,\n Kb_Favorites = FL_Favorites,\n};\nenum MouseButton {\n Mouse_Left = FL_LEFT_MOUSE,\n Mouse_Middle = FL_MIDDLE_MOUSE,\n Mouse_Right = FL_RIGHT_MOUSE,\n};\nenum EventState {\n Kb_ShiftState = FL_SHIFT,\n Kb_CapsLockState = FL_CAPS_LOCK,\n Kb_CtrlState = FL_CTRL,\n Kb_AltState = FL_ALT,\n Kb_NumLockState = FL_NUM_LOCK,\n Kb_MetaState = FL_META,\n Kb_ScrollLockState = FL_SCROLL_LOCK,\n Mouse_Button1State = FL_BUTTON1,\n Mouse_Button2State = FL_BUTTON2,\n Mouse_Button3State= FL_BUTTON3,\n};\nenum KeyboardKeyMask {\n Kb_KeyMask = FL_KEY_MASK\n};\nenum MouseButtonsMask {\n Mouse_ButtonsMask = FL_BUTTONS,\n};\nenum Damage {\n DamageChild = FL_DAMAGE_CHILD,\n DamageExpose = FL_DAMAGE_EXPOSE,\n DamageScroll = FL_DAMAGE_SCROLL,\n DamageOverlay = FL_DAMAGE_OVERLAY,\n DamageUser1 = FL_DAMAGE_USER1,\n DamageUser2 = FL_DAMAGE_USER2,\n DamageAll = FL_DAMAGE_ALL\n};\n#ifdef GLSUPPORT\nenum GlutDraw {\n GlutNormal = GLUT_NORMAL,\n GlutOverlay = GLUT_OVERLAY\n};\nenum GlutMouseCodes {\n GlutLeftButton = GLUT_LEFT_BUTTON,\n GlutRightButton = GLUT_RIGHT_BUTTON,\n GlutMiddleButton = GLUT_MIDDLE_BUTTON\n};\nenum GlutUpDown {\n GlutUp = GLUT_UP,\n GlutDown = GLUT_DOWN\n};\nenum GlutVisibility {\n GlutVisible = GLUT_VISIBLE,\n GlutNotVisible = GLUT_NOT_VISIBLE\n};\nenum GlutMenuProperties {\n GlutMenuNotInUse = GLUT_MENU_NOT_IN_USE,\n GlutMenuInUse = GLUT_MENU_IN_USE,\n GlutMenuNumItems = GLUT_MENU_NUM_ITEMS\n};\nenum GlutEnteredLeft {\n GlutEntered = GLUT_ENTERED,\n GlutLeft = GLUT_LEFT\n};\nenum GlutKeyboardCodes {\n GlutKeyF1 = GLUT_KEY_F1,\n GlutKeyF2 = GLUT_KEY_F2,\n GlutKeyF3 = GLUT_KEY_F3,\n GlutKeyF4 = GLUT_KEY_F4,\n GlutKeyF5 = GLUT_KEY_F5,\n GlutKeyF6 = GLUT_KEY_F6,\n GlutKeyF7 = GLUT_KEY_F7,\n GlutKeyF8 = GLUT_KEY_F8,\n GlutKeyF9 = GLUT_KEY_F9,\n GlutKeyF10 = GLUT_KEY_F10,\n GlutKeyF11 = GLUT_KEY_F11,\n GlutKeyF12 = GLUT_KEY_F12,\n GlutKeyLeft = GLUT_KEY_LEFT,\n GlutKeyUp = GLUT_KEY_UP,\n GlutKeyRight = GLUT_KEY_RIGHT,\n GlutKeyDown = GLUT_KEY_DOWN,\n GlutKeyPageUp = GLUT_KEY_PAGE_UP,\n GlutKeyPageDown = GLUT_KEY_PAGE_DOWN,\n GlutKeyHome = GLUT_KEY_HOME,\n GlutKeyEnd = GLUT_KEY_END,\n GlutKeyInsert = GLUT_KEY_INSERT,\n GlutActiveShift = GLUT_ACTIVE_SHIFT,\n GlutActiveCtrl = GLUT_ACTIVE_CTRL,\n GlutActiveAlt = GLUT_ACTIVE_ALT\n};\nenum GlutConstants {\n GlutReturnZero = GLUT_RETURN_ZERO,\n GlutDisplayModePossible = GLUT_DISPLAY_MODE_POSSIBLE,\n GlutVersion = GLUT_VERSION,\n GlutOverlayPossible = GLUT_OVERLAY_POSSIBLE,\n GlutTransparentIndex = GLUT_TRANSPARENT_INDEX,\n GlutNormalDamaged = GLUT_NORMAL_DAMAGED,\n GlutOverlayDamaged = GLUT_OVERLAY_DAMAGED\n};\nenum GlutWindowProperties {\n GlutWindowX = GLUT_WINDOW_X,\n GlutWindowY = GLUT_WINDOW_Y,\n GlutWindowWidth = GLUT_WINDOW_WIDTH,\n GlutWindowHeight = GLUT_WINDOW_HEIGHT,\n GlutWindowParent = GLUT_WINDOW_PARENT,\n GlutScreenWidth = GLUT_SCREEN_WIDTH,\n GlutScreenHeight = GLUT_SCREEN_HEIGHT,\n GlutInitWindowX = GLUT_INIT_WINDOW_X,\n GlutInitWindowY = GLUT_INIT_WINDOW_Y,\n GlutInitWindowWidth = GLUT_INIT_WINDOW_WIDTH,\n GlutInitWindowHeight = GLUT_INIT_WINDOW_HEIGHT,\n GlutInitDisplayMode = GLUT_INIT_DISPLAY_MODE,\n GlutWindowBufferSize = GLUT_WINDOW_BUFFER_SIZE,\n GlutWindowStencilSize = GLUT_WINDOW_STENCIL_SIZE,\n GlutWindowDepthSize = GLUT_WINDOW_DEPTH_SIZE,\n GlutWindowRedSize = GLUT_WINDOW_RED_SIZE,\n GlutWindowGreenSize = GLUT_WINDOW_GREEN_SIZE,\n GlutWindowBlueSize = GLUT_WINDOW_BLUE_SIZE,\n GlutWindowAlphaSize = GLUT_WINDOW_ALPHA_SIZE,\n GlutWindowAccumRedSize = GLUT_WINDOW_ACCUM_RED_SIZE,\n GlutWindowAccumGreenSize = GLUT_WINDOW_ACCUM_GREEN_SIZE,\n GlutWindowAccumBlueSize = GLUT_WINDOW_ACCUM_BLUE_SIZE,\n GlutWindowAccumAlphaSize = GLUT_WINDOW_ACCUM_ALPHA_SIZE,\n GlutWindowDoublebuffer = GLUT_WINDOW_DOUBLEBUFFER,\n GlutWindowRgba = GLUT_WINDOW_RGBA,\n GlutWindowColormapSize = GLUT_WINDOW_COLORMAP_SIZE,\n GlutWindowNumSamples = GLUT_WINDOW_NUM_SAMPLES,\n GlutWindowStereo = GLUT_WINDOW_STEREO\n};\nenum GlutCursor {\n GlutCursorRightArrow = 2,\n GlutCursorLeftArrow = 67,\n GlutCursorDestroy = 45,\n GlutCursorCycle = 26,\n GlutCursorSpray = 63,\n GlutCursorInfo = FL_CURSOR_HAND,\n GlutCursorHelp = FL_CURSOR_HELP,\n GlutCursorWait = FL_CURSOR_WAIT,\n GlutCursorText = FL_CURSOR_INSERT,\n GlutCursorLeftRight = FL_CURSOR_WE,\n GlutCursorTopSide = FL_CURSOR_N,\n GlutCursorBottomSide = FL_CURSOR_S,\n GlutCursorLeftSide = FL_CURSOR_W,\n GlutCursorRightSide = FL_CURSOR_E,\n GlutCursorTopLeftCorner = FL_CURSOR_NW,\n GlutCursorTopRightCorner = FL_CURSOR_NE,\n GlutCursorBottomRightCorner = FL_CURSOR_SE,\n GlutCursorBottomLeftCorner = FL_CURSOR_SW,\n GlutCursorInherit = FL_CURSOR_DEFAULT,\n GlutCursorNone = FL_CURSOR_NONE,\n GlutCursorUpDown = FL_CURSOR_NS,\n GlutCursorCrosshair = FL_CURSOR_CROSS\n};\n#endif\nenum Cursor {\n CursorDefault = FL_CURSOR_DEFAULT,\n CursorArrow = FL_CURSOR_ARROW,\n CursorCross = FL_CURSOR_CROSS,\n CursorWait = FL_CURSOR_WAIT,\n CursorInsert = FL_CURSOR_INSERT,\n CursorHand = FL_CURSOR_HAND,\n CursorHelp = FL_CURSOR_HELP,\n CursorMove = FL_CURSOR_MOVE,\n CursorNS = FL_CURSOR_NS,\n CursorWE = FL_CURSOR_WE,\n CursorNWSE = FL_CURSOR_NWSE,\n CursorNesw = FL_CURSOR_NESW,\n CursorNone = FL_CURSOR_NONE,\n CursorN = FL_CURSOR_N,\n CursorNE = FL_CURSOR_NE,\n CursorE = FL_CURSOR_E,\n CursorSE = FL_CURSOR_SE,\n CursorS = FL_CURSOR_S,\n CursorSW = FL_CURSOR_SW,\n CursorW = FL_CURSOR_W,\n CursorNW = FL_CURSOR_NW\n};\nenum Mode {\n ModeRGB = FL_RGB,\n ModeRGB8 = FL_RGB8,\n ModeIndex = FL_INDEX,\n ModeDouble = FL_DOUBLE,\n ModeAccum = FL_ACCUM,\n ModeAlpha = FL_ALPHA,\n ModeDepth = FL_DEPTH,\n ModeStencil = FL_STENCIL,\n ModeMultisample = FL_MULTISAMPLE,\n ModeStereo = FL_STEREO,\n ModeFakeSingle = FL_FAKE_SINGLE\n#if FLTK_API_VERSION >= 10304\n , ModeOpenGL3 = FL_OPENGL3\n#endif\n};\nenum AlignType {\n AlignTypeCenter = 0,\n AlignTypeTop = 1,\n AlignTypeBottom = 2,\n AlignTypeLeft = 4,\n AlignTypeRight = 8,\n AlignTypeInside = 16,\n AlignTypeTextOverImage = 0x0020,\n AlignTypeClip = 64,\n AlignTypeWrap = 128,\n AlignTypeImageNextToText = 0x0100,\n AlignTypeTextNextToImage = 0x0120,\n AlignTypeImageBackdrop = 0x0200,\n AlignTypeLeftTop = 0x0007,\n AlignTypeRightTop = 0x000b,\n AlignTypeLeftBottom = 0x000d,\n AlignTypeRightBottom = 0x000e,\n};\n#endc\n{#enum Event {} deriving (Show, Eq) #}\n{#enum When {} deriving (Show, Eq, Ord) #}\n{#enum FdWhen {} deriving (Show, Eq, Ord) #}\n{#enum TreeSort {} deriving (Show, Eq) #}\n{#enum TreeConnector {} deriving (Show, Eq) #}\n{#enum TreeSelect {} deriving (Show, Eq) #}\n{#enum SearchDirection {} deriving (Show, Eq) #}\n#if FLTK_ABI_VERSION >= 10302\n{#enum TreeItemReselectMode {} deriving (Show, Eq) #}\n{#enum TreeItemDrawMode {} deriving (Show, Eq) #}\n#endif\n{#enum SpecialKey {} deriving (Show, Eq) #}\n\nallShortcutSpecialKeys :: [CInt]\nallShortcutSpecialKeys = [\n fromIntegral $ fromEnum (Kb_Backspace),\n fromIntegral $ fromEnum (Kb_Tab),\n fromIntegral $ fromEnum (Kb_Clear),\n fromIntegral $ fromEnum (Kb_Enter),\n fromIntegral $ fromEnum (Kb_Pause),\n fromIntegral $ fromEnum (Kb_ScrollLockState),\n fromIntegral $ fromEnum (Kb_Escape),\n fromIntegral $ fromEnum (Kb_Home),\n fromIntegral $ fromEnum (Kb_Left),\n fromIntegral $ fromEnum (Kb_Up),\n fromIntegral $ fromEnum (Kb_Right),\n fromIntegral $ fromEnum (Kb_Down),\n fromIntegral $ fromEnum (Kb_PageUp),\n fromIntegral $ fromEnum (Kb_PageDown),\n fromIntegral $ fromEnum (Kb_End),\n fromIntegral $ fromEnum (Kb_Print),\n fromIntegral $ fromEnum (Kb_Insert),\n fromIntegral $ fromEnum (Kb_Menu),\n fromIntegral $ fromEnum (Kb_NumLockState),\n fromIntegral $ fromEnum (Kb_KpEnter),\n fromIntegral $ fromEnum (Kb_ShiftL),\n fromIntegral $ fromEnum (Kb_ShiftR),\n fromIntegral $ fromEnum (Kb_ControlL),\n fromIntegral $ fromEnum (Kb_ControlR),\n fromIntegral $ fromEnum (Kb_CapsLock),\n fromIntegral $ fromEnum (Kb_MetaL),\n fromIntegral $ fromEnum (Kb_MetaR),\n fromIntegral $ fromEnum (Kb_AltL),\n fromIntegral $ fromEnum (Kb_AltR),\n fromIntegral $ fromEnum (Kb_Delete)\n ]\n\nallSpecialKeys :: [SpecialKey]\nallSpecialKeys = [\n Button,\n Kb_Backspace,\n Kb_Clear,\n Kb_Tab,\n Kb_IsoKey,\n Kb_Enter,\n Kb_Pause,\n Kb_Escape,\n Kb_Kana,\n Kb_Eisu,\n Kb_Yen,\n Kb_JisUnderscore,\n Kb_Home,\n Kb_Left,\n Kb_Up,\n Kb_Right,\n Kb_Down,\n Kb_PageUp,\n Kb_PageDown,\n Kb_End,\n Kb_Print,\n Kb_Insert,\n Kb_Menu,\n Kb_Help,\n Kb_Kp,\n Kb_KpEnter,\n Kb_F,\n Kb_Flast,\n Kb_ShiftL,\n Kb_ShiftR,\n Kb_ControlL,\n Kb_ControlR,\n Kb_CapsLock,\n Kb_MetaL,\n Kb_MetaR,\n Kb_AltL,\n Kb_AltR,\n Kb_Delete,\n Kb_VolumeDown,\n Kb_VolumeMute,\n Kb_VolumeUp,\n Kb_MediaPlay,\n Kb_MediaStop,\n Kb_MediaPrev,\n Kb_MediaNext,\n Kb_HomePage,\n Kb_Mail,\n Kb_Search,\n Kb_Back,\n Kb_Forward,\n Kb_Stop,\n Kb_Refresh,\n Kb_Sleep,\n Kb_Favorites\n ]\n\n{#enum MouseButton {} deriving (Show, Eq) #}\n{#enum EventState {} deriving (Show, Eq, Ord) #}\n{#enum KeyboardKeyMask {} deriving (Show, Eq, Ord) #}\n{#enum MouseButtonsMask {} deriving (Show, Eq, Ord) #}\nkb_CommandState, kb_ControlState :: EventState\n#ifdef __APPLE__\nkb_CommandState = Kb_MetaState\nkb_ControlState = Kb_CtrlState\n#else\nkb_CommandState = Kb_CtrlState\nkb_ControlState = Kb_MetaState\n#endif\nkb_KpLast :: SpecialKey\nkb_KpLast = Kb_F\n{#enum Damage {} deriving (Show) #}\n{#enum Cursor {} deriving (Show) #}\n#ifdef GLSUPPORT\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutDraw {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutMouseCodes {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutUpDown {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutVisibility {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutMenuProperties {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutEnteredLeft {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutKeyboardCodes {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutConstants {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutWindowProperties {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum GlutCursor {} deriving (Show) #}\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\nglutCursorFullCrossHair :: GlutCursor\nglutCursorFullCrossHair = GlutCursorCrosshair\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{#enum Mode {} deriving (Show,Eq,Ord) #}\n-- Fl_Mode Aliases\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\nsingle :: Mode\nsingle = ModeRGB\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\nnewtype Modes = Modes [Mode] deriving (Show,Eq,Ord)\n-- | Only available if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\nallModes :: [Mode]\nallModes =\n [\n ModeRGB,\n ModeIndex,\n ModeDouble,\n ModeAccum,\n ModeAlpha,\n ModeDepth,\n ModeStencil,\n ModeRGB8,\n ModeMultisample,\n ModeStereo,\n ModeFakeSingle\n#if FLTK_API_VERSION >= 10304\n , ModeOpenGL3\n#endif\n ]\n#endif \/* GLSUPPORT *\/\n\n{#enum AlignType {} deriving (Show, Eq, Ord) #}\nnewtype Alignments = Alignments [AlignType] deriving Show\nalignCenter :: Alignments\nalignCenter = Alignments [AlignTypeCenter]\nalignTop :: Alignments\nalignTop = Alignments [AlignTypeTop]\nalignBottom :: Alignments\nalignBottom = Alignments [AlignTypeBottom]\nalignLeft :: Alignments\nalignLeft = Alignments [AlignTypeLeft]\nalignRight :: Alignments\nalignRight = Alignments [AlignTypeRight]\nalignInside :: Alignments\nalignInside = Alignments [AlignTypeInside]\nalignTextOverImage :: Alignments\nalignTextOverImage = Alignments [AlignTypeTextOverImage]\nalignClip :: Alignments\nalignClip = Alignments [AlignTypeClip]\nalignWrap :: Alignments\nalignWrap = Alignments [AlignTypeWrap]\nalignImageNextToText :: Alignments\nalignImageNextToText = Alignments [AlignTypeImageNextToText]\nalignTextNextToImage :: Alignments\nalignTextNextToImage = Alignments [AlignTypeTextNextToImage]\nalignImageBackdrop :: Alignments\nalignImageBackdrop = Alignments [AlignTypeImageBackdrop]\nalignLeftTop :: Alignments\nalignLeftTop = Alignments [AlignTypeLeftTop]\nalignRightTop :: Alignments\nalignRightTop = Alignments [AlignTypeRightTop]\nalignLeftBottom :: Alignments\nalignLeftBottom = Alignments [AlignTypeLeftBottom]\nalignRightBottom :: Alignments\nalignRightBottom = Alignments [AlignTypeRightBottom]\nalignPositionMask :: Alignments\nalignPositionMask = Alignments [AlignTypeLeft, AlignTypeRight, AlignTypeTop, AlignTypeBottom]\nalignImageMask :: Alignments\nalignImageMask = Alignments [AlignTypeImageBackdrop, AlignTypeImageNextToText, AlignTypeTextOverImage]\nalignNoWrap :: Alignments\nalignNoWrap = alignCenter\nalignImageOverText :: Alignments\nalignImageOverText = alignCenter\nalignTopLeft :: Alignments\nalignTopLeft = Alignments [AlignTypeTop, AlignTypeLeft]\nalignTopRight :: Alignments\nalignTopRight = Alignments [AlignTypeTop, AlignTypeRight]\nalignBottomLeft :: Alignments\nalignBottomLeft = Alignments [AlignTypeBottom, AlignTypeLeft]\nalignBottomRight :: Alignments\nalignBottomRight = Alignments [AlignTypeBottom, AlignTypeRight]\nallAlignTypes :: [AlignType]\nallAlignTypes = [\n AlignTypeCenter,\n AlignTypeTop,\n AlignTypeBottom,\n AlignTypeLeft,\n AlignTypeRight,\n AlignTypeInside,\n AlignTypeTextOverImage,\n AlignTypeClip,\n AlignTypeWrap,\n AlignTypeImageNextToText,\n AlignTypeTextNextToImage,\n AlignTypeImageBackdrop,\n AlignTypeLeftTop,\n AlignTypeRightTop,\n AlignTypeLeftBottom,\n AlignTypeRightBottom\n ]\nallWhen :: [When]\nallWhen = [\n WhenNever,\n WhenChanged,\n WhenNotChanged,\n WhenRelease,\n WhenReleaseAlways,\n WhenEnterKey,\n WhenEnterKeyAlways,\n WhenEnterKeyChanged\n ]\n\nallEventStates :: [EventState]\nallEventStates = [\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 ]\ndata Boxtype = NoBox\n | FlatBox\n | UpBox\n | DownBox\n | UpFrame\n | DownFrame\n | ThinUpBox\n | ThinDownBox\n | ThinUpFrame\n | ThinDownFrame\n | EngravedBox\n | EmbossedBox\n | EngravedFrame\n | EmbossedFrame\n | BorderBox\n | ShadowBox\n | BorderFrame\n | ShadowFrame\n | RoundedBox\n | RshadowBox\n | RoundedFrame\n | RFlatBox\n | RoundUpBox\n | RoundDownBox\n | DiamondUpBox\n | DiamondDownBox\n | OvalBox\n | OshadowBox\n | OvalFrame\n | FloatBox\n | PlasticUpBox\n | PlasticDownBox\n | PlasticUpFrame\n | PlasticDownFrame\n | PlasticThinUpBox\n | PlasticThinDownBox\n | PlasticRoundUpBox\n | PlasticRoundDownBox\n | GtkUpBox\n | GtkDownBox\n | GtkUpFrame\n | GtkDownFrame\n | GtkThinUpBox\n | GtkThinDownBox\n | GtkThinUpFrame\n | GtkThinDownFrame\n | GtkRoundUpBox\n | GtkRoundDownBox\n | GleamUpBox\n | GleamDownBox\n | GleamUpFrame\n | GleamDownFrame\n | GleamThinUpBox\n | GleamThinDownBox\n | GleamRoundUpBox\n | GleamRoundDownBox\n | FreeBoxtype\n deriving (Show)\ninstance Enum Boxtype where\n fromEnum NoBox = 0\n fromEnum FlatBox = 1\n fromEnum UpBox = 2\n fromEnum DownBox = 3\n fromEnum UpFrame = 4\n fromEnum DownFrame = 5\n fromEnum ThinUpBox = 6\n fromEnum ThinDownBox = 7\n fromEnum ThinUpFrame = 8\n fromEnum ThinDownFrame = 9\n fromEnum EngravedBox = 10\n fromEnum EmbossedBox = 11\n fromEnum EngravedFrame = 12\n fromEnum EmbossedFrame = 13\n fromEnum BorderBox = 14\n fromEnum ShadowBox = defineShadowBox_\n fromEnum BorderFrame = 16\n fromEnum ShadowFrame = defineShadowBox_ + 2\n fromEnum RoundedBox = defineRoundedBox_\n fromEnum RshadowBox = defineRshadowBox_\n fromEnum RoundedFrame = defineRoundedBox_ + 2\n fromEnum RFlatBox = defineRflatBox_\n fromEnum RoundUpBox = defineRoundUpBox_\n fromEnum RoundDownBox = defineRoundUpBox_ + 1\n fromEnum DiamondUpBox = defineDiamondBox_\n fromEnum DiamondDownBox = defineDiamondBox_ + 1\n fromEnum OvalBox = defineOvalBox_\n fromEnum OshadowBox = defineOvalBox_ + 1\n fromEnum OvalFrame = defineOvalBox_ + 2\n fromEnum FloatBox = defineOvalBox_ + 3\n fromEnum PlasticUpBox = definePlasticUpBox_\n fromEnum PlasticDownBox = definePlasticUpBox_ + 1\n fromEnum PlasticUpFrame = definePlasticUpBox_ + 2\n fromEnum PlasticDownFrame = definePlasticUpBox_ + 3\n fromEnum PlasticThinUpBox = definePlasticUpBox_ + 4\n fromEnum PlasticThinDownBox = definePlasticUpBox_ + 5\n fromEnum PlasticRoundUpBox = definePlasticUpBox_ + 6\n fromEnum PlasticRoundDownBox = definePlasticUpBox_ + 7\n fromEnum GtkUpBox = defineGtkUpBox_\n fromEnum GtkDownBox = defineGtkUpBox_ + 1\n fromEnum GtkUpFrame = defineGtkUpBox_ + 2\n fromEnum GtkDownFrame = defineGtkUpBox_ + 3\n fromEnum GtkThinUpBox = defineGtkUpBox_ + 4\n fromEnum GtkThinDownBox = defineGtkUpBox_ + 5\n fromEnum GtkThinUpFrame = defineGtkUpBox_ + 6\n fromEnum GtkThinDownFrame = defineGtkUpBox_ + 7\n fromEnum GtkRoundUpBox = defineGtkUpBox_ + 8\n fromEnum GtkRoundDownBox = defineGtkUpBox_ + 9\n fromEnum GleamUpBox = defineGleamUpBox_\n fromEnum GleamDownBox = defineGleamUpBox_ + 1\n fromEnum GleamUpFrame = defineGleamUpBox_ + 2\n fromEnum GleamDownFrame = defineGleamUpBox_ + 3\n fromEnum GleamThinUpBox = defineGleamUpBox_ + 4\n fromEnum GleamThinDownBox = defineGleamUpBox_ + 5\n fromEnum GleamRoundUpBox = defineGleamUpBox_ + 6\n fromEnum GleamRoundDownBox = defineGleamUpBox_ + 7\n fromEnum FreeBoxtype = 48\n\n toEnum 0 = NoBox\n toEnum 1 = FlatBox\n toEnum 2 = UpBox\n toEnum 3 = DownBox\n toEnum 4 = UpFrame\n toEnum 5 = DownFrame\n toEnum 6 = ThinUpBox\n toEnum 7 = ThinDownBox\n toEnum 8 = ThinUpFrame\n toEnum 9 = ThinDownFrame\n toEnum 10 = EngravedBox\n toEnum 11 = EmbossedBox\n toEnum 12 = EngravedFrame\n toEnum 13 = EmbossedFrame\n toEnum 14 = BorderBox\n toEnum 16 = BorderFrame\n toEnum 48 = FreeBoxtype\n toEnum x | x == defineShadowBox_ = ShadowBox\n | x == defineShadowBox_ + 2 = ShadowFrame\n | x == defineRoundedBox_ = RoundedBox\n | x == defineRshadowBox_ = RshadowBox\n | x == defineRoundedBox_ + 2 = RoundedFrame\n | x == defineRflatBox_ = RFlatBox\n | x == defineRoundUpBox_ = RoundUpBox\n | x == defineRoundUpBox_ + 1 = RoundDownBox\n | x == defineDiamondBox_ = DiamondUpBox\n | x == defineDiamondBox_ + 1 = DiamondDownBox\n | x == defineOvalBox_ = OvalBox\n | x == defineOvalBox_ + 1 = OshadowBox\n | x == defineOvalBox_ + 2 = OvalFrame\n | x == defineOvalBox_ + 3 = FloatBox\n | x == definePlasticUpBox_ = PlasticUpBox\n | x == definePlasticUpBox_ + 1 = PlasticDownBox\n | x == definePlasticUpBox_ + 2 = PlasticUpFrame\n | x == definePlasticUpBox_ + 3 = PlasticDownFrame\n | x == definePlasticUpBox_ + 4 = PlasticThinUpBox\n | x == definePlasticUpBox_ + 5 = PlasticThinDownBox\n | x == definePlasticUpBox_ + 6 = PlasticRoundUpBox\n | x == definePlasticUpBox_ + 7 = PlasticRoundDownBox\n | x == defineGtkUpBox_ = GtkUpBox\n | x == defineGtkUpBox_ + 1 = GtkDownBox\n | x == defineGtkUpBox_ + 2 = GtkUpFrame\n | x == defineGtkUpBox_ + 3 = GtkDownFrame\n | x == defineGtkUpBox_ + 4 = GtkThinUpBox\n | x == defineGtkUpBox_ + 5 = GtkThinDownBox\n | x == defineGtkUpBox_ + 6 = GtkThinUpFrame\n | x == defineGtkUpBox_ + 7 = GtkThinDownFrame\n | x == defineGtkUpBox_ + 8 = GtkRoundUpBox\n | x == defineGtkUpBox_ + 9 = GtkRoundDownBox\n | x == defineGleamUpBox_ = GleamUpBox\n | x == defineGleamUpBox_ + 1 = GleamDownBox\n | x == defineGleamUpBox_ + 2 = GleamUpFrame\n | x == defineGleamUpBox_ + 3 = GleamDownFrame\n | x == defineGleamUpBox_ + 4 = GleamThinUpBox\n | x == defineGleamUpBox_ + 5 = GleamThinDownBox\n | x == defineGleamUpBox_ + 6 = GleamRoundUpBox\n | x == defineGleamUpBox_ + 7 = GleamRoundDownBox\n | otherwise = error (\"Boxtype.toEnum: Cannot match \" ++ show otherwise)\nframe,frameBox, circleBox, diamondBox :: Boxtype\nframe = EngravedFrame\nframeBox = EngravedBox\ncircleBox = RoundDownBox\ndiamondBox = DiamondDownBox\n\n\n-- Fonts\nnewtype Font = Font Int deriving Show\ndata FontAttribute = Bold | Italic | BoldItalic deriving (Show, Enum)\ncFromFont :: Font -> CInt\ncFromFont (Font f) = fromIntegral f\ncToFont :: CInt -> Font\ncToFont f = Font (fromIntegral f)\n\ncFromFontAttribute :: FontAttribute -> CInt\ncFromFontAttribute Bold = cFromFont helveticaBold\ncFromFontAttribute Italic = cFromFont helveticaItalic\ncFromFontAttribute BoldItalic = cFromFont helveticaBoldItalic\n\ncToFontAttribute :: CInt -> Maybe FontAttribute\ncToFontAttribute attributeCode =\n case (attributeCode `has` helveticaBold, attributeCode `has` helveticaItalic) of\n (True,True) -> Just BoldItalic\n (True,False) -> Just Bold\n (False,True) -> Just Italic\n (False,False) -> Nothing\n where\n has :: CInt -> Font -> Bool\n has code (Font f) = code .&. (fromIntegral f) \/= 0\nhelvetica :: Font\nhelvetica = Font 0\nhelveticaBold :: Font\nhelveticaBold = Font 1\nhelveticaItalic :: Font\nhelveticaItalic = Font 2\nhelveticaBoldItalic :: Font\nhelveticaBoldItalic = Font 3\ncourier :: Font\ncourier = Font 4\ncourierBold :: Font\ncourierBold = Font 5\ncourierItalic :: Font\ncourierItalic = Font 6\ncourierBoldItalic :: Font\ncourierBoldItalic = Font 7\ntimes :: Font\ntimes = Font 8\ntimesBold :: Font\ntimesBold = Font 9\ntimesItalic :: Font\ntimesItalic = Font 10\ntimesBoldItalic :: Font\ntimesBoldItalic = Font 11\nsymbol :: Font\nsymbol = Font 12\nscreen :: Font\nscreen = Font 13\nscreenBold :: Font\nscreenBold = Font 14\nzapfDingbats :: Font\nzapfDingbats = Font 15\nfreeFont :: Font\nfreeFont = Font 16\n\n-- Colors\n\nnewtype Color = Color CUInt deriving Show\nforegroundColor :: Color\nforegroundColor = Color 0\nbackground2Color :: Color\nbackground2Color = Color 7\ninactiveColor :: Color\ninactiveColor = Color 8\nselectionColor :: Color\nselectionColor = Color 15\ngray0Color :: Color\ngray0Color = Color 32\ndark3Color :: Color\ndark3Color = Color 39\ndark2Color :: Color\ndark2Color = Color 45\ndark1Color :: Color\ndark1Color = Color 47\nbackgroundColor :: Color\nbackgroundColor = Color 49\nlight1Color :: Color\nlight1Color = Color 50\nlight2Color :: Color\nlight2Color = Color 52\nlight3Color :: Color\nlight3Color = Color 54\nblackColor :: Color\nblackColor = Color 56\nredColor :: Color\nredColor = Color 88\ngreenColor :: Color\ngreenColor = Color 63\nyellowColor :: Color\nyellowColor = Color 95\nblueColor :: Color\nblueColor = Color 216\nmagentaColor :: Color\nmagentaColor = Color 248\ncyanColor :: Color\ncyanColor = Color 223\ndarkRedColor :: Color\ndarkRedColor = Color 72\ndarkGreenColor :: Color\ndarkGreenColor = Color 60\ndarkYellowColor :: Color\ndarkYellowColor = Color 76\ndarkBlueColor :: Color\ndarkBlueColor = Color 136\ndarkMagentaColor :: Color\ndarkMagentaColor = Color 152\ndarkCyanColor :: Color\ndarkCyanColor = Color 140\nwhiteColor :: Color\nwhiteColor = Color 255\nfreeColor :: Color\nfreeColor = Color 16\nnumFreeColor :: Color\nnumFreeColor =Color 16\ngrayRampColor :: Color\ngrayRampColor = Color 32\nnumGray:: Color\nnumGray= Color 24\ngrayColor :: Color\ngrayColor = backgroundColor\ncolorCubeColor :: Color\ncolorCubeColor = Color 56\nnumRed :: Color\nnumRed = Color 5\nnumGreen :: Color\nnumGreen = Color 8\nnumBlue :: Color\nnumBlue = Color 5\n\n-- Fl_LabelType\n\ndata Labeltype = NormalLabel\n | NoLabel\n | ShadowLabel\n | EngravedLabel\n | EmbossedLabel\n | FreeLabelType deriving Show\n\ninstance Enum Labeltype where\n fromEnum NormalLabel = 0\n fromEnum NoLabel = 1\n fromEnum ShadowLabel = defineShadowLabel_\n fromEnum EngravedLabel = defineEngravedLabel_\n fromEnum EmbossedLabel = defineEmbossedLabel_\n fromEnum FreeLabelType = 8\n\n toEnum 0 = NormalLabel\n toEnum 1 = NoLabel\n toEnum x | x == defineShadowLabel_ = ShadowLabel\n | x == defineEngravedLabel_ = EngravedLabel\n | x == defineEmbossedLabel_ = EmbossedLabel\n toEnum 8 = FreeLabelType\n\nsymbolLabel :: Labeltype\nsymbolLabel = NormalLabel\n\ndefineRoundUpBox_ :: (Num a) => a\ndefineRoundUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_ROUND_UP_BOXC #}\n\ndefineRoundUpBox :: Boxtype\ndefineRoundUpBox =\n toEnum defineRoundUpBox_\n\ndefineShadowBox_ :: (Num a) => a\ndefineShadowBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_SHADOW_BOXC #}\n\ndefineShadowBox :: Boxtype\ndefineShadowBox =\n toEnum defineShadowBox_\n\ndefineRoundedBox_ :: (Num a) => a\ndefineRoundedBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_ROUNDED_BOXC #}\ndefineRoundedBox :: Boxtype\ndefineRoundedBox = toEnum defineRoundedBox_\n\ndefineRflatBox_ :: (Num a) => a\ndefineRflatBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_RFLAT_BOXC #}\ndefineRflatBox :: Boxtype\ndefineRflatBox = toEnum defineRflatBox_\n\ndefineRshadowBox_ :: (Num a) => a\ndefineRshadowBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_RSHADOW_BOXC #}\ndefineRshadowBox :: Boxtype\ndefineRshadowBox = toEnum defineRshadowBox_\n\ndefineDiamondBox_ :: (Num a) => a\ndefineDiamondBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_DIAMOND_BOXC #}\ndefineDiamondBox :: Boxtype\ndefineDiamondBox = toEnum defineDiamondBox_\n\ndefineOvalBox_ :: (Num a) => a\ndefineOvalBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_OVAL_BOXC #}\ndefineOvalBox :: Boxtype\ndefineOvalBox = toEnum defineOvalBox_\n\ndefinePlasticUpBox_ :: (Num a) => a\ndefinePlasticUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_PLASTIC_UP_BOXC #}\ndefinePlasticUpBox :: Boxtype\ndefinePlasticUpBox = toEnum definePlasticUpBox_\n\ndefineGtkUpBox_ :: (Num a) => a\ndefineGtkUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_GTK_UP_BOXC #}\ndefineGtkUpBox :: Boxtype\ndefineGtkUpBox = toEnum defineGtkUpBox_\n\ndefineGleamUpBox_ :: (Num a ) => a\ndefineGleamUpBox_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_GLEAM_UP_BOXC #}\n\ndefineShadowLabel_ :: (Num a) => a\ndefineShadowLabel_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_SHADOW_LABELC #}\ndefineShadowLabel :: Labeltype\ndefineShadowLabel = toEnum defineShadowLabel_\n\ndefineEngravedLabel_ :: (Num a) => a\ndefineEngravedLabel_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_ENGRAVED_LABELC #}\n\ndefineEngravedLabel :: Labeltype\ndefineEngravedLabel = toEnum defineEngravedLabel_\n\ndefineEmbossedLabel_ :: (Num a) => a\ndefineEmbossedLabel_ =\n fromIntegral $ {#call pure unsafe fl_define_FL_EMBOSSED_LABELC #}\n\ndefineEmbossedLabel :: Labeltype\ndefineEmbossedLabel = toEnum defineEmbossedLabel_\n\ncFromColor :: Color -> CUInt\ncFromColor (Color c) = fromIntegral c\ncToColor :: CUInt-> Color\ncToColor c = Color (fromIntegral c)\n\ntype RGB = (CUChar, CUChar, CUChar)\n\n{#fun pure fl_inactiveC as\n inactive {cFromColor `Color' } -> `Color' cToColor#}\n{#fun pure fl_contrastC as\n contrast {cFromColor `Color',cFromColor `Color'}\n -> `Color' cToColor#}\n{#fun pure fl_color_averageC as\n color_average {cFromColor `Color',\n cFromColor `Color',\n realToFrac `Double'}\n -> `Color' cToColor#}\n{#fun pure fl_lighterC as\n lighter {cFromColor `Color'} -> `Color' cToColor#}\n{#fun pure fl_darkerC as\n darker {cFromColor `Color'} -> `Color' cToColor#}\n{#fun fl_rgb_color_with_rgbC as\n rgbColorWithRgb' {id `CUChar',\n id `CUChar',\n id `CUChar'}\n -> `CUInt' #}\nrgbColorWithRgb :: RGB -> IO Color\nrgbColorWithRgb (r,g,b) = rgbColorWithRgb' r g b >>= return . Color\n\n{#fun pure fl_rgb_color_with_grayscaleC as\n rgbColorWithGrayscale {castCharToCUChar `Char'}\n -> `Color' cToColor#}\n{#fun pure fl_gray_rampC as grayRamp {`Int'} -> `Color' cToColor#}\n{#fun pure fl_color_cubeC as colorCube {`Int',`Int',`Int'}\n -> `Color' cToColor#}\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"1354c99be363cce6e996dfdddc5c66ad8db3ac2c","subject":"retEither tysig","message":"retEither tysig\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\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 undefined spStr (fromBool acrossFs) cdsStr\n retEither res $ undefined\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\n-- TODO: Refactor some bits\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","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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\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 undefined spStr (fromBool acrossFs) cdsStr\n retEither res $ undefined\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\n-- TODO: Refactor some bits\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\n-- TODO: Add tysig\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"623cd1b968761c6a664f53898bd74678624ae9bf","subject":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members","message":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult(..),\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult,\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"465b92e61161626f3a1bcd32309ff45d58a89cc3","subject":"Fix the releaseImport bug, add functions.","message":"Fix the releaseImport bug, add functions.\n","repos":"joelburget\/assimp,joelburget\/assimp,haraldsteinlechner\/assimp,haraldsteinlechner\/assimp","old_file":"Graphics\/Formats\/Assimp\/Fun.chs","new_file":"Graphics\/Formats\/Assimp\/Fun.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Graphics.Formats.Assimp.Fun (\n importFile\n , applyPostProcessing\n-- , releaseImport\n , getErrorString\n , isExtensionSupported\n , setImportPropertyInteger\n , setImportPropertyFloat\n , getVersionMinor\n , getVersionMajor\n , getVersionRevision\n ) where\n\nimport C2HS\nimport Graphics.Formats.Assimp.Types\nimport Graphics.Formats.Assimp.Storable\n\n#include \"assimp.h\"\n#include \"aiVersion.h\"\n#include \"typedefs.h\"\n\n--withT = with -- http:\/\/blog.ezyang.com\/2010\/06\/call-and-fun-marshalling-redux\/\nwith' :: (Storable a) => a -> (Ptr b -> IO c) -> IO c\nwith' x y = with x (y . castPtr)\n\npeek' :: (Storable b) => Ptr a -> IO b\npeek' = peek . castPtr\n\n-- Removing these for now. I don't see any reason to use them. You can't\n-- release resources after using this importFile because you don't get the\n-- pointer.\n-- {#fun unsafe aiImportFile as importFile\n-- {`String', cFromEnum `PostProcessSteps'} -> `Scene' peek'*#}\n-- \n-- {#fun unsafe aiReleaseImport as releaseImport\n-- {with'* `Scene'} -> `()'#}\n\n-- aiImportFileEx\n-- aiImportFileFromMemory\n\n{#fun unsafe aiApplyPostProcessing as applyPostProcessing \n {with'* `Scene', cFromEnum `PostProcessSteps'} -> `Scene' peek'*#}\n\n--{#fun aiGetPredefinedLogStream as ^\n-- {cFromEnum `DefaultLogStream', `String'} -> `LogStream' id#}\n\n-- aiAttachLogStream\n-- aiEnableVerboseLogging\n-- aiDetachLogStream\n-- aiDetachAllLogStreams\n\nimportFile :: String -> PostProcessSteps -> IO Scene\nimportFile str psteps = do \n let psteps' = cFromEnum psteps\n sceneptr <- withCString str $ \\x -> {#call unsafe aiImportFile#} x psteps'\n scene <- peek' sceneptr\n {#call unsafe aiReleaseImport#} sceneptr\n return scene\n\n{#fun unsafe aiGetErrorString as getErrorString\n {} -> `String'#}\n\n{#fun unsafe aiIsExtensionSupported as isExtensionSupported\n {`String'} -> `Bool'#}\n\n-- aiGetExtensionList\n-- aiGetMemoryRequirements\n\n{# fun unsafe aiSetImportPropertyInteger as setImportPropertyInteger\n {`String', `Int'} -> `()'#}\n\n{# fun unsafe aiSetImportPropertyFloat as setImportPropertyFloat \n {`String', `Float'} -> `()'#}\n\n--{# fun aiSetImportPropertyString as ^\n-- {`String', `String'} -> `()'#}\n\n-- aiGetLegalString\n{# fun unsafe aiGetVersionMinor as getVersionMinor\n {} -> `Int'#}\n{# fun unsafe aiGetVersionMajor as getVersionMajor\n {} -> `Int'#}\n{# fun unsafe aiGetVersionRevision as getVersionRevision\n {} -> `Int'#}\n-- aiGetCompileFlags\n-- aiGetMaterialProperty\n-- aiGetMaterialFloatArray\n-- aiGetMaterialIntegerArray\n-- aiGetMaterialColor\n-- aiGetMaterialString\n\n-- I'm not sure whether or not I will implement these or not. I guess I'll\n-- check the source to see if they're pure. They could easily be implemented in\n-- pure haskell.\n\n-- aiCreateQuaternionFromMatrix\n-- aiDecomposeMatrix\n-- aiTransposematrix4\n-- aiTransposematrix3\n-- aiTransformVecByMatrix3\n-- aiTransformVecByMatrix4\n-- aiMultiplyMatrix3\n-- aiMultiplyMatrix4\n-- aiIdentityMatrix3\n-- aiIdentityMatrix4\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Graphics.Formats.Assimp.Fun (\n importFile\n , applyPostProcessing\n , releaseImport\n , getErrorString\n , isExtensionSupported\n , setImportPropertyInteger\n , setImportPropertyFloat\n ) where\n\nimport C2HS\nimport Graphics.Formats.Assimp.Types\nimport Graphics.Formats.Assimp.Storable\n\n#include \"assimp.h\"\n#include \"typedefs.h\"\n\n--withT = with -- http:\/\/blog.ezyang.com\/2010\/06\/call-and-fun-marshalling-redux\/\nwith' :: (Storable a) => a -> (Ptr b -> IO c) -> IO c\nwith' x y = with x (y . castPtr)\n\npeek' :: (Storable b) => Ptr a -> IO b\npeek' = peek . castPtr\n\n{#fun unsafe aiImportFile as importFile\n {`String', cFromEnum `PostProcessSteps'} -> `Scene' peek'*#}\n\n-- aiImportFileEx\n-- aiImportFileFromMemory\n\n{#fun unsafe aiApplyPostProcessing as applyPostProcessing \n {with'* `Scene', cFromEnum `PostProcessSteps'} -> `Scene' peek'*#}\n\n--{#fun aiGetPredefinedLogStream as ^\n-- {cFromEnum `DefaultLogStream', `String'} -> `LogStream' id#}\n\n-- aiAttachLogStream\n-- aiEnableVerboseLogging\n-- aiDetachLogStream\n-- aiDetachAllLogStreams\n\n{#fun unsafe aiReleaseImport as releaseImport\n {with'* `Scene'} -> `()'#}\n\n{#fun unsafe aiGetErrorString as getErrorString\n {} -> `String'#}\n\n{#fun unsafe aiIsExtensionSupported as isExtensionSupported\n {`String'} -> `Bool'#}\n\n-- aiGetExtensionList\n-- aiGetMemoryRequirements\n\n{# fun unsafe aiSetImportPropertyInteger as setImportPropertyInteger\n {`String', `Int'} -> `()'#}\n\n{# fun unsafe aiSetImportPropertyFloat as setImportPropertyFloat \n {`String', `Float'} -> `()'#}\n\n--{# fun aiSetImportPropertyString as ^\n-- {`String', `String'} -> `()'#}\n\n-- aiGetLegalString\n-- aiGetVersionMinor\n-- aiGetVersionmajor\n-- aiGetVersionRevision\n-- aiGetCompileFlags\n-- aiGetMaterialProperty\n-- aiGetMaterialFloatArray\n-- aiGetMaterialIntegerArray\n-- aiGetMaterialColor\n-- aiGetMaterialString\n\n-- I'm not sure whether or not I will implement these or not. I guess I'll\n-- check the source to see if they're pure. They could easily be implemented in\n-- pure haskell.\n\n-- aiCreateQuaternionFromMatrix\n-- aiDecomposeMatrix\n-- aiTransposematrix4\n-- aiTransposematrix3\n-- aiTransformVecByMatrix3\n-- aiTransformVecByMatrix4\n-- aiMultiplyMatrix3\n-- aiMultiplyMatrix4\n-- aiIdentityMatrix3\n-- aiIdentityMatrix4\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c698c0ae6aafbef44de963c4622f809c93d62b61","subject":"typechecker-regex-prototype: fix libfa build on debian, remove unused declaration","message":"typechecker-regex-prototype: fix libfa build on debian, remove unused declaration\n","repos":"mpranj\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,petermax2\/libelektra,mpranj\/libelektra,mpranj\/libelektra,BernhardDenner\/libelektra,petermax2\/libelektra,petermax2\/libelektra,BernhardDenner\/libelektra,BernhardDenner\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,mpranj\/libelektra,mpranj\/libelektra,petermax2\/libelektra,mpranj\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,mpranj\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,e1528532\/libelektra,petermax2\/libelektra,mpranj\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,petermax2\/libelektra,mpranj\/libelektra,petermax2\/libelektra,mpranj\/libelektra","old_file":"src\/libs\/typesystem\/libfa\/FiniteAutomata.chs","new_file":"src\/libs\/typesystem\/libfa\/FiniteAutomata.chs","new_contents":"--\n-- @file\n--\n-- @brief LibFA Haskell Bindings\n--\n-- @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n-- \nmodule FiniteAutomata (FiniteAutomata, BasicAutomata (..),\n compile, makeBasic, asRegexp, minimize, FiniteAutomata.concat, union, \n intersect, complement, minus, iter, contains, equals, overlap) where\n\n#include \nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.ForeignPtr (ForeignPtr, newForeignPtr, withForeignPtr)\nimport Foreign.Storable (peek)\nimport Foreign.C.Types (CChar)\nimport Foreign.C.String (withCString)\n\n{#context lib=\"libfa\" prefix = \"fa\" #}\n\n{#pointer *fa as FiniteAutomata foreign finalizer free newtype #}\n\n{#enum fa_basic as BasicAutomata { underscoreToCase } deriving (Show, Eq) #}\n\n{#typedef size_t Int #}\n{#typedef ssize_t Int #}\n\n--\n-- Convert from\/to Regex\n--\n{#fun unsafe make_basic as makeBasic {`BasicAutomata'} -> `FiniteAutomata' #}\n\n-- Implemented manually to get around that double Ptr issue with c2hs\ncompile :: String -> IO (Either Int FiniteAutomata)\ncompile str = withCString str $ \\a1' -> \n alloca $ \\a3' -> \n fa_compile a1' (length str) a3' >>= \\res ->\n let {res' = fromIntegral res} in\n peek a3' >>= \\a3'' ->\n newForeignPtr fa_free (castPtr a3'') >>= \\a3''' ->\n withForeignPtr a3''' $ \\a3'''' -> \n if a3'''' == nullPtr then return $ Left res' else return $ Right $ FiniteAutomata a3'''\n\n{#fun unsafe as_regexp as asRegexp {`FiniteAutomata', alloca- `Ptr CChar' peek*, alloca- `Int' peek*} -> `Int' #}\n\n--\n-- Finite Automata Algorithms\n--\n{#fun unsafe minimize {`FiniteAutomata'} -> `Int' #}\n{#fun unsafe concat {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe union {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe intersect {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe complement {`FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe minus {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe iter {`FiniteAutomata', `Int', `Int'} -> `FiniteAutomata' #}\n{#fun unsafe contains {`FiniteAutomata', `FiniteAutomata'} -> `Int' #}\n{#fun unsafe equals {`FiniteAutomata', `FiniteAutomata'} -> `Int' #}\n{#fun unsafe overlap {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n\nforeign import ccall unsafe \"FiniteAutomata.chs.h fa_compile\"\n fa_compile :: ((C2HSImp.Ptr C2HSImp.CChar) -> (Int -> ((C2HSImp.Ptr (C2HSImp.Ptr ())) -> (IO C2HSImp.CInt))))\n","old_contents":"--\n-- @file\n--\n-- @brief LibFA Haskell Bindings\n--\n-- @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n-- \nmodule FiniteAutomata (FiniteAutomata, State, BasicAutomata (..),\n compile, makeBasic, asRegexp, minimize, FiniteAutomata.concat, union, \n intersect, complement, minus, iter, contains, equals, overlap) where\n\n#include \nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.ForeignPtr (ForeignPtr, newForeignPtr, withForeignPtr)\nimport Foreign.Storable (peek)\nimport Foreign.C.Types (CChar)\nimport Foreign.C.String (withCString)\n\n{#context lib=\"libfa\" prefix = \"fa\" #}\n\n{#pointer *fa as FiniteAutomata foreign finalizer free newtype #}\n{#pointer *state as State foreign newtype #}\n\n{#enum fa_basic as BasicAutomata { underscoreToCase } deriving (Show, Eq) #}\n\n{#typedef size_t Int #}\n{#typedef ssize_t Int #}\n\n--\n-- Convert from\/to Regex\n--\n{#fun unsafe make_basic as makeBasic {`BasicAutomata'} -> `FiniteAutomata' #}\n\n-- Implemented manually to get around that double Ptr issue with c2hs\ncompile :: String -> IO (Either Int FiniteAutomata)\ncompile str = withCString str $ \\a1' -> \n alloca $ \\a3' -> \n fa_compile a1' (length str) a3' >>= \\res ->\n let {res' = fromIntegral res} in\n peek a3' >>= \\a3'' ->\n newForeignPtr fa_free (castPtr a3'') >>= \\a3''' ->\n withForeignPtr a3''' $ \\a3'''' -> \n if a3'''' == nullPtr then return $ Left res' else return $ Right $ FiniteAutomata a3'''\n\n{#fun unsafe as_regexp as asRegexp {`FiniteAutomata', alloca- `Ptr CChar' peek*, alloca- `Int' peek*} -> `Int' #}\n\n--\n-- Finite Automata Algorithms\n--\n{#fun unsafe minimize {`FiniteAutomata'} -> `Int' #}\n{#fun unsafe concat {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe union {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe intersect {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe complement {`FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe minus {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n{#fun unsafe iter {`FiniteAutomata', `Int', `Int'} -> `FiniteAutomata' #}\n{#fun unsafe contains {`FiniteAutomata', `FiniteAutomata'} -> `Int' #}\n{#fun unsafe equals {`FiniteAutomata', `FiniteAutomata'} -> `Int' #}\n{#fun unsafe overlap {`FiniteAutomata', `FiniteAutomata'} -> `FiniteAutomata' #}\n\nforeign import ccall unsafe \"FiniteAutomata.chs.h fa_compile\"\n fa_compile :: ((C2HSImp.Ptr C2HSImp.CChar) -> (Int -> ((C2HSImp.Ptr (C2HSImp.Ptr ())) -> (IO C2HSImp.CInt))))\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"40e81fc3e9c9c77ad978c74e1925d0a69d63a236","subject":"updated with the latest version of librdkafka","message":"updated with the latest version of librdkafka\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\n--import Control.Applicative\nimport Control.Monad\nimport Data.Word\nimport Foreign\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Kafka.Internal.RdKafkaEnum\nimport System.IO\nimport System.Posix.IO\nimport System.Posix.Types\n\n#include \"rdkafka.h\"\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\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 unsafe rd_kafka_version as ^\n {} -> `Int' #}\n\n{#fun pure unsafe rd_kafka_version_str as ^\n {} -> `String' #}\n\n{#fun pure unsafe rd_kafka_err2str as ^\n {enumToCInt `RdKafkaRespErrT'} -> `String' #}\n\n{#fun pure unsafe rd_kafka_errno2err as ^\n {`Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\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 }\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 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\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 unsafe rd_kafka_topic_partition_list_new as ^\n {`Int'} -> `RdKafkaTopicPartitionListTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_partition_list_destroy\"\n rdKafkaTopicPartitionListDestroy :: FunPtr (Ptr RdKafkaTopicPartitionListT -> IO ())\n \nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy ret\n return ret\n \n{# fun unsafe rd_kafka_topic_partition_list_add as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int'} -> `RdKafkaTopicPartitionTPtr' #}\n \n{# fun unsafe rd_kafka_topic_partition_list_add_range as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int', `Int'} -> `()' #}\n \n{# fun unsafe rd_kafka_topic_partition_list_copy as ^\n {`RdKafkaTopicPartitionListTPtr'} -> `RdKafkaTopicPartitionListTPtr' #}\n \ncopyRdKafkaTopicPartitionList :: RdKafkaTopicPartitionListTPtr -> IO RdKafkaTopicPartitionListTPtr\ncopyRdKafkaTopicPartitionList pl = do\n cp <- rdKafkaTopicPartitionListCopy pl\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy cp\n return cp\n \n{# fun unsafe 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 -> Ptr Word8 -> 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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetRebalanceCb' c cb'\n return ()\n\n---- Delivery Callback\ntype DeliveryCallback = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkDeliveryCallback :: DeliveryCallback -> IO (FunPtr DeliveryCallback)\n\nforeign import ccall unsafe \"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 cb\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 unsafe \"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 -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkOffsetCommitCallback :: OffsetCommitCallback' -> IO (FunPtr OffsetCommitCallback')\n\nforeign import ccall unsafe \"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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetOffsetCommitCb' c cb'\n return ()\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 unsafe \"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---- Stats Callback \ntype StatsCallback = Ptr RdKafkaT -> CString -> CSize -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkStatsCallback :: StatsCallback -> IO (FunPtr StatsCallback)\n\nforeign import ccall unsafe \"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 cb\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 unsafe \"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 unsafe rd_kafka_conf_set_opaque as ^\n {`RdKafkaConfTPtr', castPtr `Word8Ptr'} -> `()' #}\n \n{#fun unsafe rd_kafka_opaque as ^\n {`RdKafkaTPtr'} -> `Word8Ptr' castPtr #}\n \n{#fun unsafe 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 unsafe \"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 unsafe rd_kafka_topic_partition_available as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\n \n{#fun unsafe 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 unsafe 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 unsafe 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 unsafe rd_kafka_yield as ^\n {`RdKafkaTPtr'} -> `()' #}\n\n---- Pause \/ Resume\n{#fun unsafe rd_kafka_pause_partitions as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe 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 unsafe rd_kafka_queue_new as ^\n {`RdKafkaTPtr'} -> `RdKafkaQueueTPtr' #}\n \nforeign import ccall unsafe \"rdkafka.h &rd_kafka_queue_destroy\"\n rdKafkaQueueDestroy :: FunPtr (Ptr RdKafkaQueueT -> IO ())\n \nnewRdKafkaQueue :: RdKafkaTPtr -> IO RdKafkaQueueTPtr\nnewRdKafkaQueue k = do\n q <- rdKafkaQueueNew k\n addForeignPtrFinalizer rdKafkaQueueDestroy q\n return q\n-------------------------------------------------------------------------------------------------\n---- High-level KafkaConsumer \n\n{#fun unsafe rd_kafka_subscribe as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_unsubscribe as ^\n {`RdKafkaTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_subscription as ^\n {`RdKafkaTPtr', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'} \n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe 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 unsafe rd_kafka_consumer_close as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_poll_set_consumer as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n \n-- rd_kafka_assign\n{#fun unsafe rd_kafka_assign as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} \n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_assignment as ^\n {`RdKafkaTPtr', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_commit as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_commit_message as ^\n {`RdKafkaTPtr', `RdKafkaMessageTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_committed as ^ \n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun unsafe 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 foreign -> RdKafkaGroupMemberInfoT #}\n\ndata RdKafkaGroupInfoT = RdKafkaGroupInfoT\n { broker'RdKafkaGroupInfoT :: Ptr RdKafkaMetadataBrokerT\n , group'RdKafkaGroupInfoT :: CString\n , err'RdKafkaGroupInfoT :: RdKafkaRespErrT\n , state'RdKafkaGroupInfoT :: CString\n , protocolType'RdKafkaGroupInfoT :: CString\n , protocol'RdKafkaGroupInfoT :: CString\n , members'RdKafkaGroupInfoT :: Ptr RdKafkaGroupMemberInfoT\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 ^\n {`RdKafkaTPtr', `String', castPtr `Ptr (Ptr RdKafkaGroupListT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #} \n \nforeign import ccall unsafe \"rdkafka.h &rd_kafka_list_groups\"\n rdKafkaGroupListDestroy :: FunPtr (Ptr RdKafkaGroupListT -> IO ())\n \n-- listRdKafkaGroups :: RdKafkaTPtr -> String -> Int -> IO (Either RdKafkaRespErrT RdKafkaGroupListTPtr)\n-- listRdKafkaGroups k g t = alloca $ \\lstDblPtr -> do\n-- err <- rdKafkaListGroups k g lstDblPtr t\n-- case err of\n-- RdKafkaRespErrNoError -> do\n-- lstPtr <- peek lstDblPtr\n-- lst <- peek lstPtr\n-- addForeignPtrFinalizer rdKafkaGroupListDestroy lstPtr\n-- return $ Right lstPtr\n-- e -> return $ Left e\n-------------------------------------------------------------------------------------------------\n\n-- rd_kafka_message\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_message_destroy\"\n rdKafkaMessageDestroyF :: FunPtr (Ptr RdKafkaMessageT -> IO ())\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_message_destroy\"\n rdKafkaMessageDestroy :: Ptr RdKafkaMessageT -> IO ()\n\n-- rd_kafka_conf\n{#fun unsafe rd_kafka_conf_new as ^\n {} -> `RdKafkaConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_conf_destroy\"\n rdKafkaConfDestroy :: FunPtr (Ptr RdKafkaConfT -> IO ())\n\n{#fun unsafe rd_kafka_conf_dup as ^\n {`RdKafkaConfTPtr'} -> `RdKafkaConfTPtr' #}\n\n{#fun unsafe 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 unsafe rd_kafka_conf_dump as ^\n {`RdKafkaConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n{#fun unsafe rd_kafka_conf_dump_free as ^\n {id `Ptr CString', cIntConv `CSize'} -> `()' #}\n\n{#fun unsafe rd_kafka_conf_properties_show as ^\n {`CFilePtr'} -> `()' #}\n\n-- rd_kafka_topic_conf\n{#fun unsafe rd_kafka_topic_conf_new as ^\n {} -> `RdKafkaTopicConfTPtr' #}\n{#fun unsafe rd_kafka_topic_conf_dup as ^\n {`RdKafkaTopicConfTPtr'} -> `RdKafkaTopicConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_conf_destroy\"\n rdKafkaTopicConfDestroy :: FunPtr (Ptr RdKafkaTopicConfT -> IO ())\n\n{#fun unsafe 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 unsafe rd_kafka_topic_conf_dump as ^\n {`RdKafkaTopicConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n-- rd_kafka\n{#fun unsafe rd_kafka_new as ^\n {enumToCInt `RdKafkaTypeT', `RdKafkaConfTPtr', id `CCharBufPointer', cIntConv `CSize'} \n -> `RdKafkaTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_destroy\"\n rdKafkaDestroy :: FunPtr (Ptr RdKafkaT -> IO ())\n\nnewRdKafkaT :: RdKafkaTypeT -> RdKafkaConfTPtr -> IO (Either String 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 peekCString charPtr >>= return . Left\n else do\n addForeignPtrFinalizer rdKafkaDestroy ret\n return $ Right ret\n\n{#fun unsafe rd_kafka_brokers_add as ^\n {`RdKafkaTPtr', `String'} -> `Int' #}\n\n{#fun unsafe rd_kafka_set_log_level as ^\n {`RdKafkaTPtr', `Int'} -> `()' #}\n\n-- rd_kafka consume\n\n{#fun unsafe 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 unsafe rd_kafka_consume_stop as rdKafkaConsumeStopInternal\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\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 unsafe rd_kafka_offset_store as rdKafkaOffsetStore\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', cIntConv `CInt64T'} \n -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka produce\n\n{#fun unsafe rd_kafka_produce as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', castPtr `Word8Ptr', \n cIntConv `CSize', castPtr `Word8Ptr', cIntConv `CSize', castPtr `Word8Ptr'}\n -> `Int' #}\n\n{#fun unsafe rd_kafka_produce_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', `RdKafkaMessageTPtr', `Int'} -> `Int' #}\n\ncastMetadata :: Ptr (Ptr RdKafkaMetadataT) -> Ptr (Ptr ())\ncastMetadata ptr = castPtr ptr\n\n-- rd_kafka_metadata\n\n{#fun unsafe rd_kafka_metadata as ^\n {`RdKafkaTPtr', boolToCInt `Bool', `RdKafkaTopicTPtr', \n castMetadata `Ptr (Ptr RdKafkaMetadataT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{# fun unsafe rd_kafka_metadata_destroy as ^\n {castPtr `Ptr RdKafkaMetadataT'} -> `()' #}\n\n{#fun unsafe rd_kafka_poll as ^\n {`RdKafkaTPtr', `Int'} -> `Int' #}\n\n{#fun unsafe rd_kafka_outq_len as ^\n {`RdKafkaTPtr'} -> `Int' #}\n\n{#fun unsafe rd_kafka_dump as ^\n {`CFilePtr', `RdKafkaTPtr'} -> `()' #}\n\n\n-- rd_kafka_topic\n{#fun unsafe rd_kafka_topic_name as ^\n {`RdKafkaTopicTPtr'} -> `String' #}\n\n{#fun unsafe rd_kafka_topic_new as ^\n {`RdKafkaTPtr', `String', `RdKafkaTopicConfTPtr'} -> `RdKafkaTopicTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_destroy\"\n rdKafkaTopicDestroy :: FunPtr (Ptr RdKafkaTopicT -> IO ())\n\nnewRdKafkaTopicT :: RdKafkaTPtr -> String -> RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- rdKafkaTopicConfDup topicConfPtr\n ret <- rdKafkaTopicNew kafkaPtr topic duper\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then kafkaErrnoString >>= return . Left\n else do\n addForeignPtrFinalizer rdKafkaTopicDestroy ret\n return $ Right ret\n\n-- Marshall \/ Unmarshall\nenumToCInt :: Enum a => a -> CInt\nenumToCInt = fromIntegral . fromEnum\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\nboolToCInt :: Bool -> CInt\nboolToCInt True = CInt 1\nboolToCInt False = CInt 0\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\n--import Control.Applicative\nimport Control.Monad\nimport Data.Word\nimport Foreign\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Kafka.Internal.RdKafkaEnum\nimport System.IO\nimport System.Posix.IO\nimport System.Posix.Types\n\n#include \"rdkafka.h\"\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\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 unsafe rd_kafka_version as ^\n {} -> `Int' #}\n\n{#fun pure unsafe rd_kafka_version_str as ^\n {} -> `String' #}\n\n{#fun pure unsafe rd_kafka_err2str as ^\n {enumToCInt `RdKafkaRespErrT'} -> `String' #}\n\n{#fun pure unsafe rd_kafka_errno2err as ^\n {`Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\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 }\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 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\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 unsafe rd_kafka_topic_partition_list_new as ^\n {`Int'} -> `RdKafkaTopicPartitionListTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_partition_list_destroy\"\n rdKafkaTopicPartitionListDestroy :: FunPtr (Ptr RdKafkaTopicPartitionListT -> IO ())\n \nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy ret\n return ret\n \n{# fun unsafe rd_kafka_topic_partition_list_add as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int'} -> `RdKafkaTopicPartitionTPtr' #}\n \n{# fun unsafe rd_kafka_topic_partition_list_add_range as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int', `Int'} -> `()' #}\n \n{# fun unsafe rd_kafka_topic_partition_list_copy as ^\n {`RdKafkaTopicPartitionListTPtr'} -> `RdKafkaTopicPartitionListTPtr' #}\n \ncopyRdKafkaTopicPartitionList :: RdKafkaTopicPartitionListTPtr -> IO RdKafkaTopicPartitionListTPtr\ncopyRdKafkaTopicPartitionList pl = do\n cp <- rdKafkaTopicPartitionListCopy pl\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy cp\n return cp\n \n{# fun unsafe 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 -> Ptr Word8 -> 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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetRebalanceCb' c cb'\n return ()\n\n---- Delivery Callback\ntype DeliveryCallback = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkDeliveryCallback :: DeliveryCallback -> IO (FunPtr DeliveryCallback)\n\nforeign import ccall unsafe \"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 cb\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 unsafe \"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 -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkOffsetCommitCallback :: OffsetCommitCallback' -> IO (FunPtr OffsetCommitCallback')\n\nforeign import ccall unsafe \"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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetOffsetCommitCb' c cb'\n return ()\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 unsafe \"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---- Stats Callback \ntype StatsCallback = Ptr RdKafkaT -> CString -> CSize -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkStatsCallback :: StatsCallback -> IO (FunPtr StatsCallback)\n\nforeign import ccall unsafe \"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 cb\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 unsafe \"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 unsafe rd_kafka_conf_set_opaque as ^\n {`RdKafkaConfTPtr', castPtr `Word8Ptr'} -> `()' #}\n \n{#fun unsafe rd_kafka_opaque as ^\n {`RdKafkaTPtr'} -> `Word8Ptr' castPtr #}\n \n{#fun unsafe 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 unsafe \"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 unsafe rd_kafka_topic_partition_available as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\n \n{#fun unsafe 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 unsafe 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 unsafe 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 unsafe rd_kafka_yield as ^\n {`RdKafkaTPtr'} -> `()' #}\n\n---- Pause \/ Resume\n{#fun unsafe rd_kafka_pause_partitions as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe 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 unsafe rd_kafka_queue_new as ^\n {`RdKafkaTPtr'} -> `RdKafkaQueueTPtr' #}\n \nforeign import ccall unsafe \"rdkafka.h &rd_kafka_queue_destroy\"\n rdKafkaQueueDestroy :: FunPtr (Ptr RdKafkaQueueT -> IO ())\n \nnewRdKafkaQueue :: RdKafkaTPtr -> IO RdKafkaQueueTPtr\nnewRdKafkaQueue k = do\n q <- rdKafkaQueueNew k\n addForeignPtrFinalizer rdKafkaQueueDestroy q\n return q\n-------------------------------------------------------------------------------------------------\n---- High-level KafkaConsumer \n\n{#fun unsafe rd_kafka_subscribe as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_unsubscribe as ^\n {`RdKafkaTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_subscription as ^\n {`RdKafkaTPtr', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'} \n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe 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 unsafe rd_kafka_consumer_close as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_poll_set_consumer as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n \n-- rd_kafka_assign\n{#fun unsafe rd_kafka_assign as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} \n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_assignment as ^\n {`RdKafkaTPtr', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_commit as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_commit_message as ^\n {`RdKafkaTPtr', `RdKafkaMessageTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n \n{#fun unsafe rd_kafka_position as ^ \n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\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 foreign -> RdKafkaGroupMemberInfoT #}\n\ndata RdKafkaGroupInfoT = RdKafkaGroupInfoT\n { broker'RdKafkaGroupInfoT :: Ptr RdKafkaMetadataBrokerT\n , group'RdKafkaGroupInfoT :: CString\n , err'RdKafkaGroupInfoT :: RdKafkaRespErrT\n , state'RdKafkaGroupInfoT :: CString\n , protocolType'RdKafkaGroupInfoT :: CString\n , protocol'RdKafkaGroupInfoT :: CString\n , members'RdKafkaGroupInfoT :: Ptr RdKafkaGroupMemberInfoT\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 ^\n {`RdKafkaTPtr', `String', castPtr `Ptr (Ptr RdKafkaGroupListT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #} \n \nforeign import ccall unsafe \"rdkafka.h &rd_kafka_list_groups\"\n rdKafkaGroupListDestroy :: FunPtr (Ptr RdKafkaGroupListT -> IO ())\n \n-- listRdKafkaGroups :: RdKafkaTPtr -> String -> Int -> IO (Either RdKafkaRespErrT RdKafkaGroupListTPtr)\n-- listRdKafkaGroups k g t = alloca $ \\lstDblPtr -> do\n-- err <- rdKafkaListGroups k g lstDblPtr t\n-- case err of\n-- RdKafkaRespErrNoError -> do\n-- lstPtr <- peek lstDblPtr\n-- lst <- peek lstPtr\n-- addForeignPtrFinalizer rdKafkaGroupListDestroy lstPtr\n-- return $ Right lstPtr\n-- e -> return $ Left e\n-------------------------------------------------------------------------------------------------\n\n-- rd_kafka_message\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_message_destroy\"\n rdKafkaMessageDestroyF :: FunPtr (Ptr RdKafkaMessageT -> IO ())\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_message_destroy\"\n rdKafkaMessageDestroy :: Ptr RdKafkaMessageT -> IO ()\n\n-- rd_kafka_conf\n{#fun unsafe rd_kafka_conf_new as ^\n {} -> `RdKafkaConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_conf_destroy\"\n rdKafkaConfDestroy :: FunPtr (Ptr RdKafkaConfT -> IO ())\n\n{#fun unsafe rd_kafka_conf_dup as ^\n {`RdKafkaConfTPtr'} -> `RdKafkaConfTPtr' #}\n\n{#fun unsafe 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 unsafe rd_kafka_conf_dump as ^\n {`RdKafkaConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n{#fun unsafe rd_kafka_conf_dump_free as ^\n {id `Ptr CString', cIntConv `CSize'} -> `()' #}\n\n{#fun unsafe rd_kafka_conf_properties_show as ^\n {`CFilePtr'} -> `()' #}\n\n-- rd_kafka_topic_conf\n{#fun unsafe rd_kafka_topic_conf_new as ^\n {} -> `RdKafkaTopicConfTPtr' #}\n{#fun unsafe rd_kafka_topic_conf_dup as ^\n {`RdKafkaTopicConfTPtr'} -> `RdKafkaTopicConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_conf_destroy\"\n rdKafkaTopicConfDestroy :: FunPtr (Ptr RdKafkaTopicConfT -> IO ())\n\n{#fun unsafe 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 unsafe rd_kafka_topic_conf_dump as ^\n {`RdKafkaTopicConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n-- rd_kafka\n{#fun unsafe rd_kafka_new as ^\n {enumToCInt `RdKafkaTypeT', `RdKafkaConfTPtr', id `CCharBufPointer', cIntConv `CSize'} \n -> `RdKafkaTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_destroy\"\n rdKafkaDestroy :: FunPtr (Ptr RdKafkaT -> IO ())\n\nnewRdKafkaT :: RdKafkaTypeT -> RdKafkaConfTPtr -> IO (Either String 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 peekCString charPtr >>= return . Left\n else do\n addForeignPtrFinalizer rdKafkaDestroy ret\n return $ Right ret\n\n{#fun unsafe rd_kafka_brokers_add as ^\n {`RdKafkaTPtr', `String'} -> `Int' #}\n\n{#fun unsafe rd_kafka_set_log_level as ^\n {`RdKafkaTPtr', `Int'} -> `()' #}\n\n-- rd_kafka consume\n\n{#fun unsafe 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 unsafe rd_kafka_consume_stop as rdKafkaConsumeStopInternal\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\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 unsafe rd_kafka_offset_store as rdKafkaOffsetStore\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', cIntConv `CInt64T'} \n -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka produce\n\n{#fun unsafe rd_kafka_produce as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', castPtr `Word8Ptr', \n cIntConv `CSize', castPtr `Word8Ptr', cIntConv `CSize', castPtr `Word8Ptr'}\n -> `Int' #}\n\n{#fun unsafe rd_kafka_produce_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', `RdKafkaMessageTPtr', `Int'} -> `Int' #}\n\ncastMetadata :: Ptr (Ptr RdKafkaMetadataT) -> Ptr (Ptr ())\ncastMetadata ptr = castPtr ptr\n\n-- rd_kafka_metadata\n\n{#fun unsafe rd_kafka_metadata as ^\n {`RdKafkaTPtr', boolToCInt `Bool', `RdKafkaTopicTPtr', \n castMetadata `Ptr (Ptr RdKafkaMetadataT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{# fun unsafe rd_kafka_metadata_destroy as ^\n {castPtr `Ptr RdKafkaMetadataT'} -> `()' #}\n\n{#fun unsafe rd_kafka_poll as ^\n {`RdKafkaTPtr', `Int'} -> `Int' #}\n\n{#fun unsafe rd_kafka_outq_len as ^\n {`RdKafkaTPtr'} -> `Int' #}\n\n{#fun unsafe rd_kafka_dump as ^\n {`CFilePtr', `RdKafkaTPtr'} -> `()' #}\n\n\n-- rd_kafka_topic\n{#fun unsafe rd_kafka_topic_name as ^\n {`RdKafkaTopicTPtr'} -> `String' #}\n\n{#fun unsafe rd_kafka_topic_new as ^\n {`RdKafkaTPtr', `String', `RdKafkaTopicConfTPtr'} -> `RdKafkaTopicTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_destroy\"\n rdKafkaTopicDestroy :: FunPtr (Ptr RdKafkaTopicT -> IO ())\n\nnewRdKafkaTopicT :: RdKafkaTPtr -> String -> RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- rdKafkaTopicConfDup topicConfPtr\n ret <- rdKafkaTopicNew kafkaPtr topic duper\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then kafkaErrnoString >>= return . Left\n else do\n addForeignPtrFinalizer rdKafkaTopicDestroy ret\n return $ Right ret\n\n-- Marshall \/ Unmarshall\nenumToCInt :: Enum a => a -> CInt\nenumToCInt = fromIntegral . fromEnum\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\nboolToCInt :: Bool -> CInt\nboolToCInt True = CInt 1\nboolToCInt False = CInt 0\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":"593af3e57dbcbdbd06fc80b59412a7113b4259c8","subject":"Remove commented out code.","message":"Remove commented out code.\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#} 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","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 let m' = do\n x <- m\n -- _ <- waitForStatus\n -- throwIfErrorStatus\n return x\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":"5806b9e49d30ecec55211bda08bba1a347ff0a68","subject":"Use req\/resp as names for type parameters instead of o\/i.","message":"Use req\/resp as names for type parameters instead of o\/i.\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\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 mempty 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 -> C.withForeignPtr bb $ \\bb' -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb'\n ]\n finish = do\n C.withForeignPtr bb $ \\_ -> return () --touch\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bb <- 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 bb\n ]\n finish = do\n recvBb <- C.peek bb\n C.free bb\n writeIORef value =<< if recvBb \/= C.nullPtr\n then liftM Just (addBBFinalizer recvBb >>= toLazyByteString)\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 <- 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 putStrLn \"clientWaitForInitialMetadata(..)\"\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 putStrLn (\"metadata: \" ++ show md)\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err -> do\n putStrLn \"clientWaitForInitialMetadata: callBatch failed\"\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n putStrLn \"clientReadInitialMetadata(..)\"\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n putStrLn \"clientRead(..)\"\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n putStrLn \"recvMessage(..)\"\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 ())\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n callBatch crw [ OpX recvStatusOp ]\n Just _ -> return (RpcOk ())\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n -- clientWaitForStatus crw\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\nclientSendClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendClose 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\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\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\nsendClose :: Rpc req resp ()\nsendClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ncallBidi :: ClientContext -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _ deadline) method = 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 []\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\nassertCallOk :: CallError -> IO ()\nassertCallOk CallOk = return ()\nassertCallOk status = gprAssert (\"call status: \" ++ show status)\n\ngprAssert :: Show a => a -> IO b\ngprAssert = throwIO . GprAssertException . show\n\ndata GprAssertException = GprAssertException String deriving Show\ninstance Exception GprAssertException\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","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\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 mempty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ndata Client o i = Client { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder o\n , clientDecoder :: Decoder i\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 -> C.withForeignPtr bb $ \\bb' -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb'\n ]\n finish = do\n C.withForeignPtr bb $ \\_ -> return () --touch\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bb <- 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 bb\n ]\n finish = do\n recvBb <- C.peek bb\n C.free bb\n writeIORef value =<< if recvBb \/= C.nullPtr\n then liftM Just (addBBFinalizer recvBb >>= toLazyByteString)\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 <- 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 putStrLn \"clientWaitForInitialMetadata(..)\"\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 putStrLn (\"metadata: \" ++ show md)\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err -> do\n putStrLn \"clientWaitForInitialMetadata: callBatch failed\"\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n putStrLn \"clientReadInitialMetadata(..)\"\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n putStrLn \"clientRead(..)\"\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n putStrLn \"recvMessage(..)\"\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 ())\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n callBatch crw [ OpX recvStatusOp ]\n Just _ -> return (RpcOk ())\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n -- clientWaitForStatus crw\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\nclientSendClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendClose 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 o i a = ReaderT (Client o i) (ExceptT RpcError IO) a\n\naskCrw :: Rpc o i ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc o i (Decoder i)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc o i (Encoder o)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc o i a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithClient :: Client o i -> Rpc o i 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\nreceiveMessage :: Rpc o i (Maybe i)\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 o i [i]\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 :: o -> Rpc o i ()\nsendMessage o = do\n crw <- askCrw\n encoder <- askEncoder\n x <- joinReply =<< liftIO (encoder o)\n joinReply =<< liftIO (clientWrite crw x)\n\nsendClose :: Rpc o i ()\nsendClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendClose crw)\n\ncloseCall :: Rpc o i ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ncallBidi :: ClientContext -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _ deadline) method = 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 []\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\nassertCallOk :: CallError -> IO ()\nassertCallOk CallOk = return ()\nassertCallOk status = gprAssert (\"call status: \" ++ show status)\n\ngprAssert :: Show a => a -> IO b\ngprAssert = throwIO . GprAssertException . show\n\ndata GprAssertException = GprAssertException String deriving Show\ninstance Exception GprAssertException\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":"9f559dc061dacdd9017ec0a1119445b732752d18","subject":"fixes for 7.8","message":"fixes for 7.8\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\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 , setDatasetProjection\n , datasetGeotransform\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 , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\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.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\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.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.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 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\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection =\n liftIO . ({#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString)\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n unsafeUseAsCString (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\ndatasetGeotransform :: Dataset s a 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 == CE_None\n then liftM Just (peek p)\n else return Nothing\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 = dataType (undefined :: 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 (bx :+: by) =\n bandMaskType band >>= \\case\n MaskNoData ->\n liftM2 mkValueUVector (noDataOrFail band) (read_ band)\n MaskAllValid ->\n liftM mkAllValidValueUVector (read_ band)\n _ ->\n liftM2 mkMaskedValueUVector (read_ =<< bandMask band) (read_ band)\n where\n sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n read_ :: forall a'. GDALType a' => Band s a' t -> GDAL s (St.Vector a')\n read_ b = liftIO $ do\n vec <- M.new (bx*by)\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 (dataType (undefined :: 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 (dataType (undefined :: a')))\n 0\n 0\n G.unsafeFreeze vec\n{-# INLINE readBand #-}\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@(bx :+: by) uvec =\n bandMaskType band >>= \\case\n MaskNoData ->\n noDataOrFail band >>= write band . flip toGVecWithNodata uvec\n MaskAllValid ->\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band)\n (toGVec uvec)\n _ -> do let (mask, vec) = toGVecWithMask uvec\n write band vec\n mBand <- bandMask band\n write mBand mask\n where\n write :: forall a'. GDALType a'\n => RWBand s a' -> St.Vector a' -> GDAL s ()\n write band' 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 (dataType (undefined :: a')))\n 0\n 0\n{-# INLINE writeBand #-}\n\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 -> BlockIx -> 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\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\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = addCleanup flush $ 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 flush f = when f (bandDataset band >>= flushCache)\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = dataType (undefined :: 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 = dataType (undefined :: 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 DeriveFunctor #-}\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\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 , setDatasetProjection\n , datasetGeotransform\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 , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\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.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\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.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.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 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\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection =\n liftIO . ({#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString)\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n unsafeUseAsCString (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\ndatasetGeotransform :: Dataset s a 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 == CE_None\n then liftM Just (peek p)\n else return Nothing\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 = dataType (undefined :: 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 (bx :+: by) =\n bandMaskType band >>= \\case\n MaskNoData ->\n liftM2 mkValueUVector (noDataOrFail band) (read_ band)\n MaskAllValid ->\n liftM mkAllValidValueUVector (read_ band)\n _ ->\n liftM2 mkMaskedValueUVector (read_ =<< bandMask band) (read_ band)\n where\n sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n read_ :: forall a'. GDALType a' => Band s a' t -> GDAL s (St.Vector a')\n read_ b = liftIO $ do\n vec <- M.new (bx*by)\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 (dataType (undefined :: 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 (dataType (undefined :: a')))\n 0\n 0\n G.unsafeFreeze vec\n{-# INLINE readBand #-}\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@(bx :+: by) uvec =\n bandMaskType band >>= \\case\n MaskNoData ->\n noDataOrFail band >>= write band . flip toGVecWithNodata uvec\n MaskAllValid ->\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band)\n (toGVec uvec)\n _ -> do let (mask, vec) = toGVecWithMask uvec\n write band vec\n mBand <- bandMask band\n write mBand mask\n where\n write :: forall a'. GDALType a'\n => RWBand s a' -> St.Vector a' -> GDAL s ()\n write band' 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 (dataType (undefined :: a')))\n 0\n 0\n{-# INLINE writeBand #-}\n\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 -> BlockIx -> 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\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\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = addCleanup flush $ 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 flush f = when f (bandDataset band >>= flushCache)\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = dataType (undefined :: 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 = dataType (undefined :: 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":"a4007be8b35218dd3499f4802f03b123e36fd3a3","subject":"Add property functions for Char type","message":"Add property functions for Char type","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 objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\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\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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 writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fc40308a695427790078aa8b45cc7447f9cb20d5","subject":"Add yet another property for read access.","message":"Add yet another property for read access.","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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n newAttrFromMaybeStringProperty,\n readAttrFromMaybeStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n readAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nreadAttrFromMaybeStringProperty :: GObjectClass gobj => String -> ReadAttr gobj (Maybe String)\nreadAttrFromMaybeStringProperty propName =\n readAttr (objectGetPropertyMaybeString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject gtype propName)\n \nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n\nreadAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> ReadAttr gobj gobj'\nreadAttrFromObjectProperty propName gtype =\n readAttr (objectGetPropertyGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n newAttrFromMaybeStringProperty,\n readAttrFromMaybeStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nreadAttrFromMaybeStringProperty :: GObjectClass gobj => String -> ReadAttr gobj (Maybe String)\nreadAttrFromMaybeStringProperty propName =\n readAttr (objectGetPropertyMaybeString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"03f367e2dbfb2c3a0c7f7c793f698c9171199c22","subject":"Bind to _hpx_run instead, but don't know how to handle variadic args","message":"Bind to _hpx_run instead, but don't know how to handle variadic args\n","repos":"iu-parfunc\/haskell-hpx,iu-parfunc\/haskell-hpx","old_file":"Foreign\/HPX.chs","new_file":"Foreign\/HPX.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.HPX\n-- Copyright :\n-- License : BSD\n--\n-- Haskell Bindings for HPX.\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.HPX {-\n(\n Action(..),\n Foreign.HPX.init, initWith,\n registerAction,\n run, shutdown\n)\n -} where\n\nimport Foreign\nimport Foreign.C\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.C2HS\n\nimport System.Environment (getProgName, getArgs)\nimport Control.Monad (liftM, liftM2)\nimport Data.Map as M\nimport Data.IORef\nimport System.IO.Unsafe (unsafePerformIO)\n\n#include \"hpx\/hpx.h\"\n\n--------------------------------------------------------------------------------\n-- Global Mutable Structures\n--------------------------------------------------------------------------------\n\n{-# NOINLINE hpxActionTable #-}\nhpxActionTable :: IORef (M.Map (FunPtr a) Action)\nhpxActionTable = unsafePerformIO$ newIORef M.empty\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Action = Action { useAction :: {# type hpx_action_t #} }\n deriving (Eq, Show)\n\ntype Handler = {#type hpx_action_handler_t#}\n\n--------------------------------------------------------------------------------\n-- Initialization\n--------------------------------------------------------------------------------\n\n{-# INLINEABLE init #-}\ninit :: IO [String]\ninit = initWith =<< (liftM2 (:) getProgName $ getArgs)\n\ninitWith :: [String] -> IO [String]\ninitWith argv =\n withMany withCString argv $ \\argv' -> -- argv' :: [CString]\n withArray argv' $ \\argv'' -> -- argv'' :: Ptr CString\n with argv'' $ \\argv''' -> do -- argv''' :: Ptr (Ptr CString)\n\n (r, argc) <- hpxInit (length argv) argv'''\n -- TODO throw exception on 'r'\n x <- peekArray argc =<< peek argv''' -- :: [Ptr CString]\n mapM peekCString x\n\n\n{# fun unsafe hpx_init as ^\n { withIntConv* `Int' peekIntConv*\n , id `Ptr (Ptr (Ptr CChar))'\n } -> `Int' cIntConv #}\n\n--------------------------------------------------------------------------------\n-- Action Registration\n--------------------------------------------------------------------------------\n\nforeign import ccall \"wrapper\"\n wrap :: (Ptr () -> IO CInt) -> IO (FunPtr (Ptr () -> IO CInt))\n\nforeign import ccall \"dynamic\"\n unwrap :: FunPtr (Ptr () -> IO CInt) -> (Ptr () -> IO CInt)\n\n--Different # of args:\n\n-- {# fun unsafe hpx_register_action as ^\n-- { alloca- `Action' peekAction*\n-- , withCString* `String'\n-- , id `Handler'\n-- } -> `Int' cIntConv #}\n-- where peekAction = liftM Action . peek\n\nhpxRegisterAction = undefined\n\n{-# INLINEABLE registerAction#-}\nregisterAction :: String -> (Ptr () -> IO CInt) -> IO ()\nregisterAction s p = do\n ptr <- wrap p\n (r, act) <- hpxRegisterAction s ptr\n -- TODO throw exception on 'r'\n modifyIORef hpxActionTable (M.insert ptr act)\n putStrLn$ \"Registered action pointer: \"++ show ptr ++ \" with key: \"++ show s\n\n--------------------------------------------------------------------------------\n-- Runtime Calls\n--------------------------------------------------------------------------------\n\n{# fun _hpx_run as ^\n { withAction* `Action'\n , cIntConv `Int'\n-- , id `Ptr ()'\n } -> `Int' cIntConv #}\n where withAction = with . useAction\n\n\nrun :: (Ptr () -> IO CInt) -> Ptr () -> Int -> IO Int\nrun p args size = do\n tbl <- readIORef hpxActionTable\n ptr <- wrap p\n case M.lookup ptr tbl of\n Nothing -> error$ \"ERROR: Invalid action pointer: \"++ show ptr\n Just action -> hpxRun action size -- args\n\n{# fun hpx_shutdown as ^ { cIntConv `Int' } -> `()' #}\n\nshutdown :: Int -> IO ()\nshutdown = hpxShutdown\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.HPX\n-- Copyright :\n-- License : BSD\n--\n-- Haskell Bindings for HPX.\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.HPX {-\n(\n Action(..),\n Foreign.HPX.init, initWith,\n registerAction,\n run, shutdown\n)\n -} where\n\nimport Foreign\nimport Foreign.C\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.C2HS\n\nimport System.Environment (getProgName, getArgs)\nimport Control.Monad (liftM, liftM2)\nimport Data.Map as M\nimport Data.IORef\nimport System.IO.Unsafe (unsafePerformIO)\n\n#include \"hpx\/hpx.h\"\n\n--------------------------------------------------------------------------------\n-- Global Mutable Structures\n--------------------------------------------------------------------------------\n\n{-# NOINLINE hpxActionTable #-}\nhpxActionTable :: IORef (M.Map (FunPtr a) Action)\nhpxActionTable = unsafePerformIO$ newIORef M.empty\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Action = Action { useAction :: {# type hpx_action_t #} }\n deriving (Eq, Show)\n\ntype Handler = {#type hpx_action_handler_t#}\n\n--------------------------------------------------------------------------------\n-- Initialization\n--------------------------------------------------------------------------------\n\n{-# INLINEABLE init #-}\ninit :: IO [String]\ninit = initWith =<< (liftM2 (:) getProgName $ getArgs)\n\ninitWith :: [String] -> IO [String]\ninitWith argv =\n withMany withCString argv $ \\argv' -> -- argv' :: [CString]\n withArray argv' $ \\argv'' -> -- argv'' :: Ptr CString\n with argv'' $ \\argv''' -> do -- argv''' :: Ptr (Ptr CString)\n\n (r, argc) <- hpxInit (length argv) argv'''\n -- TODO throw exception on 'r'\n x <- peekArray argc =<< peek argv''' -- :: [Ptr CString]\n mapM peekCString x\n\n\n{# fun unsafe hpx_init as ^\n { withIntConv* `Int' peekIntConv*\n , id `Ptr (Ptr (Ptr CChar))'\n } -> `Int' cIntConv #}\n\n--------------------------------------------------------------------------------\n-- Action Registration\n--------------------------------------------------------------------------------\n\nforeign import ccall \"wrapper\"\n wrap :: (Ptr () -> IO CInt) -> IO (FunPtr (Ptr () -> IO CInt))\n\nforeign import ccall \"dynamic\"\n unwrap :: FunPtr (Ptr () -> IO CInt) -> (Ptr () -> IO CInt)\n\n--Different # of args:\n\n-- {# fun unsafe hpx_register_action as ^\n-- { alloca- `Action' peekAction*\n-- , withCString* `String'\n-- , id `Handler'\n-- } -> `Int' cIntConv #}\n-- where peekAction = liftM Action . peek\n\nhpxRegisterAction = undefined\n\n{-# INLINEABLE registerAction#-}\nregisterAction :: String -> (Ptr () -> IO CInt) -> IO ()\nregisterAction s p = do\n ptr <- wrap p\n (r, act) <- hpxRegisterAction s ptr\n -- TODO throw exception on 'r'\n modifyIORef hpxActionTable (M.insert ptr act)\n putStrLn$ \"Registered action pointer: \"++ show ptr ++ \" with key: \"++ show s\n\n--------------------------------------------------------------------------------\n-- Runtime Calls\n--------------------------------------------------------------------------------\n\n-- hpx_run must have been renamed\n\n-- {# fun hpx_run as ^\n-- { withAction* `Action'\n-- , id `Ptr ()'\n-- , cIntConv `Int'\n-- } -> `Int' cIntConv #}\n-- where withAction = with . useAction\n\nhpxRun = undefined\n\nrun :: (Ptr () -> IO CInt) -> Ptr () -> Int -> IO Int\nrun p args size = do\n tbl <- readIORef hpxActionTable\n ptr <- wrap p\n case M.lookup ptr tbl of\n Nothing -> error$ \"ERROR: Invalid action pointer: \"++ show ptr\n Just action -> hpxRun action args size\n\n{# fun hpx_shutdown as ^ { cIntConv `Int' } -> `()' #}\n\nshutdown :: Int -> IO ()\nshutdown = hpxShutdown\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"369f9069030449483d06cdeb216bb43f082795de","subject":"Trac #1250: binding to the wrong signal name for script-alert","message":"Trac #1250: binding to the wrong signal name for script-alert\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/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 webViewGetDomDocument,\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-- 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-- 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 \"script_alert\")\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\nwebViewGetDomDocument :: WebView -> IO Document\nwebViewGetDomDocument webview =\n makeNewGObject mkDocument $ {#call webkit_web_view_get_dom_document#} webview\n\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 webViewGetDomDocument,\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-- 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-- 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\nwebViewGetDomDocument :: WebView -> IO Document\nwebViewGetDomDocument webview =\n makeNewGObject mkDocument $ {#call webkit_web_view_get_dom_document#} webview\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"bb6290584f0475552da2e331d4d3decdd330ad2d","subject":"new CLKernel type","message":"new CLKernel type\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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n CLProgramInfo_, CLBuildStatus_,CLKernel\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..),\n -- * Functions\n clSuccess, wrapPError, wrapCheckSuccess, wrapGetInfo, getCLValue, getEnumCL,\n getDeviceLocalMemType, bitmaskToFlags,\n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\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#}\ntype CLKernel = {#type cl_kernel#}\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#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\n\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CL_SUCCESS\n then return $ Right v\n else return $ Left errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . toEnum . fromIntegral\n\nwrapGetInfo :: Storable a => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) \n -> IO (Either CLError b)\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap (Right . fconvert) $ peek dat\n else return . Left . toEnum . fromIntegral $ errcode\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . getEnumCL\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . getEnumCL\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . getEnumCL\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CL_EXEC_ERROR\n | otherwise = Just . getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes = bitmaskToFlags [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n CLProgramInfo_, CLBuildStatus_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..),\n -- * Functions\n clSuccess, wrapPError, wrapCheckSuccess, wrapGetInfo, getCLValue, getEnumCL,\n getDeviceLocalMemType, bitmaskToFlags,\n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\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#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\n\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CL_SUCCESS\n then return $ Right v\n else return $ Left errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . toEnum . fromIntegral\n\nwrapGetInfo :: Storable a => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) \n -> IO (Either CLError b)\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap (Right . fconvert) $ peek dat\n else return . Left . toEnum . fromIntegral $ errcode\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . getEnumCL\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . getEnumCL\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . getEnumCL\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CL_EXEC_ERROR\n | otherwise = Just . getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes = bitmaskToFlags [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"58e7707f926f0101f922da9215365d3163ea043d","subject":"Make safe calls to g_object_get_property This is too complex a function for use to be confident that it's ok to make an unsafe foreign call to it. This probably does not fix Axel's current segfault bug.","message":"Make safe calls to g_object_get_property\nThis is too complex a function for use to be confident that it's ok to make an\nunsafe foreign call to it.\nThis probably does not fix Axel's current segfault bug.\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 objectSetPropertyGObject,\n objectGetPropertyGObject,\n \n objectSetPropertyInternal,\n objectGetPropertyInternal,\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 newAttrFromMaybeStringProperty,\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 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\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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString 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 objectSetPropertyGObject,\n objectGetPropertyGObject,\n \n objectSetPropertyInternal,\n objectGetPropertyInternal,\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 newAttrFromMaybeStringProperty,\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\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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString 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":"e58e17e94c0078197ee97170e4a93bf3eda163cf","subject":"Make `unsafePerformIO` a qualified import.","message":"Make `unsafePerformIO` a qualified import.\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 #-}\nmodule Graphics.UI.FLTK.LowLevel.FL\n (\n Option(..),\n run,\n check,\n ready,\n option,\n addAwakeHandler,\n getAwakeHandler_,\n display,\n ownColormap,\n getSystemColors,\n foreground,\n background,\n background2,\n setScheme,\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__)\n glVisual,\n glVisualWithAlist,\n#endif\n scheme,\n wait,\n setWait,\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 -- * 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 )\nwhere\n#include \"Fl_C.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\nimport Data.IORef\nimport Foreign.C.Types\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 )\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified System.IO.Unsafe as Unsafe (unsafePerformIO)\n#c\n enum Option {\n ArrowFocus = OPTION_ARROW_FOCUS,\n VisibleFocus = OPTION_VISIBLE_FOCUS,\n DndText = OPTION_DND_TEXT,\n ShowTooltips = OPTION_SHOW_TOOLTIPS,\n Last = 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\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 Int\noption o = {#call Fl_option as fl_option #} (cFromEnum o) >>= return . fromIntegral\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 {} -> `String' #}\n\ndisplay :: String -> IO ()\ndisplay text = withCString text $ \\str -> {#call Fl_display as fl_display #} str\n{# fun Fl_visual as visual\n {cFromEnum `Mode'} -> `Int' #}\n#if !defined(__APPLE__)\n{# fun Fl_gl_visual as glVisual\n {cFromEnum `Mode'} -> `Int' #}\n{# fun Fl_gl_visual_with_alist as glVisualWithAlist\n {cFromEnum `Mode', id `Ptr CInt'} -> `Int' #}\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-- | In the function below marked `pure`, c2hs uses `unsafePerformIO` unqualified causing\n-- | a compile error if it imported qualifed. This is a workaround.\nunsafePerformIO :: IO a -> a\nunsafePerformIO = Unsafe.unsafePerformIO\n{# fun pure Fl_scheme as scheme\n {} -> `String' #}\nsetScheme :: String -> IO Int\nsetScheme sch = withCString sch $ \\str -> {#call Fl_set_scheme as fl_set_scheme #} str >>= return . fromIntegral\nisScheme :: String -> IO Bool\nisScheme sch = withCString 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 setWait\n { `Double' } -> `Double' #}\n{# fun Fl_readqueue as readqueue\n { } -> `Ref Widget' unsafeToRef #}\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 { } -> `Ref Window' unsafeToRef #}\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 ()' } -> `Ref Window' unsafeToRef #}\nnextWindow :: (Parent a Window) => Ref a -> IO (Ref Window)\nnextWindow currWindow =\n withRef currWindow nextWindow'\n{# fun Fl_modal as modal\n { } -> `Ref Window' unsafeToRef #}\n{# fun Fl_grab as grab\n { } -> `Ref Window' unsafeToRef #}\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{# fun Fl_event_button as eventButton\n { } -> `MouseButton' cToEnum #}\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-- foldModifiers :: [KeyboardCode] -> CInt\n-- foldModifiers codes =\n-- let validKeysyms = map cFromEnum (filter (\\c -> c `elem` validKeyboardStates) codes)\n-- in\n-- case validKeysyms of\n-- [] -> (-1)\n-- (k:ks) -> foldl (\\accum k' -> accum .&. k') k ks\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 { } -> `KeyboardCode' cToEnum #}\n{# fun Fl_event_original_key as eventOriginalKey\n { } -> `KeyboardCode' cToEnum #}\n{# fun Fl_event_key_pressed as eventKeyPressed\n {cFromEnum `KeyboardCode' } -> `Bool' toBool #}\n{# fun Fl_get_key as getKey\n {cFromEnum `KeyboardCode' } -> `Bool' toBool #}\n{# fun Fl_event_text as eventText\n { } -> `String' #}\n{# fun Fl_event_length as eventLength\n { } -> `Int' #}\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 { } -> `Ref Widget' unsafeToRef #}\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 { } -> `Ref Widget' unsafeToRef #}\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 { } -> `Ref Widget' unsafeToRef #}\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_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 { `String',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_copy_with_destination as copyWithDestination\n { `String',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_paste_with_source as pasteWithSource\n { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\npaste :: (Parent a Widget) => Ref a -> Maybe Int -> IO ()\npaste widget (Just clipboard) = withRef widget ((flip pasteWithSource) clipboard)\npaste widget Nothing = withRef widget ((flip pasteWithSource) 0)\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 -> Int -> Int -> Int -> 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- `Word8' peekIntConv*,\n alloca- `Word8' peekIntConv*,\n alloca- `Word8' peekIntConv*\n } -> `()' supressWarningAboutRes #}\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' } -> `String' #}\n{# fun Fl_get_font_name_with_attributes as getFontNameWithAttributes'\n { cFromFont `Font', alloca- `Maybe FontAttribute' toAttribute* } -> `String' #}\ntoAttribute :: Ptr CInt -> IO (Maybe FontAttribute)\ntoAttribute ptr =\n do\n attributeCode <- peekIntConv ptr\n return $ cToFontAttribute attributeCode\ngetFontName :: Font -> IO (String, 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',`String' } -> `()' 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 { `String' } -> `Font' cToFont #}\n{# fun Fl_get_boxtype as getBoxtype'\n { cFromEnum `Boxtype' } -> `FunPtr BoxDrawFPrim' id #}\n\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","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.FL\n (\n Option(..),\n run,\n check,\n ready,\n option,\n addAwakeHandler,\n getAwakeHandler_,\n display,\n ownColormap,\n getSystemColors,\n foreground,\n background,\n background2,\n setScheme,\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__)\n glVisual,\n glVisualWithAlist,\n#endif\n scheme,\n wait,\n setWait,\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 -- * 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 )\nwhere\n#include \"Fl_C.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\nimport Data.IORef\nimport Foreign.C.Types\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 )\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport System.IO.Unsafe (unsafePerformIO)\n#c\n enum Option {\n ArrowFocus = OPTION_ARROW_FOCUS,\n VisibleFocus = OPTION_VISIBLE_FOCUS,\n DndText = OPTION_DND_TEXT,\n ShowTooltips = OPTION_SHOW_TOOLTIPS,\n Last = OPTION_LAST\n };\n#endc\n\n{#enum Option {} deriving (Show) #}\n\nptrToGlobalEventHandler :: IORef (FunPtr GlobalEventHandlerPrim)\nptrToGlobalEventHandler = unsafePerformIO $ do\n initialHandler <- toGlobalEventHandlerPrim (\\_ -> return (-1))\n newIORef initialHandler\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 Int\noption o = {#call Fl_option as fl_option #} (cFromEnum o) >>= return . fromIntegral\n\nunsafeToCallbackPrim :: GlobalCallback -> FunPtr CallbackPrim\nunsafeToCallbackPrim = 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 {} -> `String' #}\n\ndisplay :: String -> IO ()\ndisplay text = withCString text $ \\str -> {#call Fl_display as fl_display #} str\n{# fun Fl_visual as visual\n {cFromEnum `Mode'} -> `Int' #}\n#if !defined(__APPLE__)\n{# fun Fl_gl_visual as glVisual\n {cFromEnum `Mode'} -> `Int' #}\n{# fun Fl_gl_visual_with_alist as glVisualWithAlist\n {cFromEnum `Mode', id `Ptr CInt'} -> `Int' #}\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 scheme\n {} -> `String' #}\nsetScheme :: String -> IO Int\nsetScheme sch = withCString sch $ \\str -> {#call Fl_set_scheme as fl_set_scheme #} str >>= return . fromIntegral\nisScheme :: String -> IO Bool\nisScheme sch = withCString 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 setWait\n { `Double' } -> `Double' #}\n{# fun Fl_readqueue as readqueue\n { } -> `Ref Widget' unsafeToRef #}\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 { } -> `Ref Window' unsafeToRef #}\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 ()' } -> `Ref Window' unsafeToRef #}\nnextWindow :: (Parent a Window) => Ref a -> IO (Ref Window)\nnextWindow currWindow =\n withRef currWindow nextWindow'\n{# fun Fl_modal as modal\n { } -> `Ref Window' unsafeToRef #}\n{# fun Fl_grab as grab\n { } -> `Ref Window' unsafeToRef #}\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{# fun Fl_event_button as eventButton\n { } -> `MouseButton' cToEnum #}\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-- foldModifiers :: [KeyboardCode] -> CInt\n-- foldModifiers codes =\n-- let validKeysyms = map cFromEnum (filter (\\c -> c `elem` validKeyboardStates) codes)\n-- in\n-- case validKeysyms of\n-- [] -> (-1)\n-- (k:ks) -> foldl (\\accum k' -> accum .&. k') k ks\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 { } -> `KeyboardCode' cToEnum #}\n{# fun Fl_event_original_key as eventOriginalKey\n { } -> `KeyboardCode' cToEnum #}\n{# fun Fl_event_key_pressed as eventKeyPressed\n {cFromEnum `KeyboardCode' } -> `Bool' toBool #}\n{# fun Fl_get_key as getKey\n {cFromEnum `KeyboardCode' } -> `Bool' toBool #}\n{# fun Fl_event_text as eventText\n { } -> `String' #}\n{# fun Fl_event_length as eventLength\n { } -> `Int' #}\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 { } -> `Ref Widget' unsafeToRef #}\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 { } -> `Ref Widget' unsafeToRef #}\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 { } -> `Ref Widget' unsafeToRef #}\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_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 { `String',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_copy_with_destination as copyWithDestination\n { `String',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_paste_with_source as pasteWithSource\n { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\npaste :: (Parent a Widget) => Ref a -> Maybe Int -> IO ()\npaste widget (Just clipboard) = withRef widget ((flip pasteWithSource) clipboard)\npaste widget Nothing = withRef widget ((flip pasteWithSource) 0)\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 -> Int -> Int -> Int -> 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- `Word8' peekIntConv*,\n alloca- `Word8' peekIntConv*,\n alloca- `Word8' peekIntConv*\n } -> `()' supressWarningAboutRes #}\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' } -> `String' #}\n{# fun Fl_get_font_name_with_attributes as getFontNameWithAttributes'\n { cFromFont `Font', alloca- `Maybe FontAttribute' toAttribute* } -> `String' #}\ntoAttribute :: Ptr CInt -> IO (Maybe FontAttribute)\ntoAttribute ptr =\n do\n attributeCode <- peekIntConv ptr\n return $ cToFontAttribute attributeCode\ngetFontName :: Font -> IO (String, 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',`String' } -> `()' 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 { `String' } -> `Font' cToFont #}\n{# fun Fl_get_boxtype as getBoxtype'\n { cFromEnum `Boxtype' } -> `FunPtr BoxDrawFPrim' id #}\n\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","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"bfba17892c439c5cbbf1730061aaed020162c73e","subject":"Add function sourceCompletionGetInfoWindow","message":"Add function sourceCompletionGetInfoWindow\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n -- sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionGetInfoWindow,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n -- sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\n-- sourceCompletionShow :: SourceCompletionClass sc => sc\n-- -> [SourceCompletionProvider]\n-- -> \n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | The info widget is the window where the completion displays optional extra information of the\n-- proposal.\nsourceCompletionGetInfoWindow :: SourceCompletionClass sc => sc -> IO SourceCompletionInfo\nsourceCompletionGetInfoWindow sc =\n makeNewObject mkSourceCompletionInfo $\n {#call gtk_source_completion_get_info_window #}\n (toSourceCompletion sc)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate_proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move_cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move_page\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n -- sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n -- sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\n-- sourceCompletionShow :: SourceCompletionClass sc => sc\n-- -> [SourceCompletionProvider]\n-- -> \n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate_proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move_cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move_page\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fe08f5ee262670faf9c1a2f81996fc3cf0e99e19","subject":"Added SKIPDATA mode, fixed use-after-free","message":"Added SKIPDATA mode, fixed use-after-free\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 , 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\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 ({#offsetof cs_detail.groups_count#} + 1)\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr p)\n CsArchArm64 -> Arm64 <$> peek (castPtr p)\n CsArchArm -> Arm <$> peek (castPtr p)\n CsArchMips -> Mips <$> peek (castPtr p)\n CsArchPpc -> Ppc <$> peek (castPtr p)\n CsArchSparc -> Sparc <$> peek (castPtr p)\n CsArchSysz -> SysZ <$> peek (castPtr p)\n CsArchXcore -> XCore <$> peek (castPtr p)\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 :: 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 =<< {#get cs_insn->mnemonic#} p)\n <*> (peekCString =<< {#get cs_insn->op_str#} p)\n <*> (castPtr <$> {#get cs_insn->detail#} p >>= peek)\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 newCString m >>= {#set cs_insn->mnemonic#} p\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else newCString o >>= {#set cs_insn->op_str#} p\n csDetailPtr <- castPtr <$> ({#get cs_insn->detail#} p)\n poke csDetailPtr d\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 <- mapM (peek . plusPtr resPtr . ({#sizeof cs_insn#} *)) [0..resNum]\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-- TODO: decide whether we want cs_disasm_iter\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 , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , csInsnOffset\n , CsErr(..)\n , csSupport\n , csOpen\n , csClose\n , csOption\n , csErrno\n , csStrerror\n , csDisasm\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\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, withCString)\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-- TODO: what is this SKIPDATA business whose callback function\n-- we happily omitted?\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 ({#offsetof cs_detail.groups_count#} + 1)\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr p)\n CsArchArm64 -> Arm64 <$> peek (castPtr p)\n CsArchArm -> Arm <$> peek (castPtr p)\n CsArchMips -> Mips <$> peek (castPtr p)\n CsArchPpc -> Ppc <$> peek (castPtr p)\n CsArchSparc -> Sparc <$> peek (castPtr p)\n CsArchSysz -> SysZ <$> peek (castPtr p)\n CsArchXcore -> XCore <$> peek (castPtr p)\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 :: 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 =<< {#get cs_insn->mnemonic#} p)\n <*> (peekCString =<< {#get cs_insn->op_str#} p)\n <*> (castPtr <$> {#get cs_insn->detail#} p >>= peek)\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 withCString m ({#set cs_insn->mnemonic#} p)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else withCString o ({#set cs_insn->op_str#} p)\n csDetailPtr <- castPtr <$> ({#get cs_insn->detail#} p)\n poke csDetailPtr d\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 <- mapM (peek . plusPtr resPtr . ({#sizeof cs_insn#} *)) [0..resNum]\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-- TODO: decide whether we want cs_disasm_iter\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":"d8cf589e474b9d5e67cf7b84a3fe90cc07f582c0","subject":"Fixed Image.getChannel not using the MutableImage with the relevant COI set.","message":"Fixed Image.getChannel not using the MutableImage with the relevant COI set.\n","repos":"aleator\/CV,aleator\/CV,BeautifulDestinations\/CV,TomMD\/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 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, 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3c91ee25fd97e7a34b58fdc649433400575dd288","subject":"Make MessageID a newtype.","message":"Make MessageID a newtype.\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Statusbar.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Statusbar.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Statusbar\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/11\/06 20:46:10 $\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-- Report messages of minor importance to the user\n--\nmodule Graphics.UI.Gtk.Display.Statusbar (\n-- * Detail\n-- \n-- | A 'Statusbar' is usually placed along the bottom of an application's main\n-- 'Window'. It may provide a regular commentary of the application's status\n-- (as is usually the case in a web browser, for example), or may be used to\n-- simply output a message when the status changes, (when an upload is complete\n-- in an FTP client, for example). It may also have a resize grip (a triangular\n-- area in the lower right corner) which can be clicked on to resize the window\n-- containing the statusbar.\n--\n-- Status bars in Gtk+ maintain a stack of messages. The message at the top\n-- of the each bar's stack is the one that will currently be displayed.\n--\n-- Any messages added to a statusbar's stack must specify a \/context_id\/\n-- that is used to uniquely identify the source of a message. This context_id\n-- can be generated by 'statusbarGetContextId', given a message and the\n-- statusbar that it will be added to. Note that messages are stored in a\n-- stack, and when choosing which message to display, the stack structure is\n-- adhered to, regardless of the context identifier of a message.\n--\n-- Status bars are created using 'statusbarNew'.\n--\n-- Messages are added to the bar's stack with 'statusbarPush'.\n--\n-- The message at the top of the stack can be removed using 'statusbarPop'.\n-- A message can be removed from anywhere in the stack if its message_id was\n-- recorded at the time it was added. This is done using 'statusbarRemove'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Box'\n-- | +----'HBox'\n-- | +----Statusbar\n-- @\n\n-- * Types\n Statusbar,\n StatusbarClass,\n castToStatusbar,\n toStatusbar,\n ContextId,\n MessageId,\n\n-- * Constructors\n statusbarNew,\n\n-- * Methods\n statusbarGetContextId,\n statusbarPush,\n statusbarPop,\n statusbarRemove,\n statusbarSetHasResizeGrip,\n statusbarGetHasResizeGrip,\n\n-- * Attributes\n statusbarHasResizeGrip,\n\n-- * Signals\n onTextPopped,\n afterTextPopped,\n onTextPushed,\n afterTextPushed,\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\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-- Constructors\n\n-- | Creates a new 'Statusbar' ready for messages.\n--\nstatusbarNew :: IO Statusbar\nstatusbarNew =\n makeNewObject mkStatusbar $\n liftM (castPtr :: Ptr Widget -> Ptr Statusbar) $\n {# call unsafe statusbar_new #}\n\n--------------------\n-- Methods\n\ntype ContextId = {#type guint#}\n\n-- | Returns a new context identifier, given a description of the actual\n-- context. This id can be used to later remove entries form the Statusbar.\n--\nstatusbarGetContextId :: StatusbarClass self => self\n -> String -- ^ @contextDescription@ - textual description of what context the\n -- new message is being used in.\n -> IO ContextId -- ^ returns an id that can be used to later remove entries\n -- ^ from the Statusbar.\nstatusbarGetContextId self contextDescription =\n withUTFString contextDescription $ \\contextDescriptionPtr ->\n {# call unsafe statusbar_get_context_id #}\n (toStatusbar self)\n contextDescriptionPtr\n\nnewtype MessageId = MessageId {#type guint#}\n\n-- | Pushes a new message onto the Statusbar's stack. It will\n-- be displayed as long as it is on top of the stack.\n--\nstatusbarPush :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the message's context id, as returned by\n -- 'statusbarGetContextId'.\n -> String -- ^ @text@ - the message to add to the statusbar.\n -> IO MessageId -- ^ returns the message's new message id for use with\n -- 'statusbarRemove'.\nstatusbarPush self contextId text =\n liftM MessageId $\n withUTFString text $ \\textPtr ->\n {# call statusbar_push #}\n (toStatusbar self)\n contextId\n textPtr\n\n-- | Removes the topmost message that has the correct context.\n--\nstatusbarPop :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the context identifier used when the\n -- message was added.\n -> IO ()\nstatusbarPop self contextId =\n {# call statusbar_pop #}\n (toStatusbar self)\n contextId\n\n-- | Forces the removal of a message from a statusbar's stack. The exact\n-- @contextId@ and @messageId@ must be specified.\n--\nstatusbarRemove :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - a context identifier.\n -> MessageId -- ^ @messageId@ - a message identifier, as returned by\n -- 'statusbarPush'.\n -> IO ()\nstatusbarRemove self contextId (MessageId messageId) =\n {# call statusbar_remove #}\n (toStatusbar self)\n contextId\n messageId\n\n-- | Sets whether the statusbar has a resize grip. @True@ by default.\n--\nstatusbarSetHasResizeGrip :: StatusbarClass self => self -> Bool -> IO ()\nstatusbarSetHasResizeGrip self setting =\n {# call statusbar_set_has_resize_grip #}\n (toStatusbar self)\n (fromBool setting)\n\n-- | Returns whether the statusbar has a resize grip.\n--\nstatusbarGetHasResizeGrip :: StatusbarClass self => self -> IO Bool\nstatusbarGetHasResizeGrip self =\n liftM toBool $\n {# call unsafe statusbar_get_has_resize_grip #}\n (toStatusbar self)\n\n--------------------\n-- Attributes\n\n-- | Whether the statusbar has a grip for resizing the toplevel window.\n--\n-- Default value: @True@\n--\nstatusbarHasResizeGrip :: StatusbarClass self => Attr self Bool\nstatusbarHasResizeGrip = newAttr\n statusbarGetHasResizeGrip\n statusbarSetHasResizeGrip\n\n--------------------\n-- Signals\n\n-- | Called if a message is removed.\n--\nonTextPopped, afterTextPopped :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" False self (user . fromIntegral)\nafterTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" True self (user . fromIntegral)\n\n-- | Called if a message is pushed on top of the\n-- stack.\n--\nonTextPushed, afterTextPushed :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" False self (user . fromIntegral)\nafterTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" True self (user . fromIntegral)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Statusbar\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/11\/06 20:46:10 $\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-- Report messages of minor importance to the user\n--\nmodule Graphics.UI.Gtk.Display.Statusbar (\n-- * Detail\n-- \n-- | A 'Statusbar' is usually placed along the bottom of an application's main\n-- 'Window'. It may provide a regular commentary of the application's status\n-- (as is usually the case in a web browser, for example), or may be used to\n-- simply output a message when the status changes, (when an upload is complete\n-- in an FTP client, for example). It may also have a resize grip (a triangular\n-- area in the lower right corner) which can be clicked on to resize the window\n-- containing the statusbar.\n--\n-- Status bars in Gtk+ maintain a stack of messages. The message at the top\n-- of the each bar's stack is the one that will currently be displayed.\n--\n-- Any messages added to a statusbar's stack must specify a \/context_id\/\n-- that is used to uniquely identify the source of a message. This context_id\n-- can be generated by 'statusbarGetContextId', given a message and the\n-- statusbar that it will be added to. Note that messages are stored in a\n-- stack, and when choosing which message to display, the stack structure is\n-- adhered to, regardless of the context identifier of a message.\n--\n-- Status bars are created using 'statusbarNew'.\n--\n-- Messages are added to the bar's stack with 'statusbarPush'.\n--\n-- The message at the top of the stack can be removed using 'statusbarPop'.\n-- A message can be removed from anywhere in the stack if its message_id was\n-- recorded at the time it was added. This is done using 'statusbarRemove'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Box'\n-- | +----'HBox'\n-- | +----Statusbar\n-- @\n\n-- * Types\n Statusbar,\n StatusbarClass,\n castToStatusbar,\n toStatusbar,\n ContextId,\n MessageId,\n\n-- * Constructors\n statusbarNew,\n\n-- * Methods\n statusbarGetContextId,\n statusbarPush,\n statusbarPop,\n statusbarRemove,\n statusbarSetHasResizeGrip,\n statusbarGetHasResizeGrip,\n\n-- * Attributes\n statusbarHasResizeGrip,\n\n-- * Signals\n onTextPopped,\n afterTextPopped,\n onTextPushed,\n afterTextPushed,\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\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-- Constructors\n\n-- | Creates a new 'Statusbar' ready for messages.\n--\nstatusbarNew :: IO Statusbar\nstatusbarNew =\n makeNewObject mkStatusbar $\n liftM (castPtr :: Ptr Widget -> Ptr Statusbar) $\n {# call unsafe statusbar_new #}\n\n--------------------\n-- Methods\n\ntype ContextId = {#type guint#}\n\n-- | Returns a new context identifier, given a description of the actual\n-- context. This id can be used to later remove entries form the Statusbar.\n--\nstatusbarGetContextId :: StatusbarClass self => self\n -> String -- ^ @contextDescription@ - textual description of what context the\n -- new message is being used in.\n -> IO ContextId -- ^ returns an id that can be used to later remove entries\n -- ^ from the Statusbar.\nstatusbarGetContextId self contextDescription =\n withUTFString contextDescription $ \\contextDescriptionPtr ->\n {# call unsafe statusbar_get_context_id #}\n (toStatusbar self)\n contextDescriptionPtr\n\ntype MessageId = {#type guint#}\n\n-- | Pushes a new message onto the Statusbar's stack. It will\n-- be displayed as long as it is on top of the stack.\n--\nstatusbarPush :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the message's context id, as returned by\n -- 'statusbarGetContextId'.\n -> String -- ^ @text@ - the message to add to the statusbar.\n -> IO MessageId -- ^ returns the message's new message id for use with\n -- 'statusbarRemove'.\nstatusbarPush self contextId text =\n withUTFString text $ \\textPtr ->\n {# call statusbar_push #}\n (toStatusbar self)\n contextId\n textPtr\n\n-- | Removes the topmost message that has the correct context.\n--\nstatusbarPop :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the context identifier used when the\n -- message was added.\n -> IO ()\nstatusbarPop self contextId =\n {# call statusbar_pop #}\n (toStatusbar self)\n contextId\n\n-- | Forces the removal of a message from a statusbar's stack. The exact\n-- @contextId@ and @messageId@ must be specified.\n--\nstatusbarRemove :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - a context identifier.\n -> MessageId -- ^ @messageId@ - a message identifier, as returned by\n -- 'statusbarPush'.\n -> IO ()\nstatusbarRemove self contextId messageId =\n {# call statusbar_remove #}\n (toStatusbar self)\n contextId\n messageId\n\n-- | Sets whether the statusbar has a resize grip. @True@ by default.\n--\nstatusbarSetHasResizeGrip :: StatusbarClass self => self -> Bool -> IO ()\nstatusbarSetHasResizeGrip self setting =\n {# call statusbar_set_has_resize_grip #}\n (toStatusbar self)\n (fromBool setting)\n\n-- | Returns whether the statusbar has a resize grip.\n--\nstatusbarGetHasResizeGrip :: StatusbarClass self => self -> IO Bool\nstatusbarGetHasResizeGrip self =\n liftM toBool $\n {# call unsafe statusbar_get_has_resize_grip #}\n (toStatusbar self)\n\n--------------------\n-- Attributes\n\n-- | Whether the statusbar has a grip for resizing the toplevel window.\n--\n-- Default value: @True@\n--\nstatusbarHasResizeGrip :: StatusbarClass self => Attr self Bool\nstatusbarHasResizeGrip = newAttr\n statusbarGetHasResizeGrip\n statusbarSetHasResizeGrip\n\n--------------------\n-- Signals\n\n-- | Called if a message is removed.\n--\nonTextPopped, afterTextPopped :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" False self (user . fromIntegral)\nafterTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" True self (user . fromIntegral)\n\n-- | Called if a message is pushed on top of the\n-- stack.\n--\nonTextPushed, afterTextPushed :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" False self (user . fromIntegral)\nafterTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" True self (user . fromIntegral)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e36a8771c7a7785094f6050503c3e743aa25ef3d","subject":"fix build failure on haddock-2.10.0","message":"fix build failure on haddock-2.10.0\n\nChecking module Graphics.UI.Gtk.WebKit.WebFrame...\nCreating interface...\nhaddock: internal error: lexical error\n\/usr\/bin\/haddock returned ExitFailure 1\n\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebFrame.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebFrame.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebFrame\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-- The content of a 'WebView'\n--\n-- Note:\n-- Functon `webkit_web_frame_get_global_context` can't binding now, \n-- Because it need `JSGlobalContextRef` exist in JavaScriptCore.\n--\n-- Function `webkit_web_frame_print_full` can't binding now,\n-- Because library `GtkPrintOperation` haven't binding.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebFrame (\n-- * Description\n-- | A WebKitWebView contains a main WebKitWebFrame. A WebKitWebFrame contains the content of one\n-- URI. The URI and name of the frame can be retrieved, the load status and progress can be observed\n-- using the signals and can be controlled using the methods of the WebKitWebFrame. A WebKitWebFrame\n-- can have any number of children and one child can be found by using 'webFrameFindFrame'.\n\n-- * Types\n WebFrame,\n WebFrameClass,\n LoadStatus,\n\n-- * Constructors\n webFrameNew,\n\n-- * Methods\n webFrameGetWebView,\n webFrameGetName,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webFrameGetNetworkResponse,\n#endif\n webFrameGetTitle,\n webFrameGetUri,\n webFrameGetParent,\n webFrameGetLoadStatus,\n webFrameLoadUri,\n webFrameLoadString,\n webFrameLoadAlternateString,\n webFrameLoadRequest,\n webFrameStopLoading,\n webFrameReload,\n webFrameFindFrame,\n webFrameGetDataSource,\n webFrameGetHorizontalScrollbarPolicy,\n webFrameGetVerticalScrollbarPolicy,\n webFrameGetProvisionalDataSource,\n webFrameGetSecurityOrigin,\n webFramePrint,\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 Graphics.UI.Gtk.Gdk.Events\nimport Graphics.UI.Gtk.General.Enums\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-- * Enums\n\n{#enum LoadStatus {underscoreToCase}#}\n\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebFrame' instance with the given @webview@.\n--\n-- A 'WebFrame' contains the content of one URI.\nwebFrameNew :: \n WebViewClass webview => webview -- ^ @webview@ - the given webview\n -> IO WebFrame\nwebFrameNew webview = \n wrapNewGObject mkWebFrame $ {#call web_frame_new#} (toWebView webview)\n\n-- | Return the 'WebView' that manages the given 'WebFrame'.\nwebFrameGetWebView :: \n WebFrameClass self => self\n -> IO WebView\nwebFrameGetWebView webframe = \n makeNewObject mkWebView $ liftM castPtr $ {#call web_frame_get_web_view#} (toWebFrame webframe)\n\n-- | Return the name of the given 'WebFrame'.\nwebFrameGetName :: \n WebFrameClass self => self\n -> IO (Maybe String) -- ^ the name string or @Nothing@ in case failed.\nwebFrameGetName webframe = \n {#call web_frame_get_name#} (toWebFrame webframe) >>= maybePeek peekCString\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Returns a WebKitNetworkResponse object representing the response that was given to the request for\n-- the given frame, or 'Nothing' if the frame was not created by a load. \n--\n-- * Since 1.1.18\nwebFrameGetNetworkResponse :: WebFrameClass self => self -> IO (Maybe NetworkResponse)\nwebFrameGetNetworkResponse frame =\n maybeNull (makeNewGObject mkNetworkResponse) $ \n {#call webkit_web_frame_get_network_response#} (toWebFrame frame)\n#endif\n\n-- | Return the title of the given 'WebFrame'.\nwebFrameGetTitle :: \n WebFrameClass self => self \n -> IO (Maybe String) -- ^ the title string or @Nothing@ in case failed.\nwebFrameGetTitle webframe = \n {#call web_frame_get_title#} (toWebFrame webframe) >>= maybePeek peekCString\n\n-- | Return the URI of the given 'WebFrame'.\t\nwebFrameGetUri :: \n WebFrameClass self => self \n -> IO (Maybe String) -- ^ the URI string or @Nothing@ in case failed.\nwebFrameGetUri webframe = \n {#call web_frame_get_uri#} (toWebFrame webframe) >>= maybePeek peekCString\n\n-- | Return the 'WebFrame''s parent frame if it has one,\n-- Otherwise return Nothing.\nwebFrameGetParent :: \n WebFrameClass self => self \n -> IO (Maybe WebFrame) -- ^ a 'WebFrame' or @Nothing@ in case failed.\nwebFrameGetParent webframe = \n maybeNull (makeNewGObject mkWebFrame) $ {#call web_frame_get_parent#} (toWebFrame webframe)\n\n-- | Determines the current status of the load.\n--\n-- frame : a WebKitWebView\n-- \n-- * Since 1.1.7\nwebFrameGetLoadStatus ::\n WebFrameClass self => self\n -> IO LoadStatus \nwebFrameGetLoadStatus ls =\n liftM (toEnum . fromIntegral) $ {#call web_frame_get_load_status#} (toWebFrame ls)\n\n-- | Request loading of the specified URI string.\nwebFrameLoadUri :: \n WebFrameClass self => self \n -> String -- ^ @uri@ - an URI string. \n -> IO ()\nwebFrameLoadUri webframe uri = \n withCString uri $ \\uriPtr -> {#call web_frame_load_uri#}\n (toWebFrame webframe)\n uriPtr\n\n-- | Requests loading of the given @content@ \n-- 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.\nwebFrameLoadString :: \n WebFrameClass 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()\nwebFrameLoadString webframe 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_frame_load_string#} \n (toWebFrame webframe) \n contentPtr \n mimetypePtr \n encodingPtr \n baseuriPtr\n\n-- |Request loading of an alternate content for a URL that is unreachable.\n--\n-- Using this method will preserve the back-forward list.\n-- The URI passed in @base_uri@ has to be an absolute URI.\t\t\nwebFrameLoadAlternateString :: \n WebFrameClass self => self \n -> String -- ^ @content@ - the alternate content to display \n -- as the main page of the frame\n -> String -- ^ @base_uri@ - the base URI for relative locations. \n -> String -- ^ @unreachable_url@ - the URL for the alternate page content.\n -> IO()\nwebFrameLoadAlternateString webframe content baseurl unreachableurl = \n withCString content $ \\contentPtr ->\n withCString baseurl $ \\baseurlPtr ->\n withCString unreachableurl $ \\unreachableurlPtr ->\n {#call web_frame_load_alternate_string#}\n (toWebFrame webframe) \n contentPtr\n baseurlPtr\n unreachableurlPtr\n\n-- | Connects to a given URI by initiating an asynchronous client request.\n--\n-- Creates a provisional data source that will transition to a committed data source once any data has been received. \n-- Use 'webFrameStopLoading' to stop the load. \n-- This function is typically invoked on the main frame.\nwebFrameLoadRequest :: \n (WebFrameClass self, NetworkRequestClass requ) => self -> requ\n -> IO ()\nwebFrameLoadRequest webframe request =\n {#call web_frame_load_request#} (toWebFrame webframe) (toNetworkRequest request) \n\n-- | Stops and pending loads on the given data source and those of its children.\nwebFrameStopLoading :: \n WebFrameClass self => self\n -> IO()\nwebFrameStopLoading webframe = \n {#call web_frame_stop_loading#} (toWebFrame webframe)\n\n-- |Reloads the initial request.\nwebFrameReload :: \n WebFrameClass self => self\n -> IO()\nwebFrameReload webframe = \n {#call web_frame_reload#} (toWebFrame webframe)\n\n-- |Return the 'WebFrame' associated with the given name \n-- or @Nothing@ in case none if found\n-- \n-- For pre-defined names, return the given webframe if name is \nwebFrameFindFrame:: \n WebFrameClass self => self \n -> String -- ^ @name@ - the name of the frame to be found.\n -> IO (Maybe WebFrame)\nwebFrameFindFrame webframe name = \n withCString name $ \\namePtr ->\n\tmaybeNull (makeNewGObject mkWebFrame) $ \n {#call web_frame_find_frame#} (toWebFrame webframe) namePtr\n\n-- | Returns the committed data source.\nwebFrameGetDataSource :: \n WebFrameClass self => self\n -> IO WebDataSource\nwebFrameGetDataSource webframe =\n makeNewGObject mkWebDataSource $ {#call web_frame_get_data_source#} (toWebFrame webframe)\n\n-- | Return the policy of horizontal scrollbar.\nwebFrameGetHorizontalScrollbarPolicy :: \n WebFrameClass self => self\n -> IO PolicyType \nwebFrameGetHorizontalScrollbarPolicy webframe = \n liftM (toEnum.fromIntegral) $\n {#call web_frame_get_horizontal_scrollbar_policy#} (toWebFrame webframe)\n \n-- | Return the policy of vertical scrollbar.\nwebFrameGetVerticalScrollbarPolicy :: \n WebFrameClass self => self\n -> IO PolicyType \nwebFrameGetVerticalScrollbarPolicy webframe = \n liftM (toEnum.fromIntegral) $\n {#call web_frame_get_vertical_scrollbar_policy#} (toWebFrame webframe)\n\n-- | You use the 'webFrameLoadRequest' method to initiate a request that creates a provisional data source. \n-- The provisional data source will transition to a committed data source once any data has been received. \n-- Use 'webFrameGetDataSource' to get the committed data source.\nwebFrameGetProvisionalDataSource :: \n WebFrameClass self => self\n -> IO WebDataSource \nwebFrameGetProvisionalDataSource webframe =\n makeNewGObject mkWebDataSource $ {#call web_frame_get_provisional_data_source#} (toWebFrame webframe)\n\n-- | Returns the frame's security origin.\nwebFrameGetSecurityOrigin ::\n WebFrameClass self => self\n -> IO SecurityOrigin \nwebFrameGetSecurityOrigin webframe = \n makeNewGObject mkSecurityOrigin $ {#call web_frame_get_security_origin#} (toWebFrame webframe)\n\n-- |Prints the given 'WebFrame'.\n--\n-- by presenting a print dialog to the user. \nwebFramePrint:: \n WebFrameClass self => self\n -> IO()\nwebFramePrint webframe = \n {#call web_frame_print#} (toWebFrame webframe)\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebFrame\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-- The content of a 'WebView'\n--\n-- Note:\n-- Functon `webkit_web_frame_get_global_context` can't binding now, \n-- Because it need `JSGlobalContextRef` exist in JavaScriptCore.\n--\n-- Function `webkit_web_frame_print_full` can't binding now,\n-- Because library `GtkPrintOperation` haven't binding.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebFrame (\n-- * Description\n-- | A WebKitWebView contains a main WebKitWebFrame. A WebKitWebFrame contains the content of one\n-- URI. The URI and name of the frame can be retrieved, the load status and progress can be observed\n-- using the signals and can be controlled using the methods of the WebKitWebFrame. A WebKitWebFrame\n-- can have any number of children and one child can be found by using 'webFrameFindFrame'.\n\n-- * Types\n WebFrame,\n WebFrameClass,\n LoadStatus,\n\n-- * Constructors\n webFrameNew,\n\n-- * Methods\n webFrameGetWebView,\n webFrameGetName,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webFrameGetNetworkResponse,\n#endif\n webFrameGetTitle,\n webFrameGetUri,\n webFrameGetParent,\n webFrameGetLoadStatus,\n webFrameLoadUri,\n webFrameLoadString,\n webFrameLoadAlternateString,\n webFrameLoadRequest,\n webFrameStopLoading,\n webFrameReload,\n webFrameFindFrame,\n webFrameGetDataSource,\n webFrameGetHorizontalScrollbarPolicy,\n webFrameGetVerticalScrollbarPolicy,\n webFrameGetProvisionalDataSource,\n webFrameGetSecurityOrigin,\n webFramePrint,\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 Graphics.UI.Gtk.Gdk.Events\nimport Graphics.UI.Gtk.General.Enums\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-- * Enums\n\n{#enum LoadStatus {underscoreToCase}#}\n\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebFrame' instance with the given @webview@.\n--\n-- A 'WebFrame' contains the content of one URI.\nwebFrameNew :: \n WebViewClass webview => webview -- ^ @webview@ - the given webview\n -> IO WebFrame\nwebFrameNew webview = \n wrapNewGObject mkWebFrame $ {#call web_frame_new#} (toWebView webview)\n\n-- | Return the 'WebView' that manages the given 'WebFrame'.\nwebFrameGetWebView :: \n WebFrameClass self => self\n -> IO WebView\nwebFrameGetWebView webframe = \n makeNewObject mkWebView $ liftM castPtr $ {#call web_frame_get_web_view#} (toWebFrame webframe)\n\n-- | Return the name of the given 'WebFrame'.\nwebFrameGetName :: \n WebFrameClass self => self\n -> IO (Maybe String) -- ^ the name string or @Nothing@ in case failed.\nwebFrameGetName webframe = \n {#call web_frame_get_name#} (toWebFrame webframe) >>= maybePeek peekCString\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Returns a WebKitNetworkResponse object representing the response that was given to the request for\n-- the given frame, or 'Nothing' if the frame was not created by a load. \n--\n-- * Since 1.1.18\nwebFrameGetNetworkResponse :: WebFrameClass self => self -> IO (Maybe NetworkResponse)\nwebFrameGetNetworkResponse frame =\n maybeNull (makeNewGObject mkNetworkResponse) $ \n {#call webkit_web_frame_get_network_response#} (toWebFrame frame)\n#endif\n\n-- | Return the title of the given 'WebFrame'.\nwebFrameGetTitle :: \n WebFrameClass self => self \n -> IO (Maybe String) -- ^ the title string or @Nothing@ in case failed.\nwebFrameGetTitle webframe = \n {#call web_frame_get_title#} (toWebFrame webframe) >>= maybePeek peekCString\n\n-- | Return the URI of the given 'WebFrame'.\t\nwebFrameGetUri :: \n WebFrameClass self => self \n -> IO (Maybe String) -- ^ the URI string or @Nothing@ in case failed.\nwebFrameGetUri webframe = \n {#call web_frame_get_uri#} (toWebFrame webframe) >>= maybePeek peekCString\n\n-- | Return the 'WebFrame''s parent frame if it has one,\n-- Otherwise return Nothing.\nwebFrameGetParent :: \n WebFrameClass self => self \n -> IO (Maybe WebFrame) -- ^ a 'WebFrame' or @Nothing@ in case failed.\nwebFrameGetParent webframe = \n maybeNull (makeNewGObject mkWebFrame) $ {#call web_frame_get_parent#} (toWebFrame webframe)\n\n-- | Determines the current status of the load.\n--\n-- frame\u00a0: a WebKitWebView \n-- \n-- * Since 1.1.7\nwebFrameGetLoadStatus ::\n WebFrameClass self => self\n -> IO LoadStatus \nwebFrameGetLoadStatus ls =\n liftM (toEnum . fromIntegral) $ {#call web_frame_get_load_status#} (toWebFrame ls)\n\n-- | Request loading of the specified URI string.\nwebFrameLoadUri :: \n WebFrameClass self => self \n -> String -- ^ @uri@ - an URI string. \n -> IO ()\nwebFrameLoadUri webframe uri = \n withCString uri $ \\uriPtr -> {#call web_frame_load_uri#}\n (toWebFrame webframe)\n uriPtr\n\n-- | Requests loading of the given @content@ \n-- 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.\nwebFrameLoadString :: \n WebFrameClass 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()\nwebFrameLoadString webframe 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_frame_load_string#} \n (toWebFrame webframe) \n contentPtr \n mimetypePtr \n encodingPtr \n baseuriPtr\n\n-- |Request loading of an alternate content for a URL that is unreachable.\n--\n-- Using this method will preserve the back-forward list.\n-- The URI passed in @base_uri@ has to be an absolute URI.\t\t\nwebFrameLoadAlternateString :: \n WebFrameClass self => self \n -> String -- ^ @content@ - the alternate content to display \n -- as the main page of the frame\n -> String -- ^ @base_uri@ - the base URI for relative locations. \n -> String -- ^ @unreachable_url@ - the URL for the alternate page content.\n -> IO()\nwebFrameLoadAlternateString webframe content baseurl unreachableurl = \n withCString content $ \\contentPtr ->\n withCString baseurl $ \\baseurlPtr ->\n withCString unreachableurl $ \\unreachableurlPtr ->\n {#call web_frame_load_alternate_string#}\n (toWebFrame webframe) \n contentPtr\n baseurlPtr\n unreachableurlPtr\n\n-- | Connects to a given URI by initiating an asynchronous client request.\n--\n-- Creates a provisional data source that will transition to a committed data source once any data has been received. \n-- Use 'webFrameStopLoading' to stop the load. \n-- This function is typically invoked on the main frame.\nwebFrameLoadRequest :: \n (WebFrameClass self, NetworkRequestClass requ) => self -> requ\n -> IO ()\nwebFrameLoadRequest webframe request =\n {#call web_frame_load_request#} (toWebFrame webframe) (toNetworkRequest request) \n\n-- | Stops and pending loads on the given data source and those of its children.\nwebFrameStopLoading :: \n WebFrameClass self => self\n -> IO()\nwebFrameStopLoading webframe = \n {#call web_frame_stop_loading#} (toWebFrame webframe)\n\n-- |Reloads the initial request.\nwebFrameReload :: \n WebFrameClass self => self\n -> IO()\nwebFrameReload webframe = \n {#call web_frame_reload#} (toWebFrame webframe)\n\n-- |Return the 'WebFrame' associated with the given name \n-- or @Nothing@ in case none if found\n-- \n-- For pre-defined names, return the given webframe if name is \nwebFrameFindFrame:: \n WebFrameClass self => self \n -> String -- ^ @name@ - the name of the frame to be found.\n -> IO (Maybe WebFrame)\nwebFrameFindFrame webframe name = \n withCString name $ \\namePtr ->\n\tmaybeNull (makeNewGObject mkWebFrame) $ \n {#call web_frame_find_frame#} (toWebFrame webframe) namePtr\n\n-- | Returns the committed data source.\nwebFrameGetDataSource :: \n WebFrameClass self => self\n -> IO WebDataSource\nwebFrameGetDataSource webframe =\n makeNewGObject mkWebDataSource $ {#call web_frame_get_data_source#} (toWebFrame webframe)\n\n-- | Return the policy of horizontal scrollbar.\nwebFrameGetHorizontalScrollbarPolicy :: \n WebFrameClass self => self\n -> IO PolicyType \nwebFrameGetHorizontalScrollbarPolicy webframe = \n liftM (toEnum.fromIntegral) $\n {#call web_frame_get_horizontal_scrollbar_policy#} (toWebFrame webframe)\n \n-- | Return the policy of vertical scrollbar.\nwebFrameGetVerticalScrollbarPolicy :: \n WebFrameClass self => self\n -> IO PolicyType \nwebFrameGetVerticalScrollbarPolicy webframe = \n liftM (toEnum.fromIntegral) $\n {#call web_frame_get_vertical_scrollbar_policy#} (toWebFrame webframe)\n\n-- | You use the 'webFrameLoadRequest' method to initiate a request that creates a provisional data source. \n-- The provisional data source will transition to a committed data source once any data has been received. \n-- Use 'webFrameGetDataSource' to get the committed data source.\nwebFrameGetProvisionalDataSource :: \n WebFrameClass self => self\n -> IO WebDataSource \nwebFrameGetProvisionalDataSource webframe =\n makeNewGObject mkWebDataSource $ {#call web_frame_get_provisional_data_source#} (toWebFrame webframe)\n\n-- | Returns the frame's security origin.\nwebFrameGetSecurityOrigin ::\n WebFrameClass self => self\n -> IO SecurityOrigin \nwebFrameGetSecurityOrigin webframe = \n makeNewGObject mkSecurityOrigin $ {#call web_frame_get_security_origin#} (toWebFrame webframe)\n\n-- |Prints the given 'WebFrame'.\n--\n-- by presenting a print dialog to the user. \nwebFramePrint:: \n WebFrameClass self => self\n -> IO()\nwebFramePrint webframe = \n {#call web_frame_print#} (toWebFrame webframe)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"cfe042a0bdf4a4bf55f7ef31dff816b7ec2a6afb","subject":"Some additional color handling.","message":"Some additional color handling.","repos":"TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV,aleator\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns#-}\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.ForeignPtr\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\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\n\n\n{#pointer *IplImage as Image foreign newtype#}\n\nforeign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr Image\n\ninstance NFData Image where\n rnf a@(Image 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 releaseImage iptr\n return.Image $ fptr\n\nunImage (Image fptr) = fptr\ncomposeMultichannelImage :: Maybe Image -> Maybe Image -> Maybe Image -> Maybe Image -> Image \ncomposeMultichannelImage c1 c2 c3 c4 = unsafePerformIO $\u00a0do\n res <- createImage32F (size) 4 -- TODO: Check channel count\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\nloadImage 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\nloadColorImage 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 1)\n bw <- imageTo32F i\n return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\nconvertToGrayScale img = unsafePerformIO $\u00a0creatingImage $ do\n res <- {#call wrapCreateImage32F#} w h 1\n withImage img $ \\cimg -> \n {#call cvCvtColor#} (castPtr cimg) (castPtr res) cvRGBtoGRAY\n return res\n where \n (w,h) = getSize img\n\nconvertTo code channels img = unsafePerformIO $\u00a0creatingImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withImage img $ \\cimg -> \n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where \n (w,h) = getSize img\n\ncreateImage32F (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage32F#} w h nChannels\n\ncreateImage64F (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage64F#} w h nChannels\n\ncreateImage8U (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage8U#} w h nChannels\n\nimage32F size channels = unsafePerformIO $ createImage32F size channels\nimage8U size channels = unsafePerformIO $ createImage8U size channels\n\nemptyCopy img = image32F (getSize img) 1\n\nsaveImage filename image = do\n fpi <- imageTo8Bit image\n withCString filename $ \\name -> \n withGenImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\ngetSize image = unsafePerformIO $ withImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Integral a) => (a, a) -> (a,a) -> Image -> Image\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image \n | x+w <= width && y+h <= height = getRegion' (x,y) (w,h) image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (width,height) = getSize image\n \ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withImage image $ \\i ->\n creatingImage ({#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. \n--blit image1 image2 (x,y) =\n-- withImage image1 $ \\i1 ->\n-- withImage image2 $ \\i2 ->\n-- ({#call plainBlit#} i1 i2 x y)\n-- TODO: Remove the above\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 y x)\n where \n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\nsubPixelBlit\n :: Image -> Image -> (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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nimageTo32F img = withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\nimageTo8Bit img = withGenImage img $ \\image -> \n creatingImage \n ({#call ensure8U #} image)\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\n\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n\n let (w,h) = getSize image\n setCOI no image\n cres <- {#call wrapCreateImage32F#} w 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\nsetPixel :: (CInt,CInt) -> CDouble -> Image -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img y x v\n\ngetPixel :: (CInt,CInt) -> Image -> CDouble\ngetPixel (x,y) image = unsafePerformIO $ withGenImage image $ \\img ->\n {#call wrapGet32F2D#} img y x\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 :: (Int,Int) -> Int -> [Image] -> Image\nmontage (u',v') space' imgs = 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 <- createImage32F (rw,rh) 1\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) | y <- [0..v-1] , x <- [0..u-1] | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns#-}\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.ForeignPtr\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\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\n\n\n{#pointer *IplImage as Image foreign newtype#}\n\nforeign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr Image\n\ninstance NFData Image where\n rnf a@(Image 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 releaseImage iptr\n return.Image $ fptr\n\nunImage (Image fptr) = fptr\ncomposeMultichannelImage :: Maybe Image -> Maybe Image -> Maybe Image -> Maybe Image -> Image \ncomposeMultichannelImage c1 c2 c3 c4 = unsafePerformIO $\u00a0do\n res <- createImage32F (size) 4 -- TODO: Check channel count\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\nloadImage 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\nloadColorImage 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 1)\n bw <- imageTo32F i\n return $ Just bw\n\ncvRGBtoGRAY = 7 -- NOTE: This will break.\nconvertToGrayScale img = unsafePerformIO $\u00a0creatingImage $ do\n res <- {#call wrapCreateImage32F#} w h 1\n withImage img $ \\cimg -> \n {#call cvCvtColor#} (castPtr cimg) (castPtr res) cvRGBtoGRAY\n return res\n\n where \n (w,h) = getSize img\n\ncreateImage32F (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage32F#} w h nChannels\n\ncreateImage64F (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage64F#} w h nChannels\n\ncreateImage8U (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage8U#} w h nChannels\n\nimage32F size channels = unsafePerformIO $ createImage32F size channels\nimage8U size channels = unsafePerformIO $ createImage8U size channels\n\nemptyCopy img = image32F (getSize img) 1\n\nsaveImage filename image = do\n fpi <- imageTo8Bit image\n withCString filename $ \\name -> \n withGenImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\ngetSize image = unsafePerformIO $ withImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Integral a) => (a, a) -> (a,a) -> Image -> Image\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image \n | x+w <= width && y+h <= height = getRegion' (x,y) (w,h) image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (width,height) = getSize image\n \ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withImage image $ \\i ->\n creatingImage ({#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. \n--blit image1 image2 (x,y) =\n-- withImage image1 $ \\i1 ->\n-- withImage image2 $ \\i2 ->\n-- ({#call plainBlit#} i1 i2 x y)\n-- TODO: Remove the above\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 y x)\n where \n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\nsubPixelBlit\n :: Image -> Image -> (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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nimageTo32F img = withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\nimageTo8Bit img = withGenImage img $ \\image -> \n creatingImage \n ({#call ensure8U #} image)\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\n\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\nsetPixel :: (CInt,CInt) -> CDouble -> Image -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img y x v\n\ngetPixel :: (CInt,CInt) -> Image -> CDouble\ngetPixel (x,y) image = unsafePerformIO $ withGenImage image $ \\img ->\n {#call wrapGet32F2D#} img y x\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 :: (Int,Int) -> Int -> [Image] -> Image\nmontage (u',v') space' imgs = 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 <- createImage32F (rw,rh) 1\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) | y <- [0..v-1] , x <- [0..u-1] | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e6408c86b185f506a4961e799e03ab055583dacf","subject":"Only 8 more error messages before version 0.3 CV.Image!","message":"Only 8 more error messages before version 0.3 CV.Image!\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, TypeFamilies #-}\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.ForeignPtr\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\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGBA\ndata LAB\n\n-- Bit Depths\ndata D8\ndata D32\ndata D64\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\nforeign 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 releaseImage 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 releaseImage iptr\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\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\nloadImage :: FilePath -> IO (Maybe (Image GrayScale Double))\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 Double))\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 SizeT a :: *\n getSize :: a -> SizeT a\n\ninstance Sized BareImage where\n type SizeT 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 SizeT (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n--loadColorImage 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 1)\n-- bw <- imageTo32F i\n-- return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB Double -> Image LAB Double\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB Double -> Image GrayScale Double\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale Double) where\n type P (Image GrayScale Double) = Double \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB Double) where\n type P (Image RGB Double) = (Double,Double,Double) \n getPixel (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\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\n\nemptyCopy img = create (getSize img) \n\nsaveImage :: FilePath -> Image c d -> IO ()\nsaveImage filename image = do\n fpi <- imageTo8Bit image\n withCString filename $ \\name -> \n withGenImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n--getSize image = unsafePerformIO $ withImage image $ \\i -> do\n-- w <- {#call getImageWidth#} i\n-- h <- {#call getImageHeight#} i\n-- return (fromIntegral w,fromIntegral h)\n\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Integral a) => (a,a) -> (a,a) -> 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 (width,height) = getSize image\n \ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withImage image $ \\i ->\n creatingImage ({#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 y 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 :: (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 (unS -> image1) (unS -> 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 img fun = do \n result <- cloneImage img\n fun result\n return result\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\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI no image\n cres <- {#call wrapCreateImage32F#} w 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 :: (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs = 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) 1\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) | y <- [0..v-1] , x <- [0..u-1] | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, TypeFamilies #-}\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.ForeignPtr\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\n\n\ndata GrayScale\ndata RGB\ndata RGBA\ndata LAB\n\nnewtype NewImage channels depth = S Image\n\nunS (S i ) = i -- Unsafe and ugly\n\nwithNewImage (S i) op = withImage i op >>= return . S\nwithGenNewImage (S i) op = withGenImage i op >>= return . S\n\n{#pointer *IplImage as Image foreign newtype#}\n\nforeign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr Image\n\ninstance NFData Image where\n rnf a@(Image 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 releaseImage iptr\n return.Image $ fptr\n\nunImage (Image fptr) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nlab = undefined :: Tag LAB\n\n\ncomposeMultichannelImageNew :: Maybe (NewImage GrayScale a) -> Maybe (NewImage GrayScale a) -> Maybe (NewImage GrayScale a) -> Maybe (NewImage GrayScale a) -> Tag tp -> NewImage tp a\ncomposeMultichannelImageNew c1 c2 c3 c4 totag = S $ composeMultichannelImage (fmap unS c1) (fmap unS c2) (fmap unS c3) (fmap unS c4)\n\ncomposeMultichannelImage :: Maybe Image -> Maybe Image -> Maybe Image -> Maybe Image -> Image \ncomposeMultichannelImage c1 c2 c3 c4 = unsafePerformIO $\u00a0do\n res <- createImage32F (size) 4 -- 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\nloadImage 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\nloadImageNew :: FilePath -> IO (Maybe (NewImage GrayScale Double))\nloadImageNew 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 .\u00a0S $ bw\n\nloadColorImageNew :: FilePath -> IO (Maybe (NewImage RGB Double))\nloadColorImageNew 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 1)\n bw <- imageTo32F i\n return . Just . S $ bw\n\ngetSizeNew :: (Integral a, Integral b) => NewImage c d -> (a,b)\ngetSizeNew image = unsafePerformIO $ withImage (unS image) $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\nloadColorImage 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 1)\n bw <- imageTo32F i\n return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\nconvertToGrayScale img = unsafePerformIO $\u00a0creatingImage $ do\n res <- {#call wrapCreateImage32F#} w h 1\n withImage img $ \\cimg -> \n {#call cvCvtColor#} (castPtr cimg) (castPtr res) cvRGBtoGRAY\n return res\n where \n (w,h) = getSize img\n\nrgbToLab :: NewImage RGB Double -> NewImage LAB Double\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS \n\nrgbToGray :: NewImage RGB Double -> NewImage GrayScale Double\nrgbToGray = S . convertToGrayScale . unS\n\ngetRegionNew :: (Integral a) => (a,a) -> (a,a) -> NewImage c d -> NewImage c d\ngetRegionNew a b\n = S . getRegion a b . unS\n\nclass GetPixel a where\n type P a :: *\n getPixelNew :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (NewImage GrayScale Double) where\n type P (NewImage GrayScale Double) = Double \n getPixelNew (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $ withGenImage (unS image) $ \\img ->\n {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (NewImage RGB Double) where\n type P (NewImage RGB Double) = (Double,Double,Double) \n getPixelNew (fromIntegral -> x, fromIntegral -> y) image \n = unsafePerformIO $ do \n withGenImage (unS 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\nconvertTo code channels img = unsafePerformIO $\u00a0creatingImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withImage img $ \\cimg -> \n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where \n (w,h) = getSize img\n\ncreateImage32F (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage32F#} w h nChannels\n\ncreateImage64F (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage64F#} w h nChannels\n\ncreateImage8U (w,h) nChannels = do\n creatingImage $ {#call wrapCreateImage8U#} w h nChannels\n\nimage32F size channels = unsafePerformIO $ createImage32F size channels\nimage8U size channels = unsafePerformIO $ createImage8U size channels\n\nemptyCopy img = image32F (getSize img) 1\n\nsaveImage filename image = do\n fpi <- imageTo8Bit image\n withCString filename $ \\name -> \n withGenImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\ngetSize image = unsafePerformIO $ withImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Integral a) => (a, a) -> (a,a) -> Image -> Image\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image \n | x+w <= width && y+h <= height = getRegion' (x,y) (w,h) image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (width,height) = getSize image\n \ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withImage image $ \\i ->\n creatingImage ({#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 y 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-- | blit multiple tiles into one image\nblitM :: (Int,Int) -> [((Int,Int),Image)] -> Image\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- createImage32F (fromIntegral rw,fromIntegral rh) 1\n sequence_ [blit r i (fromIntegral x, fromIntegral y) \n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image -> Image -> (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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nimageTo32F img = withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\nimageTo8Bit img = withGenImage img $ \\image -> \n creatingImage \n ({#call ensure8U #} image)\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\n\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI no image\n cres <- {#call wrapCreateImage32F#} w 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\nsetPixel :: (CInt,CInt) -> CDouble -> Image -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img y x v\n\ngetPixel :: (CInt,CInt) -> Image -> CDouble\ngetPixel (x,y) image = unsafePerformIO $ withGenImage image $ \\img ->\n {#call wrapGet32F2D#} img y x\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 :: (Int,Int) -> Int -> [Image] -> Image\nmontage (u',v') space' imgs = 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 <- createImage32F (rw,rh) 1\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) \n | x <- [0..u-1], y <- [0..v-1] \n | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"a6546a7331a43ea0690708b9207aaf225dc6736c","subject":"Add function sourceCompletionProviderUpdateInfo","message":"Add function sourceCompletionProviderUpdateInfo\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderGetActivation,\n sourceCompletionProviderMatch,\n sourceCompletionProviderUpdateInfo,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.SourceView.Enums\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Get with what kind of activation the provider should be activated.\nsourceCompletionProviderGetActivation :: SourceCompletionProviderClass scp => scp\n -> IO SourceCompletionActivation\nsourceCompletionProviderGetActivation scp =\n liftM (toEnum . fromIntegral) $\n {#call gtk_source_completion_provider_get_activation #}\n (toSourceCompletionProvider scp)\n\n-- | Get whether the provider match the context of completion detailed in context.\nsourceCompletionProviderMatch :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO Bool -- ^ returns 'True' if provider matches the completion context, 'False' otherwise\nsourceCompletionProviderMatch scp context =\n liftM toBool $\n {#call gtk_source_completion_provider_match #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Update extra information shown in info for proposal. This should be implemented if your provider\n-- sets a custom info widget for proposal. This function MUST be implemented when\n-- 'sourceCompletionProviderGetInfoWidget' is implemented.\nsourceCompletionProviderUpdateInfo :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> SourceCompletionInfo\n -> IO ()\nsourceCompletionProviderUpdateInfo scp proposal info =\n {#call gtk_source_completion_provider_update_info #}\n (toSourceCompletionProvider scp)\n proposal\n info\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderGetActivation,\n sourceCompletionProviderMatch,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.SourceView.Enums\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Get with what kind of activation the provider should be activated.\nsourceCompletionProviderGetActivation :: SourceCompletionProviderClass scp => scp\n -> IO SourceCompletionActivation\nsourceCompletionProviderGetActivation scp =\n liftM (toEnum . fromIntegral) $\n {#call gtk_source_completion_provider_get_activation #}\n (toSourceCompletionProvider scp)\n\n-- | Get whether the provider match the context of completion detailed in context.\nsourceCompletionProviderMatch :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO Bool -- ^ returns 'True' if provider matches the completion context, 'False' otherwise\nsourceCompletionProviderMatch scp context =\n liftM toBool $\n {#call gtk_source_completion_provider_match #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d10d986a8e8865e1bb4ca70d42f929d9c7e171a2","subject":"Misspelling.","message":"Misspelling.\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,\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","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 hand 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,\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":"c225e4f408f18d4fd32cb6dbeb205476fa11ec3f","subject":"Start node IDs at 1 instead of 0.","message":"Start node IDs at 1 instead of 0.\n\nNow we can always negate an ID to get something useful.\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":"-- | 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 sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\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 1\n tref <- newIORef 1\n mref <- newIORef 1\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 | 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 sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ed2f53b88adbd99a64f282bccf96bcf5d100a7c9","subject":"Call clSetKernelArg with the integer-type defined in the header-file instead of always using CULong","message":"Call clSetKernelArg with the integer-type defined in the header-file instead of always using CULong","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) (fromIntegral $ 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 :: 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d47b4379cdefc268d72874067aba0e087d538609","subject":"Fix boolean typid","message":"Fix boolean typid\n","repos":"reinerp\/CoreFoundation","old_file":"CoreFoundation\/Boolean.chs","new_file":"CoreFoundation\/Boolean.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1e199cc637f4deae3017638fd82580c19a71e34e","subject":"Correct matrix inversion.","message":"Correct matrix inversion.\n\nCalculating the determinant was incorrect. Pointed out by\nMaur\u00edcio .\n\n\n","repos":"gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"87706d1274ffea5b994716fe606ff33453b62c23","subject":"fix bug in pre-4.0 path","message":"fix bug in pre-4.0 path\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) [2009..2011] 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 -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArrayAsync,\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 \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(..))\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.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--------------------------------------------------------------------------------\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--\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-- 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--\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{# 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--\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{# 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--\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' peekDeviceHandle*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\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 { useDeviceHandle `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 , 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--\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 (Stream nullPtr) mst)\n\n{# fun unsafe 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 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 { 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--\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 (Stream nullPtr) mst)\n\n{# fun unsafe 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-- 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 { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\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--\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{# 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--\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 (Stream nullPtr) st\n\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--\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--\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--\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 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--\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 { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\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--\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 (Stream nullPtr) mst\n\n{# fun unsafe cuMemsetD8Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\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--\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\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--\ngetBasePtr :: DevicePtr a -> IO (DevicePtr a, Int64)\ngetBasePtr dptr = do\n (status,base,size) <- cuMemGetAddressRange dptr\n resultIfOk (status, (base,size))\n\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--\ngetMemInfo :: IO (Int64, Int64)\ngetMemInfo = do\n (status,f,t) <- cuMemGetInfo\n resultIfOk (status,(f,t))\n\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--\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--\nuseDeviceHandle :: DevicePtr a -> DeviceHandle\nuseDeviceHandle = fromIntegral . ptrToIntPtr . useDevicePtr\n\n","old_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) [2009..2011] 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 -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArrayAsync,\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 \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(..))\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.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--------------------------------------------------------------------------------\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--\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-- 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--\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{# 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--\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{# 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--\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' peekDeviceHandle*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\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 { useDeviceHandle `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 , 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--\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 (Stream nullPtr) mst)\n\n{# fun unsafe 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 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 { 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--\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 (Stream nullPtr) mst)\n\n{# fun unsafe 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-- 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 { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\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--\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{# 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--\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 (Stream nullPtr) st\n\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--\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--\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--\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 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--\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 { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\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--\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 (Stream nullPtr) mst\n\n{# fun unsafe cuMemsetD8Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\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--\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\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--\ngetBasePtr :: DevicePtr a -> IO (DevicePtr a, Int64)\ngetBasePtr dptr = do\n (status,base,size) <- cuMemGetAddressRange dptr\n resultIfOk (status, (base,size))\n\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--\ngetMemInfo :: IO (Int64, Int64)\ngetMemInfo = do\n (status,f,t) <- cuMemGetInfo\n resultIfOk (status,(f,t))\n\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--\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--\nuseDeviceHandle :: DevicePtr a -> DeviceHandle\nuseDeviceHandle = fromIntegral . ptrToIntPtr . useDevicePtr\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d513c8c981fd197c761a394fa7052e71f3389d00","subject":"gstreamer: document & implement missing API for M.S.G.Core.ElementFactory","message":"gstreamer: document & implement missing API for M.S.G.Core.ElementFactory\n\ndarcs-hash:20080218011206-21862-cf9e6d090c3ef06f93b92fb45777fdf7eafe14e8.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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\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","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.ElementFactory (\n \n ElementFactory,\n ElementFactoryClass,\n castToElementFactory,\n toElementFactory,\n \n elementFactoryFind,\n elementFactoryGetElementType,\n elementFactoryGetLongname,\n elementFactoryGetKlass,\n elementFactoryGetDescription,\n elementFactoryGetAuthor,\n elementFactoryGetNumPadTemplates,\n elementFactoryGetURIType,\n elementFactoryGetURIProtocols,\n elementFactoryCreate,\n elementFactoryMake\n \n ) where\n\nimport Control.Monad ( liftM )\nimport System.Glib.FFI\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString\n , peekUTFStringArray0 )\nimport System.Glib.GType ( GType )\n{# import Media.Streaming.GStreamer.Core.Types #}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementFactoryFind :: String\n -> IO ElementFactory\nelementFactoryFind name =\n withUTFString name {# call element_factory_find #} >>= takeObject\n\nelementFactoryGetElementType :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO (Maybe GType)\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\nelementFactoryGetLongname :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetLongname factory =\n {# call element_factory_get_longname #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetKlass :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetKlass factory =\n {# call element_factory_get_klass #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetDescription :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetDescription factory =\n {# call element_factory_get_description #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetAuthor :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO String\nelementFactoryGetAuthor factory =\n {# call element_factory_get_author #} (toElementFactory factory) >>=\n peekUTFString\n\nelementFactoryGetNumPadTemplates :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO Word\nelementFactoryGetNumPadTemplates factory =\n liftM fromIntegral $\n {# call element_factory_get_num_pad_templates #} $ toElementFactory factory\n\nelementFactoryGetURIType :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO Word\nelementFactoryGetURIType factory =\n liftM fromIntegral $\n {# call element_factory_get_uri_type #} $ toElementFactory factory\n\nelementFactoryGetURIProtocols :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> IO (Maybe [String])\nelementFactoryGetURIProtocols factory =\n {# call element_factory_get_uri_protocols #} (toElementFactory factory) >>=\n maybePeek peekUTFStringArray0\n\nelementFactoryCreate :: (ElementFactoryClass elementFactory) =>\n elementFactory\n -> String\n -> IO (Maybe Element)\nelementFactoryCreate factory name =\n withUTFString name $ \\cName ->\n {# call element_factory_create #} (toElementFactory factory) cName >>=\n maybePeek takeObject\n\nelementFactoryMake :: String\n -> String\n -> IO (Maybe Element)\nelementFactoryMake factoryName name =\n withUTFString factoryName $ \\cFactoryName ->\n withUTFString name $ \\cName ->\n {# call element_factory_make #} cFactoryName cName >>=\n maybePeek takeObject\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f27adbe2a4eb8a1a332d8b84448c9c605c44502b","subject":"Pick the right function to load a Pixbuf on Windows.","message":"Pick the right function to load a Pixbuf on Windows.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/PixbufAnimation.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/PixbufAnimation.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf Animation\n--\n-- Author : Matthew Arsenault\n--\n-- Created: 14 November 2009\n--\n-- Copyright (C) 2009 Matthew Arsenault\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.Gdk.PixbufAnimation (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'PixbufAnimation'\n-- | +----'PixbufSimpleAnim'\n-- @\n\n-- * Types\n PixbufAnimation,\n PixbufAnimationClass,\n castToPixbufAnimation, gTypePixbufAnimation,\n toPixbufAnimation,\n\n PixbufAnimationIter,\n PixbufAnimationIterClass,\n castToPixbufAnimationIter, gTypePixbufAnimationIter,\n toPixbufAnimationIter,\n\n PixbufSimpleAnim,\n PixbufSimpleAnimClass,\n castToPixbufSimpleAnim, gTypePixbufSimpleAnim,\n toPixbufSimpleAnim,\n\n-- * Constructors\n pixbufAnimationNewFromFile,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimNew,\n#endif\n\n-- * Methods\n pixbufAnimationGetWidth,\n pixbufAnimationGetHeight,\n pixbufAnimationGetIter,\n pixbufAnimationIsStaticImage,\n pixbufAnimationGetStaticImage,\n pixbufAnimationIterAdvance,\n pixbufAnimationIterGetDelayTime,\n pixbufAnimationIterOnCurrentlyLoadingFrame,\n pixbufAnimationIterGetPixbuf,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimAddFrame,\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n pixbufSimpleAnimSetLoop,\n pixbufSimpleAnimGetLoop\n#endif\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\n{# import Graphics.UI.Gtk.Gdk.Pixbuf #}\n\n{# context prefix=\"gdk\" #}\n\n\n--CHECKME: Domain error doc, GFileError ???\n-- | Creates a new animation by loading it from a file. The file\n-- format is detected automatically. If the file's format does not\n-- support multi-frame images, then an animation with a single frame\n-- will be created. Possible errors are in the 'PixbufError' and\n-- 'GFileError' domains.\n--\n-- Any of several error conditions may occur: the file could not be\n-- opened, there was no loader for the file's format, there was not\n-- enough memory to allocate the image buffer, or the image file\n-- contained invalid data.\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' or 'GFileError'\n--\npixbufAnimationNewFromFile :: FilePath -- ^ Name of file to load, in the GLib file name encoding\n -> IO PixbufAnimation -- ^ A newly-created animation\npixbufAnimationNewFromFile fname =\n constructNewGObject mkPixbufAnimation $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,5)\n {#call unsafe pixbuf_animation_new_from_file_utf8#} strPtr errPtrPtr\n#else\n {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr\n#endif\n\n-- | Queries the width of the bounding box of a pixbuf animation.\npixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Width of the bounding box of the animation.\npixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self\n\n-- | Queries the height of the bounding box of a pixbuf animation.\npixbufAnimationGetHeight :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Height of the bounding box of the animation.\npixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self\n\n\n-- | Get an iterator for displaying an animation. The iterator\n-- provides the frames that should be displayed at a given time. The\n-- start time would normally come from 'gGetCurrentTime', and marks\n-- the beginning of animation playback. After creating an iterator,\n-- you should immediately display the pixbuf returned by\n-- 'pixbufAnimationIterGetPixbuf'. Then, you should install a\n-- timeout (with 'timeoutAdd') or by some other mechanism ensure\n-- that you'll update the image after\n-- 'pixbufAnimationIterGetDelayTime' milliseconds. Each time the\n-- image is updated, you should reinstall the timeout with the new,\n-- possibly-changed delay time.\n--\n-- As a shortcut, if start_time is @Nothing@, the result of\n-- 'gGetCurrentTime' will be used automatically.\n--\n-- To update the image (i.e. possibly change the result of\n-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),\n-- call 'pixbufAnimationIterAdvance'.\n--\n-- If you're using 'PixbufLoader', in addition to updating the image\n-- after the delay time, you should also update it whenever you\n-- receive the area_updated signal and\n-- 'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In\n-- this case, the frame currently being fed into the loader has\n-- received new data, so needs to be refreshed. The delay time for a\n-- frame may also be modified after an area_updated signal, for\n-- example if the delay time for a frame is encoded in the data after\n-- the frame itself. So your timeout should be reinstalled after any\n-- area_updated signal.\n--\n-- A delay time of -1 is possible, indicating \"infinite.\"\n--\npixbufAnimationGetIter :: PixbufAnimation -- ^ a 'PixbufAnimation'\n -> Maybe GTimeVal -- ^ time when the animation starts playing\n -> IO PixbufAnimationIter -- ^ an iterator to move over the animation\npixbufAnimationGetIter self tv = maybeWith with tv $ \\stPtr ->\n constructNewGObject mkPixbufAnimationIter $\n {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)\n\n\n\n-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns\n-- out to be a plain, unanimated image, then this function will\n-- return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve\n-- the image.\n--\npixbufAnimationIsStaticImage :: PixbufAnimation\n -> IO Bool -- ^ TRUE if the \"animation\" was really just an image\npixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self\n\n\n-- | If an animation is really just a plain image (has only one\n-- frame), this function returns that image. If the animation is an\n-- animation, this function returns a reasonable thing to display as\n-- a static unanimated image, which might be the first frame, or\n-- something more sophisticated. If an animation hasn't loaded any\n-- frames yet, this function will return @Nothing@.\n--\npixbufAnimationGetStaticImage :: PixbufAnimation\n -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation\npixbufAnimationGetStaticImage self =\n maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self\n\n\n\n-- | Possibly advances an animation to a new frame. Chooses the frame\n-- based on the start time passed to 'pixbufAnimationGetIter'.\n--\n-- current_time would normally come from 'gGetCurrentTime', and must\n-- be greater than or equal to the time passed to\n-- 'pixbufAnimationGetIter', and must increase or remain unchanged\n-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you\n-- can't go backward in time; animations only play forward.\n--\n-- As a shortcut, pass @Nothing@ for the current time and\n-- 'gGetCurrentTime' will be invoked on your behalf. So you only need\n-- to explicitly pass current_time if you're doing something odd like\n-- playing the animation at double speed.\n--\n-- If this function returns @False@, there's no need to update the\n-- animation display, assuming the display had been rendered prior to\n-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and\n-- update the display with the new pixbuf.\n--\npixbufAnimationIterAdvance :: PixbufAnimationIter -- ^ A 'PixbufAnimationIter'\n -> Maybe GTimeVal -- ^ current time\n -> IO Bool -- ^ @True@ if the image may need updating\npixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \\tvPtr ->\n {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)\n\n\n-- | Gets the number of milliseconds the current pixbuf should be\n-- displayed, or -1 if the current pixbuf should be displayed\n-- forever. 'timeoutAdd' conveniently takes a timeout in\n-- milliseconds, so you can use a timeout to schedule the next\n-- update.\n--\npixbufAnimationIterGetDelayTime :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Int -- ^ delay time in milliseconds (thousandths of a second)\npixbufAnimationIterGetDelayTime self = liftM fromIntegral $\n {#call unsafe pixbuf_animation_iter_get_delay_time#} self\n\n\n-- | Used to determine how to respond to the area_updated signal on\n-- 'PixbufLoader' when loading an animation. area_updated is emitted\n-- for an area of the frame currently streaming in to the loader. So\n-- if you're on the currently loading frame, you need to redraw the\n-- screen for the updated area.\n--\npixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter\n -> IO Bool -- ^ @True@ if the frame we're on is partially loaded, or the last frame\npixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $\n {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter\n\n--CHECKME: referencing, usage of constructNewGObject\n-- | Gets the current pixbuf which should be displayed; the pixbuf will\n-- be the same size as the animation itself\n-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This\n-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'\n-- milliseconds. The caller of this function does not own a reference\n-- to the returned pixbuf; the returned pixbuf will become invalid\n-- when the iterator advances to the next frame, which may happen\n-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to\n-- keep it (don't just add a reference), as it may get recycled as you\n-- advance the iterator.\n--\npixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Pixbuf -- ^ the pixbuf to be displayed\npixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $\n {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter\n\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Creates a new, empty animation.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimNew :: Int -- ^ the width of the animation\n -> Int -- ^ the height of the animation\n -> Float -- ^ the speed of the animation, in frames per second\n -> IO PixbufSimpleAnim -- ^ a newly allocated 'PixbufSimpleAnim'\npixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $\n {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)\n\n\n-- | Adds a new frame to animation. The pixbuf must have the\n-- dimensions specified when the animation was constructed.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimAddFrame :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Pixbuf -- ^ the pixbuf to add\n -> IO ()\npixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb\n\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n\n-- | Sets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimSetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Bool -- ^ whether to loop the animation\n -> IO ()\npixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)\n\n\n-- | Gets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimGetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> IO Bool -- ^ @True@ if the animation loops forever, @False@ otherwise\npixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf Animation\n--\n-- Author : Matthew Arsenault\n--\n-- Created: 14 November 2009\n--\n-- Copyright (C) 2009 Matthew Arsenault\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.Gdk.PixbufAnimation (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'PixbufAnimation'\n-- | +----'PixbufSimpleAnim'\n-- @\n\n-- * Types\n PixbufAnimation,\n PixbufAnimationClass,\n castToPixbufAnimation, gTypePixbufAnimation,\n toPixbufAnimation,\n\n PixbufAnimationIter,\n PixbufAnimationIterClass,\n castToPixbufAnimationIter, gTypePixbufAnimationIter,\n toPixbufAnimationIter,\n\n PixbufSimpleAnim,\n PixbufSimpleAnimClass,\n castToPixbufSimpleAnim, gTypePixbufSimpleAnim,\n toPixbufSimpleAnim,\n\n-- * Constructors\n pixbufAnimationNewFromFile,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimNew,\n#endif\n\n-- * Methods\n pixbufAnimationGetWidth,\n pixbufAnimationGetHeight,\n pixbufAnimationGetIter,\n pixbufAnimationIsStaticImage,\n pixbufAnimationGetStaticImage,\n pixbufAnimationIterAdvance,\n pixbufAnimationIterGetDelayTime,\n pixbufAnimationIterOnCurrentlyLoadingFrame,\n pixbufAnimationIterGetPixbuf,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimAddFrame,\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n pixbufSimpleAnimSetLoop,\n pixbufSimpleAnimGetLoop\n#endif\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\n{# import Graphics.UI.Gtk.Gdk.Pixbuf #}\n\n{# context prefix=\"gdk\" #}\n\n\n--CHECKME: Domain error doc, GFileError ???\n-- | Creates a new animation by loading it from a file. The file\n-- format is detected automatically. If the file's format does not\n-- support multi-frame images, then an animation with a single frame\n-- will be created. Possible errors are in the 'PixbufError' and\n-- 'GFileError' domains.\n--\n-- Any of several error conditions may occur: the file could not be\n-- opened, there was no loader for the file's format, there was not\n-- enough memory to allocate the image buffer, or the image file\n-- contained invalid data.\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' or 'GFileError'\n--\npixbufAnimationNewFromFile :: FilePath -- ^ Name of file to load, in the GLib file name encoding\n -> IO PixbufAnimation -- ^ A newly-created animation\npixbufAnimationNewFromFile fname =\n constructNewGObject mkPixbufAnimation $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr\n\n\n-- | Queries the width of the bounding box of a pixbuf animation.\npixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Width of the bounding box of the animation.\npixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self\n\n-- | Queries the height of the bounding box of a pixbuf animation.\npixbufAnimationGetHeight :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Height of the bounding box of the animation.\npixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self\n\n\n-- | Get an iterator for displaying an animation. The iterator\n-- provides the frames that should be displayed at a given time. The\n-- start time would normally come from 'gGetCurrentTime', and marks\n-- the beginning of animation playback. After creating an iterator,\n-- you should immediately display the pixbuf returned by\n-- 'pixbufAnimationIterGetPixbuf'. Then, you should install a\n-- timeout (with 'timeoutAdd') or by some other mechanism ensure\n-- that you'll update the image after\n-- 'pixbufAnimationIterGetDelayTime' milliseconds. Each time the\n-- image is updated, you should reinstall the timeout with the new,\n-- possibly-changed delay time.\n--\n-- As a shortcut, if start_time is @Nothing@, the result of\n-- 'gGetCurrentTime' will be used automatically.\n--\n-- To update the image (i.e. possibly change the result of\n-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),\n-- call 'pixbufAnimationIterAdvance'.\n--\n-- If you're using 'PixbufLoader', in addition to updating the image\n-- after the delay time, you should also update it whenever you\n-- receive the area_updated signal and\n-- 'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In\n-- this case, the frame currently being fed into the loader has\n-- received new data, so needs to be refreshed. The delay time for a\n-- frame may also be modified after an area_updated signal, for\n-- example if the delay time for a frame is encoded in the data after\n-- the frame itself. So your timeout should be reinstalled after any\n-- area_updated signal.\n--\n-- A delay time of -1 is possible, indicating \"infinite.\"\n--\npixbufAnimationGetIter :: PixbufAnimation -- ^ a 'PixbufAnimation'\n -> Maybe GTimeVal -- ^ time when the animation starts playing\n -> IO PixbufAnimationIter -- ^ an iterator to move over the animation\npixbufAnimationGetIter self tv = maybeWith with tv $ \\stPtr ->\n constructNewGObject mkPixbufAnimationIter $\n {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)\n\n\n\n-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns\n-- out to be a plain, unanimated image, then this function will\n-- return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve\n-- the image.\n--\npixbufAnimationIsStaticImage :: PixbufAnimation\n -> IO Bool -- ^ TRUE if the \"animation\" was really just an image\npixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self\n\n\n-- | If an animation is really just a plain image (has only one\n-- frame), this function returns that image. If the animation is an\n-- animation, this function returns a reasonable thing to display as\n-- a static unanimated image, which might be the first frame, or\n-- something more sophisticated. If an animation hasn't loaded any\n-- frames yet, this function will return @Nothing@.\n--\npixbufAnimationGetStaticImage :: PixbufAnimation\n -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation\npixbufAnimationGetStaticImage self =\n maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self\n\n\n\n-- | Possibly advances an animation to a new frame. Chooses the frame\n-- based on the start time passed to 'pixbufAnimationGetIter'.\n--\n-- current_time would normally come from 'gGetCurrentTime', and must\n-- be greater than or equal to the time passed to\n-- 'pixbufAnimationGetIter', and must increase or remain unchanged\n-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you\n-- can't go backward in time; animations only play forward.\n--\n-- As a shortcut, pass @Nothing@ for the current time and\n-- 'gGetCurrentTime' will be invoked on your behalf. So you only need\n-- to explicitly pass current_time if you're doing something odd like\n-- playing the animation at double speed.\n--\n-- If this function returns @False@, there's no need to update the\n-- animation display, assuming the display had been rendered prior to\n-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and\n-- update the display with the new pixbuf.\n--\npixbufAnimationIterAdvance :: PixbufAnimationIter -- ^ A 'PixbufAnimationIter'\n -> Maybe GTimeVal -- ^ current time\n -> IO Bool -- ^ @True@ if the image may need updating\npixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \\tvPtr ->\n {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)\n\n\n-- | Gets the number of milliseconds the current pixbuf should be\n-- displayed, or -1 if the current pixbuf should be displayed\n-- forever. 'timeoutAdd' conveniently takes a timeout in\n-- milliseconds, so you can use a timeout to schedule the next\n-- update.\n--\npixbufAnimationIterGetDelayTime :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Int -- ^ delay time in milliseconds (thousandths of a second)\npixbufAnimationIterGetDelayTime self = liftM fromIntegral $\n {#call unsafe pixbuf_animation_iter_get_delay_time#} self\n\n\n-- | Used to determine how to respond to the area_updated signal on\n-- 'PixbufLoader' when loading an animation. area_updated is emitted\n-- for an area of the frame currently streaming in to the loader. So\n-- if you're on the currently loading frame, you need to redraw the\n-- screen for the updated area.\n--\npixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter\n -> IO Bool -- ^ @True@ if the frame we're on is partially loaded, or the last frame\npixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $\n {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter\n\n--CHECKME: referencing, usage of constructNewGObject\n-- | Gets the current pixbuf which should be displayed; the pixbuf will\n-- be the same size as the animation itself\n-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This\n-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'\n-- milliseconds. The caller of this function does not own a reference\n-- to the returned pixbuf; the returned pixbuf will become invalid\n-- when the iterator advances to the next frame, which may happen\n-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to\n-- keep it (don't just add a reference), as it may get recycled as you\n-- advance the iterator.\n--\npixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Pixbuf -- ^ the pixbuf to be displayed\npixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $\n {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter\n\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Creates a new, empty animation.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimNew :: Int -- ^ the width of the animation\n -> Int -- ^ the height of the animation\n -> Float -- ^ the speed of the animation, in frames per second\n -> IO PixbufSimpleAnim -- ^ a newly allocated 'PixbufSimpleAnim'\npixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $\n {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)\n\n\n-- | Adds a new frame to animation. The pixbuf must have the\n-- dimensions specified when the animation was constructed.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimAddFrame :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Pixbuf -- ^ the pixbuf to add\n -> IO ()\npixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb\n\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n\n-- | Sets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimSetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Bool -- ^ whether to loop the animation\n -> IO ()\npixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)\n\n\n-- | Gets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimGetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> IO Bool -- ^ @True@ if the animation loops forever, @False@ otherwise\npixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"23ad4f71d0a8aafc5897dd913d03a33c3480c3f8","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\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte","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":"6be0b9a1b51764b8af679de81cd8bf3118b480da","subject":"Minor cleanups.","message":"Minor cleanups.\n","repos":"mfischer\/haskell-smartcard","old_file":"Lowlevel\/WinSCard.chs","new_file":"Lowlevel\/WinSCard.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n-- | The WinSCard module wraps the WinSCard API.\n-- It should be regarded as a low-level wrapper, though, as it still feels rather C-ish.\n-- Still missing are the getAttribute and setAttribute functions.\nmodule Lowlevel.WinSCard ( establishContext\n , releaseContext\n , validateContext\n , listReaders\n , listReaderGroups\n , transmit\n , connect\n , disconnect\n , reconnect\n , status\n , beginTransaction\n , endTransaction\n , APDU )\nwhere\n\nimport Foreign\nimport Foreign.C\nimport Foreign.C.String\nimport Lowlevel.PCSCLite\nimport Data.List\nimport Data.List.Utils\nimport Data.Bits\nimport Control.Monad\n\n#include \n\n-- | Creates a communication context to the PC\\\/SC Resource Manager. This must be the first function called in a PC\\\/SC application.\nestablishContext :: SCardScope -> IO (Either SCardStatus SCardContext)\nestablishContext s = alloca $ \\ctx_ptr ->\n do rt <- liftM fromCLong $ {#call SCardEstablishContext as ^#} (fromIntegral(fromEnum s)) nullPtr nullPtr ctx_ptr\n ctx <- peek ctx_ptr\n if rt == Ok then return $Right ctx\n else return $Left rt\n\n-- | Destroys a communication context to the PC\\\/SC Resource Manager. This must be the last function called in a PC\\\/SC application.\nreleaseContext :: SCardContext -> IO (SCardStatus)\nreleaseContext c = liftM fromCLong $ {#call SCardReleaseContext as ^#} c\n\n-- | Determines whether a 'SCardContext' is still valid.\n-- After a 'SCardContext' has been set by 'SCardEstablishContext', it may become not valid if the resource manager service has been shut down.\nvalidateContext :: SCardContext -> IO (Bool)\nvalidateContext c = do rt <- liftM fromCLong $ {#call SCardIsValidContext as ^#} c\n return $ rt == Ok\n\nlistReaders_ = {#call SCardListReaders as ^#}\n\ngetReaderSize_ :: SCardContext -> IO (Int)\ngetReaderSize_ c = alloca $ \\s -> do listReaders_ c nullPtr nullPtr s\n s' <- peek s \n return $fromIntegral s'\n\n-- | Given a 'SCardContext', lists the connected readers, or gives an error.\nlistReaders :: SCardContext -> IO (Either SCardStatus [String])\nlistReaders c = do n <- getReaderSize_ c\n allocaArray n $ \\rs ->\n do alloca $ \\size -> do poke size $fromIntegral n\n rt <- liftM fromCLong $ listReaders_ c nullPtr rs size\n n' <- peek size\n rs' <- peekArray (fromIntegral n') rs\n if (rt == Ok) then return $ Right $ filter (not . null) $ f rs'\n else return $ Left $ rt\n where f = Data.List.Utils.split \"\\0\" . map castCCharToChar\ntype SCardHandle = {#type SCARDHANDLE#}\n\n-- | Smartcard \/Application Protocol Data Unit\/\ntype APDU = [Word8]\n\n-- | Combines the given 'SCardProtocol's into one OR'd 'CULong'\ncombine :: [SCardProtocol] -> CULong\ncombine = fromIntegral . foldr ((.|.) . fromEnum) 0\n\n-- | Given a context, establishes a connection to the reader specified as a 'String'.\n-- A 'SCardShare' describing the type of connection can be given as well as a list of possible 'SCardProtocol's.\n-- The first connection will power up and perform a reset on the card.\nconnect :: SCardContext -> String -> SCardShare -> [SCardProtocol] -> IO (Either SCardStatus (SCardProtocol, SCardHandle))\nconnect c r s ps = let connect_ = {#call SCardConnect as ^#}\n in alloca $ \\p ->\n alloca $ \\h ->\n withCString r $ \\r' ->\n do rt <- liftM fromCLong $ connect_ c r' (fromIntegral $ fromEnum s) (combine ps) h p\n p' <- liftM toSCardProtocol $ peek p\n h' <- peek h\n if (rt == Ok) then return $Right (p', h')\n else return $Left rt\n\n\n-- | Reestablishes a connection to a reader that was previously connected to using 'connect'.\n-- In a multi application environment it is possible for an application to reset the card in 'Shared' mode.\n-- When this occurs any other application trying to access certain commands will be returned the value 'CardReset'.\n-- When this occurs 'reconnect' must be called in order to acknowledge that the card was reset and allow it to change it's state accordingly.\nreconnect:: SCardHandle -> SCardShare -> [SCardProtocol] -> SCardAction-> IO (Either SCardStatus SCardProtocol)\nreconnect h s ps a = let reconnect_ = {#call SCardReconnect as ^#}\n in alloca $ \\p ->\n do rt <- liftM fromCLong $ reconnect_ h (fromIntegral $ fromEnum s) (combine ps) (fromIntegral $ fromEnum a) p\n p' <- liftM toSCardProtocol $ peek p\n if (rt == Ok) then return $Right p'\n else return $Left rt\n\n-- | Terminates a connection, using the specified 'SCardAction'.\ndisconnect :: SCardHandle -> SCardAction -> IO (SCardStatus)\ndisconnect h a = let disconnect_ = {#call SCardDisconnect as ^ #}\n in liftM fromCLong $ disconnect_ h (fromIntegral $ fromEnum a)\n\n-- | Establishes a temporary exclusive access mode for doing a series of commands or transaction.\n-- You might want to use this when you are selecting a few files and then writing a large file so you can make sure\n-- that another application will not change the current file.\n-- If another application has a lock on this reader or this application is in 'Exclusive' there will be no action taken.\nbeginTransaction :: SCardHandle -> IO (SCardStatus)\nbeginTransaction h = liftM fromCLong $ {#call SCardBeginTransaction as ^#} h\n\n-- | Ends a previously begun transaction.\n-- The calling application must be the owner of the previously begun transaction or an error will occur.\n-- 'a' can have the following values:\n-- 'LeaveCard', 'ResetCard', 'UnpowerCard', 'EjectCard'\n-- The disposition action is not currently used in this release. \nendTransaction :: SCardHandle -> SCardAction -> IO (SCardStatus)\nendTransaction h a = let end_ = {#call SCardDisconnect as ^ #}\n in liftM fromCLong $ end_ h (fromIntegral $ fromEnum a)\n\n-- | Cancels all pending blocking requests on the 'getStatusChange' function.\ncancel :: SCardHandle -> IO (SCardStatus)\ncancel h = liftM fromCLong $ {#call SCardCancel as ^ #} h\n\n-- | Sends a command directly to the IFD Handler to be processed by the reader.\ncontrol :: SCardHandle -> Int -> [Word8] -> Int -> IO (Either SCardStatus [Word8])\ncontrol h op cmd lr = let f = fromIntegral . length\n l = length\n cp = castPtr\n fi = fromIntegral\n in allocaArray (l cmd) $ \\sb ->\n allocaArray lr $ \\rb ->\n alloca $ \\lr' ->\n do rt <- liftM fromCLong $ {#call SCardControl as ^ #} h (fi op) (cp (sb :: Ptr Word8)) (f cmd) (cp (rb :: Ptr Word8)) (fi lr) lr'\n lr'' <- peek lr'\n res <- peekArray (fromIntegral lr'') (castPtr rb)\n if (rt == Ok) then return $Right (res :: [Word8])\n else return $Left rt\n\n\n-- | Sends an APDU given as list of 'Word8' to the smartcard \/ RFID tag connected to by 'connect'.\n-- The maximum expected length for the given request is given as lr and the protocol to be used as p.\ntransmit :: SCardHandle -> APDU -> Int -> SCardProtocol -> IO (Either SCardStatus [Word8])\ntransmit h d lr p = allocaArray (length d) $ \\sb ->\n allocaArray lr $ \\rb ->\n alloca $ \\lo ->\n alloca $ \\pci -> let f p' = case p' of\n T0 -> mkSCardIORequestT0\n T1 -> mkSCardIORequestT1\n Raw -> mkSCardIORequestRaw\n h' = fromCLong h\n pci' = castPtr pci\n fl = fromIntegral . length\n in do poke pci $ f p\n poke lo $fromIntegral lr\n pokeArray sb d\n rt <- transmit_ h' pci' (castPtr (sb :: Ptr Word8)) (fl d) pci' (rb :: Ptr Word8) lo\n len <- peek lo\n res <- peekArray (fromIntegral len) rb\n if (rt == Ok) then return $Right res\n else return $Left rt\ntransmit_ = {#fun SCardTransmit as ^{ `Int'\n , castPtr `Ptr SCardIORequest'\n , castPtr `Ptr Word8'\n , fromIntegral `Int'\n , castPtr `Ptr SCardIORequest'\n , castPtr `Ptr Word8'\n , castPtr `Ptr CULong'\n } -> `SCardStatus' fromCLong#}\n\n-- | Given a handle and the lengths for the send and receive buffers this function returns the current status of the reader connected to.\n-- It's friendly name will be returned as a 'String'.\n-- The current state is returned as a List of 'SCardCardState', and the Protocol as 'SCardProtocol'.\nstatus :: SCardHandle -> Int -> Int -> IO (Either SCardStatus (String, [SCardCardState], SCardProtocol, [Word8]))\nstatus h lr al = allocaArray lr $ \\rs ->\n alloca $ \\s ->\n alloca $ \\st ->\n alloca $ \\p ->\n alloca $ \\atr ->\n alloca $ \\atrl -> do poke s $ fromIntegral lr\n poke atrl $ fromIntegral al\n rt <- liftM fromCLong $ {#call SCardStatus as ^ #} (fromCLong h) rs s st p atr atrl\n rs' <- peekCAString rs\n st' <- peek st\n p' <- peek p\n atrl' <- peek atrl\n atr' <- peekArray (fromIntegral atrl') atr\n if (rt == Ok) then return $ Right (rs', (fromSCardStates . fromIntegral) st', toSCardProtocol p', map fromIntegral atr')\n else return $ Left rt\n\n-- | Returns a list of currently available reader groups.\nlistReaderGroups :: SCardContext -> Int -> IO (Either SCardStatus [String])\nlistReaderGroups c lr = allocaArray lr $ \\rb ->\n alloca $ \\s -> do poke s $ fromIntegral lr\n rt <- liftM fromCLong $ {#call SCardListReaderGroups as ^ #} c rb s\n s' <- peek s\n rb' <- peekArray (fromIntegral s') rb\n if (rt == Ok) then return $ Right $ filter (not . null) $ f rb'\n else return $ Left $ rt\n where f = Data.List.Utils.split \"\\0\" . map castCCharToChar\n\nfromSCardStates :: Int -> [SCardCardState]\nfromSCardStates x = let v = [Unknown, Absent, Present, Powered, Negotiable, Specific]\n f k = (x .&. fromEnum k) \/= 0\n in filter f v\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n-- | The WinSCard module wraps the WinSCard API.\n-- It should be regarded as a low-level wrapper, though, as it still feels rather C-ish.\nmodule Lowlevel.WinSCard ( establishContext\n , releaseContext\n , validateContext\n , listReaders\n , listReaderGroups\n , transmit\n , connect\n , disconnect\n , reconnect\n , status\n , beginTransaction\n , endTransaction\n , APDU )\nwhere\n\nimport Foreign\nimport Foreign.C\nimport Foreign.C.String\nimport Lowlevel.PCSCLite\nimport Data.List\nimport Data.List.Utils\nimport Data.Bits\nimport Control.Monad\n\n#include \n\n-- | Creates a communication context to the PC\\\/SC Resource Manager. This must be the first function called in a PC\\\/SC application.\nestablishContext :: SCardScope -> IO (Either SCardStatus SCardContext)\nestablishContext s = alloca $ \\ctx_ptr ->\n do rt <- liftM fromCLong $ {#call SCardEstablishContext as ^#} (fromIntegral(fromEnum s)) nullPtr nullPtr ctx_ptr\n ctx <- peek ctx_ptr\n if rt == Ok then return $Right ctx\n else return $Left rt\n\n-- | Destroys a communication context to the PC\\\/SC Resource Manager. This must be the last function called in a PC\\\/SC application.\nreleaseContext :: SCardContext -> IO (SCardStatus)\nreleaseContext c = liftM fromCLong $ {#call SCardReleaseContext as ^#} c\n\n-- | Determines whether a 'SCardContext' is still valid.\n-- After a 'SCardContext' has been set by 'SCardEstablishContext', it may become not valid if the resource manager service has been shut down.\nvalidateContext :: SCardContext -> IO (Bool)\nvalidateContext c = do rt <- liftM fromCLong $ {#call SCardIsValidContext as ^#} c\n return $ rt == Ok\n\nlistReaders_ = {#call SCardListReaders as ^#}\n\ngetReaderSize_ :: SCardContext -> IO (Int)\ngetReaderSize_ c = alloca $ \\s -> do listReaders_ c nullPtr nullPtr s\n s' <- peek s \n return $fromIntegral s'\n\n-- | Given a 'SCardContext', lists the connected readers, or gives an error.\nlistReaders :: SCardContext -> IO (Either SCardStatus [String])\nlistReaders c = do n <- getReaderSize_ c\n allocaArray n $ \\rs ->\n do alloca $ \\size -> do poke size $fromIntegral n\n rt <- liftM fromCLong $ listReaders_ c nullPtr rs size\n n' <- peek size\n rs' <- peekArray (fromIntegral n') rs\n if (rt == Ok) then return $ Right $ filter (not . null) $ f rs'\n else return $ Left $ rt\n where f = Data.List.Utils.split \"\\0\" . map castCCharToChar\ntype SCardHandle = {#type SCARDHANDLE#}\n\n-- | Smartcard \/Application Protocol Data Unit\/\ntype APDU = [Word8]\n\ncombine :: [SCardProtocol] -> CULong\ncombine = fromIntegral . foldr ((.|.) . fromEnum) 0\n\n-- | Given a context, establishes a connection to the reader specified as a 'String'.\n-- A 'SCardShare' describing the type of connection can be given as well as a list of possible 'SCardProtocol's.\n-- The first connection will power up and perform a reset on the card.\nconnect :: SCardContext -> String -> SCardShare -> [SCardProtocol] -> IO (Either SCardStatus (SCardProtocol, SCardHandle))\nconnect c r s ps = let connect_ = {#call SCardConnect as ^#}\n in alloca $ \\p ->\n alloca $ \\h ->\n withCString r $ \\r' ->\n do rt <- liftM fromCLong $ connect_ c r' (fromIntegral $ fromEnum s) (combine ps) h p\n p' <- liftM toSCardProtocol $ peek p\n h' <- peek h\n if (rt == Ok) then return $Right (p', h')\n else return $Left rt\n\n\n-- | Reestablishes a connection to a reader that was previously connected to using 'connect'.\n-- In a multi application environment it is possible for an application to reset the card in 'Shared' mode.\n-- When this occurs any other application trying to access certain commands will be returned the value 'CardReset'.\n-- When this occurs 'reconnect' must be called in order to acknowledge that the card was reset and allow it to change it's state accordingly.\nreconnect:: SCardHandle -> SCardShare -> [SCardProtocol] -> SCardAction-> IO (Either SCardStatus SCardProtocol)\nreconnect h s ps a = let reconnect_ = {#call SCardReconnect as ^#}\n in alloca $ \\p ->\n do rt <- liftM fromCLong $ reconnect_ h (fromIntegral $ fromEnum s) (combine ps) (fromIntegral $ fromEnum a) p\n p' <- liftM toSCardProtocol $ peek p\n if (rt == Ok) then return $Right p'\n else return $Left rt\n\n-- | Terminates a connection, using the specified 'SCardAction'.\ndisconnect :: SCardHandle -> SCardAction -> IO (SCardStatus)\ndisconnect h a = let disconnect_ = {#call SCardDisconnect as ^ #}\n in liftM fromCLong $ disconnect_ h (fromIntegral $ fromEnum a)\n\n-- | Establishes a temporary exclusive access mode for doing a series of commands or transaction.\n-- You might want to use this when you are selecting a few files and then writing a large file so you can make sure\n-- that another application will not change the current file.\n-- If another application has a lock on this reader or this application is in 'Exclusive' there will be no action taken.\nbeginTransaction :: SCardHandle -> IO (SCardStatus)\nbeginTransaction h = liftM fromCLong $ {#call SCardBeginTransaction as ^#} h\n\n-- | Ends a previously begun transaction.\n-- The calling application must be the owner of the previously begun transaction or an error will occur.\n-- 'a' can have the following values:\n-- 'LeaveCard', 'ResetCard', 'UnpowerCard', 'EjectCard'\n-- The disposition action is not currently used in this release. \nendTransaction :: SCardHandle -> SCardAction -> IO (SCardStatus)\nendTransaction h a = let end_ = {#call SCardDisconnect as ^ #}\n in liftM fromCLong $ end_ h (fromIntegral $ fromEnum a)\n\n-- | Cancels all pending blocking requests on the 'getStatusChange' function.\ncancel :: SCardHandle -> IO (SCardStatus)\ncancel h = liftM fromCLong $ {#call SCardCancel as ^ #} h\n\n-- | Sends a command directly to the IFD Handler to be processed by the reader.\ncontrol :: SCardHandle -> Int -> [Word8] -> Int -> IO (Either SCardStatus [Word8])\ncontrol h op cmd lr = let f = fromIntegral . length\n l = length\n cp = castPtr\n fi = fromIntegral\n in allocaArray (l cmd) $ \\sb ->\n allocaArray lr $ \\rb ->\n alloca $ \\lr' ->\n do rt <- liftM fromCLong $ {#call SCardControl as ^ #} h (fi op) (cp (sb :: Ptr Word8)) (f cmd) (cp (rb :: Ptr Word8)) (fi lr) lr'\n lr'' <- peek lr'\n res <- peekArray (fromIntegral lr'') (castPtr rb)\n if (rt == Ok) then return $Right (res :: [Word8])\n else return $Left rt\n\n\n-- | Sends an APDU given as list of 'Word8' to the smartcard \/ RFID tag connected to by 'connect'.\n-- The maximum expected length for the given request is given as lr and the protocol to be used as p.\ntransmit :: SCardHandle -> APDU -> Int -> SCardProtocol -> IO (Either SCardStatus [Word8])\ntransmit h d lr p = allocaArray (length d) $ \\sb ->\n allocaArray lr $ \\rb ->\n alloca $ \\lo ->\n alloca $ \\pci -> let f p' = case p' of\n T0 -> mkSCardIORequestT0\n T1 -> mkSCardIORequestT1\n Raw -> mkSCardIORequestRaw\n h' = fromCLong h\n pci' = castPtr pci\n fl = fromIntegral . length\n in do poke pci $ f p\n poke lo $fromIntegral lr\n pokeArray sb d\n rt <- transmit_ h' pci' (castPtr (sb :: Ptr Word8)) (fl d) pci' (rb :: Ptr Word8) lo\n len <- peek lo\n res <- peekArray (fromIntegral len) rb\n if (rt == Ok) then return $Right res\n else return $Left rt\ntransmit_ = {#fun SCardTransmit as ^{ `Int'\n , castPtr `Ptr SCardIORequest'\n , castPtr `Ptr Word8'\n , fromIntegral `Int'\n , castPtr `Ptr SCardIORequest'\n , castPtr `Ptr Word8'\n , castPtr `Ptr CULong'\n } -> `SCardStatus' fromCLong#}\n\n-- | Given a handle and the lengths for the send and receive buffers this function returns the current status of the reader connected to.\n-- It's friendly name will be returned as a 'String'.\n-- The current state is returned as a List of 'SCardCardState', and the Protocol as 'SCardProtocol'.\nstatus :: SCardHandle -> Int -> Int -> IO (Either SCardStatus (String, [SCardCardState], SCardProtocol, [Word8]))\nstatus h lr al = allocaArray lr $ \\rs ->\n alloca $ \\s ->\n alloca $ \\st ->\n alloca $ \\p ->\n alloca $ \\atr ->\n alloca $ \\atrl -> do poke s $ fromIntegral lr\n poke atrl $ fromIntegral al\n rt <- liftM fromCLong $ {#call SCardStatus as ^ #} (fromCLong h) rs s st p atr atrl\n rs' <- peekCAString rs\n st' <- peek st\n p' <- peek p\n atrl' <- peek atrl\n atr' <- peekArray (fromIntegral atrl') atr\n if (rt == Ok) then return $ Right (rs', (fromSCardStates . fromIntegral) st', toSCardProtocol p', map fromIntegral atr')\n else return $ Left rt\n\n-- | Returns a list of currently available reader groups.\nlistReaderGroups :: SCardContext -> Int -> IO (Either SCardStatus [String])\nlistReaderGroups c lr = allocaArray lr $ \\rb ->\n alloca $ \\s -> do poke s $ fromIntegral lr\n rt <- liftM fromCLong $ {#call SCardListReaderGroups as ^ #} c rb s\n s' <- peek s\n rb' <- peekArray (fromIntegral s') rb\n if (rt == Ok) then return $ Right $ filter (not . null) $ f rb'\n else return $ Left $ rt\n where f = Data.List.Utils.split \"\\0\" . map castCCharToChar\n\nfromSCardStates :: Int -> [SCardCardState]\nfromSCardStates x = let v = [Unknown, Absent, Present, Powered, Negotiable, Specific]\n f k = (x .&. fromEnum k) \/= 0\n in filter f v\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"b6916d340136dad3a1b1eba1136ffb86031ba729","subject":"compute capability as floating point major.minor","message":"compute capability as floating point major.minor\n\nIgnore-this: 84831b1ccc3b58b3f360e156c677c43d\n\ndarcs-hash:20090720041734-115f9-c9e4ce4a1c15171ea16b2782b20e630eda5bf646.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Types.chs","new_file":"Foreign\/CUDA\/Types.chs","new_contents":"{-\n - CUDA data types\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Types\n (\n Status(..),\n CopyDirection(..),\n ComputeMode(..),\n DeviceFlags(..),\n DeviceProperties(..),\n Stream,\n\n DevicePtr, newDevicePtr, withDevicePtr\n ) where\n\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Enumerations\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n--\n-- Compute mode\n--\n{# enum ComputeMode {}\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n--\n-- Device execution flags\n--\n{# enum DeviceFlags {}\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Device Properties\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n--\n-- Store all device properties\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String,\n computeCapability :: Float,\n totalGlobalMem :: Integer,\n totalConstMem :: Integer,\n sharedMemPerBlock :: Integer,\n regsPerBlock :: Int,\n warpSize :: Int,\n maxThreadsPerBlock :: Int,\n maxThreadsDim :: (Int,Int,Int),\n maxGridSize :: (Int,Int,Int),\n clockRate :: Int,\n multiProcessorCount :: Int,\n memPitch :: Integer,\n textureAlignment :: Integer,\n computeMode :: ComputeMode,\n deviceOverlap :: Bool,\n kernelExecTimeoutEnabled :: Bool,\n integrated :: Bool,\n canMapHostMemory :: Bool\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Memory Management\n--------------------------------------------------------------------------------\n\nnewtype DevicePtr = DevicePtr (ForeignPtr ())\n\nwithDevicePtr :: DevicePtr -> (Ptr () -> IO b) -> IO b\nwithDevicePtr (DevicePtr fptr) = withForeignPtr fptr\n\nnewDevicePtr :: FinalizerPtr () -> Ptr () -> IO DevicePtr\nnewDevicePtr fp p = newForeignPtr fp p >>= \\dp -> return (DevicePtr dp)\n\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\ntype Stream = {# type cudaStream_t #}\n\n","old_contents":"{-\n - CUDA data types\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Types\n (\n Status(..),\n CopyDirection(..),\n ComputeMode(..),\n DeviceFlags(..),\n DeviceProperties(..),\n Stream,\n\n DevicePtr, newDevicePtr, withDevicePtr\n ) where\n\n\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Enumerations\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n--\n-- Compute mode\n--\n{# enum ComputeMode {}\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n--\n-- Device execution flags\n--\n{# enum DeviceFlags {}\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Device Properties\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n--\n-- Store all device properties\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String,\n computeCapability :: (Int,Int),\n totalGlobalMem :: Integer,\n totalConstMem :: Integer,\n sharedMemPerBlock :: Integer,\n regsPerBlock :: Int,\n warpSize :: Int,\n maxThreadsPerBlock :: Int,\n maxThreadsDim :: (Int,Int,Int),\n maxGridSize :: (Int,Int,Int),\n clockRate :: Int,\n multiProcessorCount :: Int,\n memPitch :: Integer,\n textureAlignment :: Integer,\n computeMode :: ComputeMode,\n deviceOverlap :: Bool,\n kernelExecTimeoutEnabled :: Bool,\n integrated :: Bool,\n canMapHostMemory :: Bool\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- cIntConv `fmap` {#get cudaDeviceProp.major#} p\n v2 <- cIntConv `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = (v1,v2),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Memory Management\n--------------------------------------------------------------------------------\n\nnewtype DevicePtr = DevicePtr (ForeignPtr ())\n\nwithDevicePtr :: DevicePtr -> (Ptr () -> IO b) -> IO b\nwithDevicePtr (DevicePtr fptr) = withForeignPtr fptr\n\nnewDevicePtr :: FinalizerPtr () -> Ptr () -> IO DevicePtr\nnewDevicePtr fp p = newForeignPtr fp p >>= \\dp -> return (DevicePtr dp)\n\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\ntype Stream = {# type cudaStream_t #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"18539b9eefa8fbcd32a9a2c239c9972ded7edde2","subject":"gstreamer: fix types for event handlers in Element.chs","message":"gstreamer: fix types for event handlers in Element.chs","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" 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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"29eda0c570b1fa1b19b22c7834bc13a8b2314fe5","subject":"Initial stubs for blob","message":"Initial stubs for blob\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\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","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\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"39500a9b1242d5c74dd456f1eb91cd324f1eeb7c","subject":"gstreamer: M.S.G.Core.Caps: document everything; code cleanups, remove capsMerge and capsAppend; add capsCopyNth","message":"gstreamer: M.S.G.Core.Caps: document everything; code cleanups, remove capsMerge and capsAppend; add capsCopyNth\n\ndarcs-hash:20080116040349-21862-98636cf9213c7319fc94891691cbbad7424f2bed.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-- | 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","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.Caps (\n \n Caps,\n capsNone,\n capsAny,\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 CapsM,\n capsCreate,\n capsModify,\n capsAppend,\n capsMerge,\n capsAppendStructure,\n capsMergeStructure,\n capsRemoveStructure,\n capsTruncate\n \n ) where\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import Media.Streaming.GStreamer.Core.Types#}\n\ncapsNone :: Caps\ncapsNone =\n unsafePerformIO $ {# call caps_new_empty #} >>= takeCaps\n\ncapsAny :: Caps\ncapsAny =\n unsafePerformIO $ {# call caps_new_any #} >>= takeCaps\n\ncapsSize :: Caps\n -> Word\ncapsSize caps =\n fromIntegral $ unsafePerformIO $ {# call caps_get_size #} caps\n\ncapsGetStructure :: Caps\n -> Word\n -> Maybe Structure\ncapsGetStructure caps index =\n unsafePerformIO $\n {# call caps_get_structure #} caps (fromIntegral index) >>=\n maybePeek peekStructure\n\ncapsIsEmpty :: Caps\n -> Bool\ncapsIsEmpty caps =\n toBool $ unsafePerformIO $\n {# call caps_is_empty #} caps\n\ncapsIsFixed :: Caps\n -> Bool\ncapsIsFixed caps =\n toBool $ unsafePerformIO $\n {# call caps_is_fixed #} caps\n\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\ncapsIsEqualFixed :: Caps\n -> Caps\n -> Bool\ncapsIsEqualFixed caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_equal_fixed #} caps1 caps2\n\ncapsIsAlwaysCompatible :: Caps\n -> Caps\n -> Bool\ncapsIsAlwaysCompatible caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_always_compatible #} caps1 caps2\n\ncapsIsSubset :: Caps\n -> Caps\n -> Bool\ncapsIsSubset caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_subset #} caps1 caps2\n\ncapsIntersect :: Caps\n -> Caps\n -> Caps\ncapsIntersect caps1 caps2 =\n unsafePerformIO $\n {# call caps_intersect #} caps1 caps2 >>=\n takeCaps\n\ncapsUnion :: Caps\n -> Caps\n -> Caps\ncapsUnion caps1 caps2 =\n unsafePerformIO $\n {# call caps_union #} caps1 caps2 >>=\n takeCaps\n\ncapsSubtract :: Caps\n -> Caps\n -> Caps\ncapsSubtract caps1 caps2 =\n unsafePerformIO $\n {# call caps_subtract #} caps1 caps2 >>=\n takeCaps\n\ncapsNormalize :: Caps\n -> Caps\ncapsNormalize caps =\n unsafePerformIO $\n {# call caps_normalize #} caps >>= takeCaps\n\ncapsToString :: Caps\n -> String\ncapsToString caps =\n unsafePerformIO $\n {# call caps_to_string #} caps >>= readUTFString\n\ncapsFromString :: String\n -> Caps\ncapsFromString string =\n unsafePerformIO $\n withUTFString string {# call caps_from_string #} >>=\n takeCaps\n\nnewtype CapsM a = CapsM (CapsMRep a)\ntype CapsMRep a = (Caps -> IO a)\n\ninstance Monad CapsM where\n (CapsM aM) >>= fbM =\n CapsM $ \\caps ->\n do a <- aM caps\n let CapsM bM = fbM a\n bM caps\n return a = CapsM $ const $ return a\n\nmarshalCapsModify :: IO (Ptr Caps)\n -> CapsM a\n -> (Caps, a)\nmarshalCapsModify mkCaps (CapsM action) =\n unsafePerformIO $\n do ptr <- mkCaps\n caps <- liftM Caps $ newForeignPtr_ ptr\n result <- action caps\n caps' <- takeCaps ptr\n return (caps', result)\n\ncapsCreate :: CapsM a\n -> (Caps, a)\ncapsCreate action =\n marshalCapsModify\n {# call caps_new_empty #}\n action\n\ncapsModify :: Caps\n -> CapsM a\n -> (Caps, a)\ncapsModify caps action =\n marshalCapsModify\n ({# call caps_copy #} caps)\n action\n\ncapsAppend :: Caps\n -> CapsM ()\ncapsAppend caps2 =\n CapsM $ \\caps1 ->\n {# call caps_copy #} caps2 >>= takeCaps >>=\n {# call caps_append #} caps1\n\ncapsMerge :: Caps\n -> CapsM ()\ncapsMerge caps2 =\n CapsM $ \\caps1 ->\n {# call caps_copy #} caps2 >>= takeCaps >>=\n {# call caps_merge #} caps1\n\ncapsAppendStructure :: Structure\n -> CapsM ()\ncapsAppendStructure structure =\n CapsM $ \\caps ->\n giveStructure structure $\n {# call caps_append_structure #} caps\n\ncapsMergeStructure :: Structure\n -> CapsM ()\ncapsMergeStructure structure =\n CapsM $ \\caps ->\n giveStructure structure $\n {# call caps_merge_structure #} caps\n\ncapsRemoveStructure :: Word\n -> CapsM ()\ncapsRemoveStructure idx =\n CapsM $ \\caps ->\n {# call caps_remove_structure #} caps $ fromIntegral idx\n\ncapsTruncate :: CapsM ()\ncapsTruncate =\n CapsM {# call caps_truncate #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"de935ab3caeef67fb5f7195d2fa6d628cd91c6e0","subject":"Define strnlen function on Windows","message":"Define strnlen function on Windows\n\nThe MinGW distribution bundled with GHC does not provide the strnlen function.","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module.chs","new_file":"Foreign\/CUDA\/Driver\/Module.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : [2009..2014] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..), JITFallback(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 ( throwIO )\nimport Data.Maybe ( mapMaybe )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal as B\n\n#if CUDA_VERSION < 5050\nimport Debug.Trace ( trace )\n#endif\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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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 , CU_PREFER_PTX as PTX }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\n#if defined(WIN32)\nc_strnlen' :: CString -> CSize -> IO CSize\nc_strnlen' str size = do\n str' <- peekCStringLen (str, fromIntegral size)\n return $ stringLen 0 str'\n where stringLen acc [] = acc\n stringLen acc ('\\0':xs) = acc\n stringLen acc (_:xs) = stringLen (acc+1) xs\n#else\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n#endif\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : [2009..2014] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..), JITFallback(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 ( throwIO )\nimport Data.Maybe ( mapMaybe )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal as B\n\n#if CUDA_VERSION < 5050\nimport Debug.Trace ( trace )\n#endif\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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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 , CU_PREFER_PTX as PTX }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"52e4a93b230869005f6a7247812eb6789cc2ecc9","subject":"don't change the external JITOption interface for cuda-5.0","message":"don't change the external JITOption interface for cuda-5.0\n\nYou'll get a runtime warning if you use an option that isn't supported in 5.0. Maybe that should be lifted to an error, but that is a bit annoying for clients to have to deal with.\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 BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Debug.Trace (trace)\nimport Data.Maybe (mapMaybe)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n#if CUDA_VERSION >= 5050\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\n#endif\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"40932e2476e47dfdf36c78b2862effd054e646dd","subject":"Have the runtime API throw exceptions","message":"Have the runtime API throw exceptions\n\nIgnore-this: 32bea19c60395283549a5a37c1f839f7\n- In the same manner as the driver bindings, throw exceptions rather than\n returning error codes that must be explicitly checked.\n- This is part one, updates to the individual modules to follow.\n\ndarcs-hash:20091219113837-dcabc-4df41191e97c3c7e35a8a98f21f5657167c69b6b.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_file":"Foreign\/CUDA\/Runtime\/Error.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error\n where\n\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Typeable\nimport Control.Exception\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\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-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorString as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the 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-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Error\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Error\n (\n Status(..),\n describe,\n resultIfOk,\n nothingIfOk\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum cudaError as Status\n { cudaSuccess as Success }\n with prefix=\"cudaError\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the descriptive string associated with a particular error code\n--\n{# fun pure unsafe cudaGetErrorString as describe\n { cFromEnum `Status' } -> `String' #}\n--\n-- Logically, this must be a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n\n\n-- |\n-- Return the results of a function on successful execution, otherwise return\n-- the error string associated with the return code\n--\nresultIfOk :: (Status, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (describe status)\n\n\n-- |\n-- Return the error string associated with an unsuccessful return code,\n-- otherwise Nothing\n--\nnothingIfOk :: Status -> Maybe String\nnothingIfOk = nothingIf (== Success) describe\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3f91089b3c3a6aa38842627e77850cb12f0862d0","subject":"Fix documenation to Editable.","message":"Fix documenation to Editable.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/Editable.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/Editable.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Interface Editable\n--\n-- Author : Axel Simon, Duncan Coutts\n--\n-- Created: 30 July 2004\n--\n-- Copyright (C) 1999-2005 Axel Simon, 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-- Interface for text-editing widgets\n--\nmodule Graphics.UI.Gtk.Entry.Editable (\n-- * Detail\n-- \n-- | The 'Editable' interface is an interface which should be implemented by\n-- text editing widgets, such as 'Entry'.\n-- It contains functions for generically manipulating an editable\n-- widget, a large number of action signals used for key bindings, and several\n-- signals that an application can connect to to modify the behavior of a\n-- widget.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | GInterface\n-- | +----Editable\n-- @\n\n-- * Types\n Editable,\n EditableClass,\n castToEditable, gTypeEditable,\n toEditable,\n\n-- * Methods\n editableSelectRegion,\n editableGetSelectionBounds,\n editableInsertText,\n editableDeleteText,\n editableGetChars,\n editableCutClipboard,\n editableCopyClipboard,\n editablePasteClipboard,\n editableDeleteSelection,\n editableSetEditable,\n editableGetEditable,\n editableSetPosition,\n editableGetPosition,\n\n-- * Attributes\n editablePosition,\n editableEditable,\n\n-- * Signals\n onEditableChanged,\n afterEditableChanged,\n onDeleteText,\n afterDeleteText,\n stopDeleteText,\n onInsertText,\n afterInsertText,\n stopInsertText\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Selects a region of text. The characters that are selected are those\n-- characters at positions from @startPos@ up to, but not including @endPos@.\n-- If @endPos@ is negative, then the the characters selected will be those\n-- characters from @startPos@ to the end of the text.\n--\n-- Calling this function with @start@=1 and @end@=4 it will mark \\\"ask\\\" in\n-- the string \\\"Haskell\\\".\n--\neditableSelectRegion :: EditableClass self => self\n -> Int -- ^ @start@ - the starting position.\n -> Int -- ^ @end@ - the end position.\n -> IO ()\neditableSelectRegion self start end =\n {# call editable_select_region #}\n (toEditable self)\n (fromIntegral start)\n (fromIntegral end)\n\n-- | Gets the current selection bounds, if there is a selection.\n--\neditableGetSelectionBounds :: EditableClass self => self\n -> IO (Int,Int) -- ^ @(start, end)@ - the starting and end positions. This\n -- pair is not ordered. The @end@ index represents the\n -- position of the cursor. The @start@ index is the other end\n -- of the selection. If both numbers are equal there is in\n -- fact no selection.\neditableGetSelectionBounds self =\n alloca $ \\startPtr ->\n alloca $ \\endPtr -> do\n {# call unsafe editable_get_selection_bounds #}\n (toEditable self)\n startPtr\n endPtr\n start <- liftM fromIntegral $ peek startPtr\n end <- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- | Inserts text at a given position.\n--\neditableInsertText :: EditableClass self => self\n -> String -- ^ @newText@ - the text to insert.\n -> Int -- ^ @position@ - the position at which to insert the text.\n -> IO Int -- ^ returns the position after the newly inserted text.\neditableInsertText self newText position = \n with (fromIntegral position) $ \\positionPtr ->\n withUTFStringLen newText $ \\(newTextPtr, newTextLength) -> do\n {# call editable_insert_text #}\n (toEditable self)\n newTextPtr\n (fromIntegral newTextLength)\n positionPtr\n position <- peek positionPtr\n return (fromIntegral position)\n\n-- | Deletes a sequence of characters. The characters that are deleted are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters deleted will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableDeleteText :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO ()\neditableDeleteText self startPos endPos =\n {# call editable_delete_text #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n\n-- | Retrieves a sequence of characters. The characters that are retrieved are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters retrieved will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableGetChars :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO String -- ^ returns the characters in the indicated region.\neditableGetChars self startPos endPos =\n {# call unsafe editable_get_chars #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n >>= readUTFString\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard and then deleted from the widget.\n--\neditableCutClipboard :: EditableClass self => self -> IO ()\neditableCutClipboard self =\n {# call editable_cut_clipboard #}\n (toEditable self)\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard.\n--\neditableCopyClipboard :: EditableClass self => self -> IO ()\neditableCopyClipboard self =\n {# call editable_copy_clipboard #}\n (toEditable self)\n\n-- | Causes the contents of the clipboard to be pasted into the given widget\n-- at the current cursor position.\n--\neditablePasteClipboard :: EditableClass self => self -> IO ()\neditablePasteClipboard self =\n {# call editable_paste_clipboard #}\n (toEditable self)\n\n-- | Deletes the current contents of the widgets selection and disclaims the\n-- selection.\n--\neditableDeleteSelection :: EditableClass self => self -> IO ()\neditableDeleteSelection self =\n {# call editable_delete_selection #}\n (toEditable self)\n\n-- | Sets the cursor position.\n--\neditableSetPosition :: EditableClass self => self\n -> Int -- ^ @position@ - the position of the cursor. The cursor is\n -- displayed before the character with the given (base 0) index in\n -- the widget. The value must be less than or equal to the number of\n -- characters in the widget. A value of -1 indicates that the\n -- position should be set after the last character in the entry.\n -> IO ()\neditableSetPosition self position =\n {# call editable_set_position #}\n (toEditable self)\n (fromIntegral position)\n\n-- | Retrieves the current cursor position.\n--\neditableGetPosition :: EditableClass self => self\n -> IO Int -- ^ returns the position of the cursor. The cursor is displayed\n -- before the character with the given (base 0) index in the widget.\n -- The value will be less than or equal to the number of characters\n -- in the widget. Note that this position is in characters, not in\n -- bytes.\neditableGetPosition self =\n liftM fromIntegral $\n {# call unsafe editable_get_position #}\n (toEditable self)\n\n-- | Determines if the user can edit the text in the editable widget or not.\n--\neditableSetEditable :: EditableClass self => self\n -> Bool -- ^ @isEditable@ - @True@ if the user is allowed to edit the text\n -- in the widget.\n -> IO ()\neditableSetEditable self isEditable =\n {# call editable_set_editable #}\n (toEditable self)\n (fromBool isEditable)\n\n-- | Retrieves whether the text is editable. See 'editableSetEditable'.\n--\neditableGetEditable :: EditableClass self => self -> IO Bool\neditableGetEditable self =\n liftM toBool $\n {# call editable_get_editable #}\n (toEditable self)\n\n--------------------\n-- Attributes\n\n-- | \\'position\\' property. See 'editableGetPosition' and\n-- 'editableSetPosition'\n--\neditablePosition :: EditableClass self => Attr self Int\neditablePosition = newAttr\n editableGetPosition\n editableSetPosition\n\n-- | \\'editable\\' property. See 'editableGetEditable' and\n-- 'editableSetEditable'\n--\neditableEditable :: EditableClass self => Attr self Bool\neditableEditable = newAttr\n editableGetEditable\n editableSetEditable\n\n--------------------\n-- Signals\n\n-- | The 'onEditableChanged' signal is emitted at the end of a single\n-- user-visible operation on the contents of the 'Editable'.\n--\n-- * For inctance, a paste operation that replaces the contents of the\n-- selection will cause only one signal emission (even though it is\n-- implemented by first deleting the selection, then inserting the new\n-- content, and may cause multiple 'onEditableInserText' signals to be\n-- emitted).\n--\nonEditableChanged, afterEditableChanged :: EditableClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEditableChanged = connect_NONE__NONE \"changed\" False\nafterEditableChanged = connect_NONE__NONE \"changed\" True\n\n-- | Emitted when a piece of text is deleted from the 'Editable' widget.\n--\n-- * See 'onInsertText' for information on how to use this signal.\n--\nonDeleteText, afterDeleteText :: EditableClass self => self\n -> (Int -> Int -> IO ()) -- ^ @(\\startPos endPos -> ...)@\n -> IO (ConnectId self)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- | Stop the current signal that deletes text.\nstopDeleteText :: EditableClass self => ConnectId self -> IO ()\nstopDeleteText (ConnectId _ obj) =\n signalStopEmission obj \"delete_text\"\n\n-- | Emitted when a piece of text is inserted into the 'Editable' widget.\n--\n-- * The connected signal receives the text that is inserted, together with\n-- the position in the entry widget. The return value should be the position\n-- in the entry widget that lies past the recently inserted text (i.e.\n-- you should return the given position plus the length of the string).\n--\n-- * To modify the text that the user inserts, you need to connect to this\n-- signal, modify the text the way you want and then call\n-- 'editableInsertText'. To avoid that this signal handler is called\n-- recursively, you need to temporarily block it using\n-- 'signalBlock'. After the default signal\n-- handler has inserted your modified text, it is important that you\n-- prevent the default handler from being executed again when this signal\n-- handler returns. To stop the current signal, use 'stopInsertText'.\n-- The following code is an example of how to turn all input into uppercase:\n--\n-- > idRef <- newIORef undefined\n-- > id <- onInsertText entry $ \\str pos -> do\n-- > id <- readIORef idRef\n-- > signalBlock id\n-- > pos' <- editableInsertText entry (map toUpper str) pos\n-- > signalUnblock id\n-- > stopInsertText id\n-- > return pos'\n-- > writeIORef idRef id\n--\n-- Note that the 'afterInsertText' function is not very useful, except to\n-- track editing actions.\n--\nonInsertText, afterInsertText :: EditableClass self => self\n -> (String -> Int -> IO Int)\n -> IO (ConnectId self)\nonInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" False obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\nafterInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" True obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\n\n-- | Stop the current signal that inserts text.\nstopInsertText :: EditableClass self => ConnectId self -> IO ()\nstopInsertText (ConnectId _ obj) =\n signalStopEmission obj \"insert_text\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Interface Editable\n--\n-- Author : Axel Simon, Duncan Coutts\n--\n-- Created: 30 July 2004\n--\n-- Copyright (C) 1999-2005 Axel Simon, 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-- Interface for text-editing widgets\n--\nmodule Graphics.UI.Gtk.Entry.Editable (\n-- * Detail\n-- \n-- | The 'Editable' interface is an interface which should be implemented by\n-- text editing widgets, such as 'Entry'.\n-- It contains functions for generically manipulating an editable\n-- widget, a large number of action signals used for key bindings, and several\n-- signals that an application can connect to to modify the behavior of a\n-- widget.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | GInterface\n-- | +----Editable\n-- @\n\n-- * Types\n Editable,\n EditableClass,\n castToEditable, gTypeEditable,\n toEditable,\n\n-- * Methods\n editableSelectRegion,\n editableGetSelectionBounds,\n editableInsertText,\n editableDeleteText,\n editableGetChars,\n editableCutClipboard,\n editableCopyClipboard,\n editablePasteClipboard,\n editableDeleteSelection,\n editableSetEditable,\n editableGetEditable,\n editableSetPosition,\n editableGetPosition,\n\n-- * Attributes\n editablePosition,\n editableEditable,\n\n-- * Signals\n onEditableChanged,\n afterEditableChanged,\n onDeleteText,\n afterDeleteText,\n stopDeleteText,\n onInsertText,\n afterInsertText,\n stopInsertText\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Selects a region of text. The characters that are selected are those\n-- characters at positions from @startPos@ up to, but not including @endPos@.\n-- If @endPos@ is negative, then the the characters selected will be those\n-- characters from @startPos@ to the end of the text.\n--\n-- Calling this function with @start@=1 and @end@=4 it will mark \\\"ask\\\" in\n-- the string \\\"Haskell\\\".\n--\neditableSelectRegion :: EditableClass self => self\n -> Int -- ^ @start@ - the starting position.\n -> Int -- ^ @end@ - the end position.\n -> IO ()\neditableSelectRegion self start end =\n {# call editable_select_region #}\n (toEditable self)\n (fromIntegral start)\n (fromIntegral end)\n\n-- | Gets the current selection bounds, if there is a selection.\n--\neditableGetSelectionBounds :: EditableClass self => self\n -> IO (Int,Int) -- ^ @(start, end)@ - the starting and end positions. This\n -- pair is not ordered. The @end@ index represents the\n -- position of the cursor. The @start@ index is the other end\n -- of the selection. If both numbers are equal there is in\n -- fact no selection.\neditableGetSelectionBounds self =\n alloca $ \\startPtr ->\n alloca $ \\endPtr -> do\n {# call unsafe editable_get_selection_bounds #}\n (toEditable self)\n startPtr\n endPtr\n start <- liftM fromIntegral $ peek startPtr\n end <- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- | Inserts text at a given position.\n--\neditableInsertText :: EditableClass self => self\n -> String -- ^ @newText@ - the text to insert.\n -> Int -- ^ @position@ - the position at which to insert the text.\n -> IO Int -- ^ returns the position after the newly inserted text.\neditableInsertText self newText position = \n with (fromIntegral position) $ \\positionPtr ->\n withUTFStringLen newText $ \\(newTextPtr, newTextLength) -> do\n {# call editable_insert_text #}\n (toEditable self)\n newTextPtr\n (fromIntegral newTextLength)\n positionPtr\n position <- peek positionPtr\n return (fromIntegral position)\n\n-- | Deletes a sequence of characters. The characters that are deleted are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters deleted will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableDeleteText :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO ()\neditableDeleteText self startPos endPos =\n {# call editable_delete_text #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n\n-- | Retrieves a sequence of characters. The characters that are retrieved are\n-- those characters at positions from @startPos@ up to, but not including\n-- @endPos@. If @endPos@ is negative, then the the characters retrieved will be\n-- those characters from @startPos@ to the end of the text.\n--\neditableGetChars :: EditableClass self => self\n -> Int -- ^ @startPos@ - the starting position.\n -> Int -- ^ @endPos@ - the end position.\n -> IO String -- ^ returns the characters in the indicated region.\neditableGetChars self startPos endPos =\n {# call unsafe editable_get_chars #}\n (toEditable self)\n (fromIntegral startPos)\n (fromIntegral endPos)\n >>= readUTFString\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard and then deleted from the widget.\n--\neditableCutClipboard :: EditableClass self => self -> IO ()\neditableCutClipboard self =\n {# call editable_cut_clipboard #}\n (toEditable self)\n\n-- | Causes the characters in the current selection to be copied to the\n-- clipboard.\n--\neditableCopyClipboard :: EditableClass self => self -> IO ()\neditableCopyClipboard self =\n {# call editable_copy_clipboard #}\n (toEditable self)\n\n-- | Causes the contents of the clipboard to be pasted into the given widget\n-- at the current cursor position.\n--\neditablePasteClipboard :: EditableClass self => self -> IO ()\neditablePasteClipboard self =\n {# call editable_paste_clipboard #}\n (toEditable self)\n\n-- | Deletes the current contents of the widgets selection and disclaims the\n-- selection.\n--\neditableDeleteSelection :: EditableClass self => self -> IO ()\neditableDeleteSelection self =\n {# call editable_delete_selection #}\n (toEditable self)\n\n-- | Sets the cursor position.\n--\neditableSetPosition :: EditableClass self => self\n -> Int -- ^ @position@ - the position of the cursor. The cursor is\n -- displayed before the character with the given (base 0) index in\n -- the widget. The value must be less than or equal to the number of\n -- characters in the widget. A value of -1 indicates that the\n -- position should be set after the last character in the entry.\n -> IO ()\neditableSetPosition self position =\n {# call editable_set_position #}\n (toEditable self)\n (fromIntegral position)\n\n-- | Retrieves the current cursor position.\n--\neditableGetPosition :: EditableClass self => self\n -> IO Int -- ^ returns the position of the cursor. The cursor is displayed\n -- before the character with the given (base 0) index in the widget.\n -- The value will be less than or equal to the number of characters\n -- in the widget. Note that this position is in characters, not in\n -- bytes.\neditableGetPosition self =\n liftM fromIntegral $\n {# call unsafe editable_get_position #}\n (toEditable self)\n\n-- | Determines if the user can edit the text in the editable widget or not.\n--\neditableSetEditable :: EditableClass self => self\n -> Bool -- ^ @isEditable@ - @True@ if the user is allowed to edit the text\n -- in the widget.\n -> IO ()\neditableSetEditable self isEditable =\n {# call editable_set_editable #}\n (toEditable self)\n (fromBool isEditable)\n\n-- | Retrieves whether the text is editable. See 'editableSetEditable'.\n--\neditableGetEditable :: EditableClass self => self -> IO Bool\neditableGetEditable self =\n liftM toBool $\n {# call editable_get_editable #}\n (toEditable self)\n\n--------------------\n-- Attributes\n\n-- | \\'position\\' property. See 'editableGetPosition' and\n-- 'editableSetPosition'\n--\neditablePosition :: EditableClass self => Attr self Int\neditablePosition = newAttr\n editableGetPosition\n editableSetPosition\n\n-- | \\'editable\\' property. See 'editableGetEditable' and\n-- 'editableSetEditable'\n--\neditableEditable :: EditableClass self => Attr self Bool\neditableEditable = newAttr\n editableGetEditable\n editableSetEditable\n\n--------------------\n-- Signals\n\n-- | Emitted when the settings of the 'Editable' widget changes.\n--\nonEditableChanged, afterEditableChanged :: EditableClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEditableChanged = connect_NONE__NONE \"changed\" False\nafterEditableChanged = connect_NONE__NONE \"changed\" True\n\n-- | Emitted when a piece of text is deleted from the 'Editable' widget.\n--\n-- * See 'onInsertText' for information on how to use this signal.\n--\nonDeleteText, afterDeleteText :: EditableClass self => self\n -> (Int -> Int -> IO ()) -- ^ @(\\startPos endPos -> ...)@\n -> IO (ConnectId self)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- | Stop the current signal that deletes text.\nstopDeleteText :: EditableClass self => ConnectId self -> IO ()\nstopDeleteText (ConnectId _ obj) =\n signalStopEmission obj \"delete_text\"\n\n-- | Emitted when a piece of text is inserted into the 'Editable' widget.\n--\n-- * The connected signal receives the text that is inserted, together with\n-- the position in the entry widget. The return value should be the position\n-- in the entry widget that lies past the recently inserted text (i.e.\n-- you should return the given position plus the length of the string).\n--\n-- * To modify the text that the user inserts, you need to connect to this\n-- signal, modify the text the way you want and then call\n-- 'editableInsertText'. To avoid that this signal handler is called\n-- recursively, you need to temporarily block it using\n-- 'signalBlock'. After the default signal\n-- handler has inserted your modified text, it is important that you\n-- prevent the default handler from being executed again when this signal\n-- handler returns. To stop the current signal, use 'stopInsertText'.\n-- The following code is an example of how to turn all input into uppercase:\n--\n-- > idRef <- newIORef undefined\n-- > id <- onInsertText entry $ \\str pos -> do\n-- > id <- readIORef idRef\n-- > signalBlock id\n-- > pos' <- editableInsertText entry (map toUpper str) pos\n-- > signalUnblock id\n-- > stopInsertText id\n-- > return pos'\n-- > writeIORef idRef id\n--\n-- Note that the 'afterInsertText' function is not very useful, except to\n-- track editing actions.\n--\nonInsertText, afterInsertText :: EditableClass self => self\n -> (String -> Int -> IO Int)\n -> IO (ConnectId self)\nonInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" False obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\nafterInsertText obj handler =\n connect_PTR_INT_PTR__NONE \"insert_text\" True obj\n (\\strPtr strLen posPtr -> do\n str <- if strLen<0 then peekUTFString strPtr\n else peekUTFStringLen (strPtr, strLen)\n pos <- peek (posPtr :: Ptr {#type gint#})\n pos' <- handler str (fromIntegral pos)\n poke (posPtr :: Ptr {#type gint#}) (fromIntegral pos')\n )\n\n-- | Stop the current signal that inserts text.\nstopInsertText :: EditableClass self => ConnectId self -> IO ()\nstopInsertText (ConnectId _ obj) =\n signalStopEmission obj \"insert_text\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f7414726ff5a9a0e841a14acb9ae027cf027a468","subject":"name function parameter alternatives consistently","message":"name function parameter alternatives consistently\n\nIgnore-this: f3c4fd17b1950b62fd03036546c368df\n\ndarcs-hash:20091210065127-9241b-c04f6518b01fac2ec208a709034375a86ea633ad.gz\n","repos":"phaazon\/cuda,mwu-tow\/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, FunParam(..), FunAttribute(..), newFun, withFun,\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, withStream)\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Maybe\nimport Control.Monad (zipWithM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A __global__ device function\n--\n{# pointer *CUfunction as Fun foreign newtype #}\nwithFun :: Fun -> (Ptr Fun -> IO a) -> IO a\n\nnewFun :: IO Fun\nnewFun = Fun `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\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-- | TRef 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 (Either String Int)\nrequires fn att = withFun fn $ \\f -> (resultIfOk `fmap` cuFuncGetAttribute att f)\n\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , castPtr `Ptr 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 (Maybe String)\nsetBlockShape fn (x,y,z) = withFun fn $ \\f -> (nothingIfOk `fmap` cuFuncSetBlockShape f x y z)\n\n{# fun unsafe cuFuncSetBlockShape\n { castPtr `Ptr 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 (Maybe String)\nsetSharedSize fn bytes = withFun fn $ \\f -> (nothingIfOk `fmap` cuFuncSetSharedSize f bytes)\n\n{# fun unsafe cuFuncSetSharedSize\n { castPtr `Ptr 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 (Maybe String)\nlaunch fn (w,h) mst =\n withFun fn $ \\f ->\n nothingIfOk `fmap` case mst of\n Nothing -> cuLaunchGridAsync f w h nullPtr\n Just st -> (withStream st $ \\s -> cuLaunchGridAsync f w h s)\n\n{# fun unsafe cuLaunchGridAsync\n { castPtr `Ptr Fun'\n , `Int'\n , `Int'\n , castPtr `Ptr 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 (Maybe [String])\nsetParams fn prs =\n withFun fn $ \\f ->\n cuParamSetSize f (last offsets) >>= \\rv ->\n case nothingIfOk rv of\n Just err -> return (Just [err])\n Nothing -> (maybeNull . catMaybes) `fmap` zipWithM (set f) offsets prs\n where\n maybeNull [] = Nothing\n maybeNull x = Just x\n\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 `fmap` cuParamSeti f o v\n set f o (FArg v) = nothingIfOk `fmap` cuParamSetf f o v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk `fmap` cuParamSetv f o p (sizeOf v))\n\n\n{# fun unsafe cuParamSetSize\n { castPtr `Ptr Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSeti\n { castPtr `Ptr Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetf\n { castPtr `Ptr Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { castPtr `Ptr 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, FunParam(..), FunAttribute(..), newFun, withFun,\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, withStream)\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Maybe\nimport Control.Monad (zipWithM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A __global__ device function\n--\n{# pointer *CUfunction as Fun foreign newtype #}\nwithFun :: Fun -> (Ptr Fun -> IO a) -> IO a\n\nnewFun :: IO Fun\nnewFun = Fun `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\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 = IVal Int\n | FVal Float\n | VArg a\n-- | TRef 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 (Either String Int)\nrequires fn att = withFun fn $ \\f -> (resultIfOk `fmap` cuFuncGetAttribute att f)\n\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , castPtr `Ptr 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 (Maybe String)\nsetBlockShape fn (x,y,z) = withFun fn $ \\f -> (nothingIfOk `fmap` cuFuncSetBlockShape f x y z)\n\n{# fun unsafe cuFuncSetBlockShape\n { castPtr `Ptr 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 (Maybe String)\nsetSharedSize fn bytes = withFun fn $ \\f -> (nothingIfOk `fmap` cuFuncSetSharedSize f bytes)\n\n{# fun unsafe cuFuncSetSharedSize\n { castPtr `Ptr 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 (Maybe String)\nlaunch fn (w,h) mst =\n withFun fn $ \\f ->\n nothingIfOk `fmap` case mst of\n Nothing -> cuLaunchGridAsync f w h nullPtr\n Just st -> (withStream st $ \\s -> cuLaunchGridAsync f w h s)\n\n{# fun unsafe cuLaunchGridAsync\n { castPtr `Ptr Fun'\n , `Int'\n , `Int'\n , castPtr `Ptr 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 (Maybe [String])\nsetParams fn prs =\n withFun fn $ \\f ->\n cuParamSetSize f (last offsets) >>= \\rv ->\n case nothingIfOk rv of\n Just err -> return (Just [err])\n Nothing -> (maybeNull . catMaybes) `fmap` zipWithM (set f) offsets prs\n where\n maybeNull [] = Nothing\n maybeNull x = Just x\n\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IVal v) = sizeOf v\n size (FVal v) = sizeOf v\n size (VArg v) = sizeOf v\n\n set f o (IVal v) = nothingIfOk `fmap` cuParamSeti f o v\n set f o (FVal v) = nothingIfOk `fmap` cuParamSetf f o v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk `fmap` cuParamSetv f o p (sizeOf v))\n\n\n{# fun unsafe cuParamSetSize\n { castPtr `Ptr Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSeti\n { castPtr `Ptr Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetf\n { castPtr `Ptr Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { castPtr `Ptr Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d9abd502c4c3caf4953ac67e54469700dad01756","subject":"fix double stable pointer free causing segfaults in some situations","message":"fix double stable pointer free causing segfaults in some situations\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/EventTargetClosures.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/EventTargetClosures.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# CFILES events.c #-}\nmodule Graphics.UI.Gtk.WebKit.DOM.EventTargetClosures\n (EventName(..), SaferEventListener(..), EventListener(..), unEventListener, EventListenerClass(..),\n eventListenerNew, eventListenerNewAsync, eventListenerNewSync, eventListenerRelease) where\nimport Control.Monad.Reader (ReaderT)\nimport System.Glib.FFI (newStablePtr, freeStablePtr, StablePtr, Ptr(..), toBool, CInt(..), CChar,\n withForeignPtr, fromBool)\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Control.Monad (void)\n\nnewtype EventName t e = EventName String\nnewtype SaferEventListener t e = SaferEventListener EventListener\n\n{# pointer *GClosure newtype #}\n\ndata EventListener = EventListener (Ptr GClosure) (StablePtr (Ptr GObject -> Ptr GObject -> IO ()))\n\nunEventListener (EventListener p _) = p\n\nclass EventListenerClass a where\n toEventListener :: a -> EventListener\n\ninstance EventListenerClass EventListener where\n toEventListener a = a\n\nforeign import ccall unsafe \"gtk2hs_closure_new\"\n gtk2hs_closure_new :: StablePtr a -> IO (Ptr GClosure)\n\neventListenerNew :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNew callback = do\n sptr <- newStablePtr action\n gclosurePtr <- gtk2hs_closure_new sptr\n return $ EventListener gclosurePtr sptr\n where action :: Ptr GObject -> Ptr GObject -> IO ()\n action obj1 obj2 =\n failOnGError $\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj2) >>= \\obj2' ->\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj1) >>= \\obj1' ->\n callback (unsafeCastGObject obj2')\n\neventListenerNewAsync :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNewAsync = eventListenerNew\n\neventListenerNewSync :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNewSync = eventListenerNew\n\nforeign import ccall unsafe \"g_closure_unref\"\n g_closure_unref :: Ptr GClosure -> IO ()\n\neventListenerRelease :: EventListener -> IO ()\neventListenerRelease (EventListener gclosurePtr sptr) = do\n g_closure_unref gclosurePtr\n\n\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# CFILES events.c #-}\nmodule Graphics.UI.Gtk.WebKit.DOM.EventTargetClosures\n (EventName(..), SaferEventListener(..), EventListener(..), unEventListener, EventListenerClass(..),\n eventListenerNew, eventListenerNewAsync, eventListenerNewSync, eventListenerRelease) where\nimport Control.Monad.Reader (ReaderT)\nimport System.Glib.FFI (newStablePtr, freeStablePtr, StablePtr, Ptr(..), toBool, CInt(..), CChar,\n withForeignPtr, fromBool)\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Control.Monad (void)\n\nnewtype EventName t e = EventName String\nnewtype SaferEventListener t e = SaferEventListener EventListener\n\n{# pointer *GClosure newtype #}\n\ndata EventListener = EventListener (Ptr GClosure) (StablePtr (Ptr GObject -> Ptr GObject -> IO ()))\n\nunEventListener (EventListener p _) = p\n\nclass EventListenerClass a where\n toEventListener :: a -> EventListener\n\ninstance EventListenerClass EventListener where\n toEventListener a = a\n\nforeign import ccall unsafe \"gtk2hs_closure_new\"\n gtk2hs_closure_new :: StablePtr a -> IO (Ptr GClosure)\n\neventListenerNew :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNew callback = do\n sptr <- newStablePtr action\n gclosurePtr <- gtk2hs_closure_new sptr\n return $ EventListener gclosurePtr sptr\n where action :: Ptr GObject -> Ptr GObject -> IO ()\n action obj1 obj2 =\n failOnGError $\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj2) >>= \\obj2' ->\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj1) >>= \\obj1' ->\n callback (unsafeCastGObject obj2')\n\neventListenerNewAsync :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNewAsync = eventListenerNew\n\neventListenerNewSync :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNewSync = eventListenerNew\n\nforeign import ccall unsafe \"g_closure_unref\"\n g_closure_unref :: Ptr GClosure -> IO ()\n\neventListenerRelease :: EventListener -> IO ()\neventListenerRelease (EventListener gclosurePtr sptr) = do\n g_closure_unref gclosurePtr\n freeStablePtr sptr\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e6f39cd0fdf8233b7848e848fffbc86dc931ec3c","subject":"Sanity check before invoking new call operations.","message":"Sanity check before invoking new call operations.\n\nCheck before invoking call operations whether the call is still going\non.\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 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","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 :: !(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 , 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 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":"661d753e9a7c42f1e3cd7ba97c190bde3f157422","subject":"[project @ 2004-07-29 12:14:23 by duncan_coutts] make FileChooserError an instance of GErrorClass so users can catch exceptions nicely using the FileChooserError enum.","message":"[project @ 2004-07-29 12:14:23 by duncan_coutts]\nmake FileChooserError an instance of GErrorClass so users can catch exceptions\nnicely using the FileChooserError enum.\n","repos":"vincenthz\/webkit","old_file":"gtk\/abstract\/FileChooser.chs","new_file":"gtk\/abstract\/FileChooser.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to GConf -*-haskell-*-\n-- for storing and retrieving configuartion information\n--\n-- Author : Duncan Coutts\n-- Created: 24 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n--\n-- The file chooser dialog and widget is a replacement\n-- for the old \"FileSel\"ection dialog. It provides a better user\n-- interface and an improved API.\n--\n-- The FileChooser (as opposed to the dialog or widget) is the interface that\n-- the \"FileChooserDialog\" and \"FileChooserWidget\" implement, all the operations\n-- except construction are on this interface.\n--\n-- * Added in GTK+ 2.4\n--\n\nmodule FileChooser (\n FileChooserClass,\n FileChooser,\n FileChooserAction(..),\n fileChooserSetAction,\n fileChooserGetAction,\n fileChooserSetLocalOnly,\n fileChooserGetLocalOnly,\n fileChooserSetSelectMultiple,\n fileChooserGetSelectMultiple,\n fileChooserSetCurrentName,\n fileChooserGetFilename,\n fileChooserSetFilename,\n fileChooserSelectFilename,\n fileChooserUnselectFilename,\n fileChooserSelectAll,\n fileChooserUnselectAll,\n fileChooserGetFilenames,\n fileChooserSetCurrentFolder,\n fileChooserGetCurrentFolder,\n fileChooserGetURI,\n fileChooserSetURI,\n fileChooserSelectURI,\n fileChooserUnselectURI,\n fileChooserGetURIs,\n fileChooserSetCurrentFolderURI,\n fileChooserGetCurrentFolderURI,\n fileChooserSetPreviewWidget,\n fileChooserGetPreviewWidget,\n fileChooserSetPreviewWidgetActive,\n fileChooserGetPreviewWidgetActive,\n fileChooserSetUsePreviewLabel,\n fileChooserGetUsePreviewLabel,\n fileChooserGetPreviewFilename,\n fileChooserGetPreviewURI,\n fileChooserSetExtraWidget,\n fileChooserGetExtraWidget,\n fileChooserAddFilter,\n fileChooserRemoveFilter,\n fileChooserListFilters,\n fileChooserSetFilter,\n fileChooserGetFilter,\n fileChooserAddShortcutFolder,\n fileChooserRemoveShortcutFolder,\n fileChooserlistShortcutFolders,\n fileChooserAddShortcutFolderURI,\n fileChooserRemoveShortcutFolderURI,\n fileChooserListShortcutFolderURIs,\n onCurrentFolderChanged,\n afterCurrentFolderChanged,\n onFileActivated,\n afterFileActivated,\n-- onSelectionChanged,\n-- afterSelectionChanged,\n onUpdatePreview,\n afterUpdatePreview\n) where\n\nimport Monad (liftM, when)\nimport FFI\n{#import Hierarchy#}\nimport Object\t\t(makeNewObject)\nimport Signal\n{#import GList#}\nimport GError (propagateGError, GErrorDomain, GErrorClass(..))\n\n{# context lib=\"gtk\" prefix =\"gtk\" #}\n\n{# enum FileChooserAction {underscoreToCase} #}\n{# enum FileChooserError {underscoreToCase} #}\n\nfileChooserErrorDomain :: GErrorDomain\nfileChooserErrorDomain = unsafePerformIO {#call unsafe file_chooser_error_quark#}\n \ninstance GErrorClass FileChooserError where\n gerrorDomain _ = fileChooserErrorDomain\n\nfileChooserSetAction :: FileChooserClass chooser => chooser -> FileChooserAction -> IO ()\nfileChooserSetAction chooser action =\n {# call gtk_file_chooser_set_action #} (toFileChooser chooser)\n (fromIntegral $ fromEnum action)\n\nfileChooserGetAction :: FileChooserClass chooser => chooser -> IO FileChooserAction\nfileChooserGetAction chooser = liftM (toEnum . fromIntegral) $\n {# call gtk_file_chooser_get_action #} (toFileChooser chooser)\n\nfileChooserSetLocalOnly :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetLocalOnly chooser localOnly = \n {# call gtk_file_chooser_set_local_only #} (toFileChooser chooser)\n (fromBool localOnly)\n\nfileChooserGetLocalOnly :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetLocalOnly chooser = liftM toBool $\n {# call gtk_file_chooser_get_local_only #} (toFileChooser chooser)\n\nfileChooserSetSelectMultiple :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetSelectMultiple chooser selectMultiple = \n {# call gtk_file_chooser_set_select_multiple #} (toFileChooser chooser)\n (fromBool selectMultiple)\n\nfileChooserGetSelectMultiple :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetSelectMultiple chooser = liftM toBool $\n {# call gtk_file_chooser_get_select_multiple #} (toFileChooser chooser)\n\nfileChooserSetCurrentName :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserSetCurrentName chooser name =\n withCString name $ \\strPtr ->\n {# call gtk_file_chooser_set_current_name #} (toFileChooser chooser) strPtr\n\nfileChooserGetFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_set_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_select_filename #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectFilename :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectFilename chooser filename = \n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_unselect_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserSelectAll chooser = \n {# call gtk_file_chooser_select_all #} (toFileChooser chooser)\n\nfileChooserUnselectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserUnselectAll chooser = \n {# call gtk_file_chooser_unselect_all #} (toFileChooser chooser)\n\nfileChooserGetFilenames :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetFilenames chooser = do\n strList <- {# call gtk_file_chooser_get_filenames #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolder :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolder chooser foldername = liftM toBool $\n withCString foldername $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolder :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetCurrentFolder chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_uri #} (toFileChooser chooser) strPtr\n\nfileChooserSelectURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_select_uri #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectURI chooser uri = \n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_unselect_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetURIs chooser = do\n strList <- {# call gtk_file_chooser_get_uris #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolderURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolderURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolderURI :: FileChooserClass chooser => chooser -> IO String\nfileChooserGetCurrentFolderURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder_uri #} (toFileChooser chooser)\n readCString strPtr\n\nfileChooserSetPreviewWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetPreviewWidget chooser widget = \n {# call gtk_file_chooser_set_preview_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetPreviewWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetPreviewWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_preview_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserSetPreviewWidgetActive :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetPreviewWidgetActive chooser active = \n {# call gtk_file_chooser_set_preview_widget_active #} (toFileChooser chooser)\n (fromBool active)\n\nfileChooserGetPreviewWidgetActive :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetPreviewWidgetActive chooser = liftM toBool $\n {# call gtk_file_chooser_get_preview_widget_active #} (toFileChooser chooser)\n\nfileChooserSetUsePreviewLabel :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetUsePreviewLabel chooser usePreview = \n {# call gtk_file_chooser_set_use_preview_label #} (toFileChooser chooser)\n (fromBool usePreview)\n\nfileChooserGetUsePreviewLabel :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetUsePreviewLabel chooser = liftM toBool $\n {# call gtk_file_chooser_get_use_preview_label #} (toFileChooser chooser)\n\nfileChooserGetPreviewFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetPreviewURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetExtraWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetExtraWidget chooser widget = \n {# call gtk_file_chooser_set_extra_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetExtraWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetExtraWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_extra_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserAddFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserAddFilter chooser filter = \n {# call gtk_file_chooser_add_filter #} (toFileChooser chooser) filter\n\nfileChooserRemoveFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserRemoveFilter chooser filter = \n {# call gtk_file_chooser_remove_filter #} (toFileChooser chooser) filter\n\nfileChooserListFilters :: FileChooserClass chooser => chooser -> IO [FileFilter]\nfileChooserListFilters chooser = do\n filterList <- {# call gtk_file_chooser_list_filters #} (toFileChooser chooser)\n filterPtrs <- fromGSList filterList\n mapM (makeNewObject mkFileFilter . return) filterPtrs\n\nfileChooserSetFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserSetFilter chooser filter = \n {# call gtk_file_chooser_set_filter #} (toFileChooser chooser) filter\n\nfileChooserGetFilter :: FileChooserClass chooser => chooser -> IO (Maybe FileFilter)\nfileChooserGetFilter chooser = do\n ptr <- {# call gtk_file_chooser_get_filter #} (toFileChooser chooser)\n maybePeek (makeNewObject mkFileFilter . return) ptr\n\nfileChooserAddShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserlistShortcutFolders :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserlistShortcutFolders chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folders #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserAddShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder_uri #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder_uri #}\n (toFileChooser chooser) strPtr gerrorPtr\n return ()\n\nfileChooserListShortcutFolderURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserListShortcutFolderURIs chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folder_uris #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nonCurrentFolderChanged, afterCurrentFolderChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" False\nafterCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" True\n\nonFileActivated, afterFileActivated :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonFileActivated = connect_NONE__NONE \"file-activated\" False\nafterFileActivated = connect_NONE__NONE \"file-activated\" True\n\n--onSelectionChanged, afterSelectionChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\n--onSelectionChanged = connect_NONE__NONE \"selection-changed\" False\n--afterSelectionChanged = connect_NONE__NONE \"selection-changed\" True\n\nonUpdatePreview, afterUpdatePreview :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonUpdatePreview = connect_NONE__NONE \"update-preview\" False\nafterUpdatePreview = connect_NONE__NONE \"update-preview\" True\n\n\n------------------------------------------------------\n-- Utility functions that really ought to go elsewhere\n\n-- like peekCString but then frees the string using g_free\nreadCString :: CString -> IO String\nreadCString strPtr = do\n str <- peekCString strPtr\n {# call unsafe g_free #} (castPtr strPtr)\n return str\n\n-- convenience functions for GSlists of strings\nfromStringGSList :: GSList -> IO [String]\nfromStringGSList strList = do\n strPtrs <- fromGSList strList\n mapM readCString strPtrs\n\ntoStringGSList :: [String] -> IO GSList\ntoStringGSList strs = do\n strPtrs <- mapM newCString strs\n toGSList strPtrs\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to GConf -*-haskell-*-\n-- for storing and retrieving configuartion information\n--\n-- Author : Duncan Coutts\n-- Created: 24 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n--\n-- The file chooser dialog and widget is a replacement\n-- for the old \"FileSel\"ection dialog. It provides a better user\n-- interface and an improved API.\n--\n-- The FileChooser (as opposed to the dialog or widget) is the interface that\n-- the \"FileChooserDialog\" and \"FileChooserWidget\" implement, all the operations\n-- except construction are on this interface.\n--\n-- * Added in GTK+ 2.4\n--\n\nmodule FileChooser (\n FileChooserClass,\n FileChooser,\n FileChooserAction(..),\n fileChooserSetAction,\n fileChooserGetAction,\n fileChooserSetLocalOnly,\n fileChooserGetLocalOnly,\n fileChooserSetSelectMultiple,\n fileChooserGetSelectMultiple,\n fileChooserSetCurrentName,\n fileChooserGetFilename,\n fileChooserSetFilename,\n fileChooserSelectFilename,\n fileChooserUnselectFilename,\n fileChooserSelectAll,\n fileChooserUnselectAll,\n fileChooserGetFilenames,\n fileChooserSetCurrentFolder,\n fileChooserGetCurrentFolder,\n fileChooserGetURI,\n fileChooserSetURI,\n fileChooserSelectURI,\n fileChooserUnselectURI,\n fileChooserGetURIs,\n fileChooserSetCurrentFolderURI,\n fileChooserGetCurrentFolderURI,\n fileChooserSetPreviewWidget,\n fileChooserGetPreviewWidget,\n fileChooserSetPreviewWidgetActive,\n fileChooserGetPreviewWidgetActive,\n fileChooserSetUsePreviewLabel,\n fileChooserGetUsePreviewLabel,\n fileChooserGetPreviewFilename,\n fileChooserGetPreviewURI,\n fileChooserSetExtraWidget,\n fileChooserGetExtraWidget,\n fileChooserAddFilter,\n fileChooserRemoveFilter,\n fileChooserListFilters,\n fileChooserSetFilter,\n fileChooserGetFilter,\n fileChooserAddShortcutFolder,\n fileChooserRemoveShortcutFolder,\n fileChooserlistShortcutFolders,\n fileChooserAddShortcutFolderURI,\n fileChooserRemoveShortcutFolderURI,\n fileChooserListShortcutFolderURIs,\n onCurrentFolderChanged,\n afterCurrentFolderChanged,\n onFileActivated,\n afterFileActivated,\n-- onSelectionChanged,\n-- afterSelectionChanged,\n onUpdatePreview,\n afterUpdatePreview\n) where\n\nimport Monad (liftM, when)\nimport FFI\n{#import Hierarchy#}\nimport Object\t\t(makeNewObject)\nimport Signal\n{#import GList#}\nimport GError (propagateGError)\n\n{# context lib=\"gtk\" prefix =\"gtk\" #}\n\n{# enum FileChooserAction {underscoreToCase} #}\n{# enum FileChooserError {underscoreToCase} #}\n\nfileChooserSetAction :: FileChooserClass chooser => chooser -> FileChooserAction -> IO ()\nfileChooserSetAction chooser action =\n {# call gtk_file_chooser_set_action #} (toFileChooser chooser)\n (fromIntegral $ fromEnum action)\n\nfileChooserGetAction :: FileChooserClass chooser => chooser -> IO FileChooserAction\nfileChooserGetAction chooser = liftM (toEnum . fromIntegral) $\n {# call gtk_file_chooser_get_action #} (toFileChooser chooser)\n\nfileChooserSetLocalOnly :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetLocalOnly chooser localOnly = \n {# call gtk_file_chooser_set_local_only #} (toFileChooser chooser)\n (fromBool localOnly)\n\nfileChooserGetLocalOnly :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetLocalOnly chooser = liftM toBool $\n {# call gtk_file_chooser_get_local_only #} (toFileChooser chooser)\n\nfileChooserSetSelectMultiple :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetSelectMultiple chooser selectMultiple = \n {# call gtk_file_chooser_set_select_multiple #} (toFileChooser chooser)\n (fromBool selectMultiple)\n\nfileChooserGetSelectMultiple :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetSelectMultiple chooser = liftM toBool $\n {# call gtk_file_chooser_get_select_multiple #} (toFileChooser chooser)\n\nfileChooserSetCurrentName :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserSetCurrentName chooser name =\n withCString name $ \\strPtr ->\n {# call gtk_file_chooser_set_current_name #} (toFileChooser chooser) strPtr\n\nfileChooserGetFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_set_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_select_filename #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectFilename :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectFilename chooser filename = \n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_unselect_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserSelectAll chooser = \n {# call gtk_file_chooser_select_all #} (toFileChooser chooser)\n\nfileChooserUnselectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserUnselectAll chooser = \n {# call gtk_file_chooser_unselect_all #} (toFileChooser chooser)\n\nfileChooserGetFilenames :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetFilenames chooser = do\n strList <- {# call gtk_file_chooser_get_filenames #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolder :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolder chooser foldername = liftM toBool $\n withCString foldername $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolder :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetCurrentFolder chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_uri #} (toFileChooser chooser) strPtr\n\nfileChooserSelectURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_select_uri #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectURI chooser uri = \n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_unselect_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetURIs chooser = do\n strList <- {# call gtk_file_chooser_get_uris #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolderURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolderURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolderURI :: FileChooserClass chooser => chooser -> IO String\nfileChooserGetCurrentFolderURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder_uri #} (toFileChooser chooser)\n readCString strPtr\n\nfileChooserSetPreviewWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetPreviewWidget chooser widget = \n {# call gtk_file_chooser_set_preview_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetPreviewWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetPreviewWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_preview_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserSetPreviewWidgetActive :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetPreviewWidgetActive chooser active = \n {# call gtk_file_chooser_set_preview_widget_active #} (toFileChooser chooser)\n (fromBool active)\n\nfileChooserGetPreviewWidgetActive :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetPreviewWidgetActive chooser = liftM toBool $\n {# call gtk_file_chooser_get_preview_widget_active #} (toFileChooser chooser)\n\nfileChooserSetUsePreviewLabel :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetUsePreviewLabel chooser usePreview = \n {# call gtk_file_chooser_set_use_preview_label #} (toFileChooser chooser)\n (fromBool usePreview)\n\nfileChooserGetUsePreviewLabel :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetUsePreviewLabel chooser = liftM toBool $\n {# call gtk_file_chooser_get_use_preview_label #} (toFileChooser chooser)\n\nfileChooserGetPreviewFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetPreviewURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetExtraWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetExtraWidget chooser widget = \n {# call gtk_file_chooser_set_extra_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetExtraWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetExtraWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_extra_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserAddFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserAddFilter chooser filter = \n {# call gtk_file_chooser_add_filter #} (toFileChooser chooser) filter\n\nfileChooserRemoveFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserRemoveFilter chooser filter = \n {# call gtk_file_chooser_remove_filter #} (toFileChooser chooser) filter\n\nfileChooserListFilters :: FileChooserClass chooser => chooser -> IO [FileFilter]\nfileChooserListFilters chooser = do\n filterList <- {# call gtk_file_chooser_list_filters #} (toFileChooser chooser)\n filterPtrs <- fromGSList filterList\n mapM (makeNewObject mkFileFilter . return) filterPtrs\n\nfileChooserSetFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserSetFilter chooser filter = \n {# call gtk_file_chooser_set_filter #} (toFileChooser chooser) filter\n\nfileChooserGetFilter :: FileChooserClass chooser => chooser -> IO (Maybe FileFilter)\nfileChooserGetFilter chooser = do\n ptr <- {# call gtk_file_chooser_get_filter #} (toFileChooser chooser)\n maybePeek (makeNewObject mkFileFilter . return) ptr\n\nfileChooserAddShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserlistShortcutFolders :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserlistShortcutFolders chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folders #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserAddShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder_uri #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder_uri #}\n (toFileChooser chooser) strPtr gerrorPtr\n return ()\n\nfileChooserListShortcutFolderURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserListShortcutFolderURIs chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folder_uris #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nonCurrentFolderChanged, afterCurrentFolderChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" False\nafterCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" True\n\nonFileActivated, afterFileActivated :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonFileActivated = connect_NONE__NONE \"file-activated\" False\nafterFileActivated = connect_NONE__NONE \"file-activated\" True\n\n--onSelectionChanged, afterSelectionChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\n--onSelectionChanged = connect_NONE__NONE \"selection-changed\" False\n--afterSelectionChanged = connect_NONE__NONE \"selection-changed\" True\n\nonUpdatePreview, afterUpdatePreview :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonUpdatePreview = connect_NONE__NONE \"update-preview\" False\nafterUpdatePreview = connect_NONE__NONE \"update-preview\" True\n\n\n------------------------------------------------------\n-- Utility functions that really ought to go elsewhere\n\n-- like peekCString but then frees the string using g_free\nreadCString :: CString -> IO String\nreadCString strPtr = do\n str <- peekCString strPtr\n {# call unsafe g_free #} (castPtr strPtr)\n return str\n\n-- convenience functions for GSlists of strings\nfromStringGSList :: GSList -> IO [String]\nfromStringGSList strList = do\n strPtrs <- fromGSList strList\n mapM readCString strPtrs\n\ntoStringGSList :: [String] -> IO GSList\ntoStringGSList strs = do\n strPtrs <- mapM newCString strs\n toGSList strPtrs\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"c79c3b77ff4e4882f9df9a5b9773997eb808ea20","subject":"improve implementation of loadDataFromPtrEx","message":"improve implementation of loadDataFromPtrEx\n\nAvoid some excessive copying when marshaling values to and from C. Instead of allocating temporary arrays, then copying these to ByteStrings, we can do a little better.\n\n * The error log is no longer returned as a ByteString. So, just marshal it directly to a Haskell String for the error message.\n\n * The info log is allocated as a foreign pointer and the C function writes directly into it. We still need on O(n) operation to gets its length so it can be trimmed when wrapping into a ByteString, but there is no additional copy.\n\n * Either operation is only done when required, on the success or failure branch.\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module.chs","new_file":"Foreign\/CUDA\/Driver\/Module.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !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, this is extracted below\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 case s of\n Success -> return (JITResult time infoLog mdl)\n _ -> cudaError (unlines [describe s, B.unpack 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"875dddaff5933e6c6b030e09ccf2b9fbea8bb931","subject":"parentObjID","message":"parentObjID\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\nnewtype Tree = Tree 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\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\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\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\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\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\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\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\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\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"4656f50c28467133c90e753d65fe8c6a259982f9","subject":"Trivial tidyup of export list in GConfValue.chs","message":"Trivial tidyup of export list in GConfValue.chs\n\nBy using this style:\nGConfValueClass(marshalFromGConfValue, marshalToGConfValue)\nrather than\nGConfValueClass, marshalFromGConfValue, marshalToGConfValue\nHaddock will document the classes member functions better. Otherwise they\nget documented as visible members of the class and separately as ordinary top\nlevel exported functions.\n\ndarcs-hash:20060122122524-b4c10-2f8a218bed5b60e270c534df466b85b74119cd97.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_contents":"{-# OPTIONS -fallow-overlapping-instances #-} -- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","old_contents":"{-# OPTIONS -fallow-overlapping-instances #-} -- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass,\n marshalFromGConfValue,\n marshalToGConfValue,\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"4d43e586ee4dc91748106800db7c37c319f8b473","subject":"FIXED: OS X Lion misses CL_PLATFORM_NOT_FOUND_KHR.","message":"FIXED: OS X Lion misses CL_PLATFORM_NOT_FOUND_KHR.\n\nI added a constant definition by hard-coded value\n(since Khronos headers _are_ normative part of definition),\nbut maybe we should rather use headers from include\/ even\nif we link to Apple's version of the library?\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Types.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Types.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 DeriveDataTypeable #-}\nmodule Control.Parallel.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLMemObjectType_, CLMemInfo_, CLImageInfo_, CLMapFlags_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..), CLMapFlag(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLMapFlags_ = {#type cl_map_flags#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n-- -----------------------------------------------------------------------------\n\n-- * NOTE: Apple lags behind official Khronos header files\n#c\nenum CLError {\n#ifdef __APPLE__\n cL_PLATFORM_NOT_FOUND_KHR=-1001,\n#else\n cL_PLATFORM_NOT_FOUND_KHR=CL_PLATFORM_NOT_FOUND_KHR,\n#endif\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_PLATFORM_NOT_FOUND_khr', Returned when no .icd (platform drivers)\n can be properly loaded.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMapFlag {\n cL_MAP_READ=CL_MAP_READ,\n cL_MAP_WRITE=CL_MAP_WRITE\n };\n#endc\n{#enum CLMapFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes =\n\tbitmaskToFlags \n\t\t[CL_DEVICE_TYPE_CPU\n\t\t,CL_DEVICE_TYPE_GPU\n\t\t,CL_DEVICE_TYPE_ACCELERATOR\n\t\t,CL_DEVICE_TYPE_DEFAULT\n\t\t,CL_DEVICE_TYPE_ALL\n\t\t]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\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 DeriveDataTypeable #-}\nmodule Control.Parallel.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLMemObjectType_, CLMemInfo_, CLImageInfo_, CLMapFlags_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..), CLMapFlag(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLMapFlags_ = {#type cl_map_flags#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_PLATFORM_NOT_FOUND_KHR=CL_PLATFORM_NOT_FOUND_KHR,\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_PLATFORM_NOT_FOUND_khr', Returned when no .icd (platform drivers)\n can be properly loaded.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMapFlag {\n cL_MAP_READ=CL_MAP_READ,\n cL_MAP_WRITE=CL_MAP_WRITE\n };\n#endc\n{#enum CLMapFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes =\n\tbitmaskToFlags \n\t\t[CL_DEVICE_TYPE_CPU\n\t\t,CL_DEVICE_TYPE_GPU\n\t\t,CL_DEVICE_TYPE_ACCELERATOR\n\t\t,CL_DEVICE_TYPE_DEFAULT\n\t\t,CL_DEVICE_TYPE_ALL\n\t\t]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6c1775892780ebd5a0e4faa24a0d924dedc70008","subject":"GLDrawingArea: provide implementation for GObjectClass Without this patch, trying to use a GLDrawingArea results in program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject","message":"GLDrawingArea: provide implementation for GObjectClass\nWithout this patch, trying to use a GLDrawingArea results in\n program: gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs:73:0: No instance nor default method for class operation System.Glib.Types.toGObject\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_file":"gtkglext\/Graphics\/UI\/Gtk\/OpenGL\/DrawingArea.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea where\n toGObject (GLDrawingArea gd) = toGObject gd\n unsafeCastGObject = GLDrawingArea . unsafeCastGObject\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) OpenGL Extension: DrawingArea Widget\n--\n-- Author : Duncan Coutts\n--\n-- Created: 9 June 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- \n--\nmodule Graphics.UI.Gtk.OpenGL.DrawingArea (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'DrawingArea'\n-- | +----GLDrawingArea\n-- @\n\n-- * Types\n GLDrawingArea,\n\n-- * Constructors\n glDrawingAreaNew,\n\n-- * Methods\n withGLDrawingArea,\n glDrawingAreaGetGLConfig,\n glDrawingAreaGetGLContext,\n glDrawingAreaGetGLWindow,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.OpenGL.Types#}\nimport Graphics.UI.Gtk.Misc.DrawingArea\t\t(drawingAreaNew)\nimport Graphics.UI.Gtk.OpenGL.Drawable\t\t(glDrawableGLBegin, glDrawableWaitGL, glDrawableGLEnd)\nimport Graphics.UI.Gtk.OpenGL.Window\t\t()\nimport Graphics.UI.Gtk.OpenGL.Context\t\t(GLRenderType(..))\n\n{# context lib=\"gtkglext\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Types\n\nnewtype GLDrawingArea = GLDrawingArea DrawingArea\n\ninstance DrawingAreaClass GLDrawingArea\ninstance WidgetClass GLDrawingArea\ninstance ObjectClass GLDrawingArea\ninstance GObjectClass GLDrawingArea\n\n--------------------\n-- Constructors\n\nglDrawingAreaNew :: GLConfig -> IO GLDrawingArea\nglDrawingAreaNew glconfig = do\n drawingArea <- drawingAreaNew\n widgetSetGLCapability drawingArea glconfig Nothing True RGBAType\n return (GLDrawingArea drawingArea)\n\n\n--------------------\n-- Methods\n\nwithGLDrawingArea :: GLDrawingArea -> (GLWindow -> IO a) -> IO a\nwithGLDrawingArea glDrawingArea glAction = do\n glcontext <- glDrawingAreaGetGLContext glDrawingArea\n glwindow <- glDrawingAreaGetGLWindow glDrawingArea\n glDrawableGLBegin glwindow glcontext\n result <- glAction glwindow\n glDrawableWaitGL glwindow\n glDrawableGLEnd glwindow\n return result\n\n-- | \n--\nglDrawingAreaGetGLConfig :: GLDrawingArea -> IO GLConfig\nglDrawingAreaGetGLConfig (GLDrawingArea widget) =\n makeNewGObject mkGLConfig $\n {# call gtk_widget_get_gl_config #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLContext :: GLDrawingArea -> IO GLContext\nglDrawingAreaGetGLContext (GLDrawingArea widget) =\n makeNewGObject mkGLContext $\n {# call gtk_widget_get_gl_context #}\n (toWidget widget)\n\n-- | \n--\nglDrawingAreaGetGLWindow :: GLDrawingArea -> IO GLWindow\nglDrawingAreaGetGLWindow (GLDrawingArea widget) =\n makeNewGObject mkGLWindow $\n {# call gtk_widget_get_gl_window #}\n (toWidget widget)\n\n-- | \n--\nwidgetSetGLCapability \n :: WidgetClass widget\n => widget\n -> GLConfig\n -> Maybe GLContext\n -> Bool\n -> GLRenderType\n -> IO Bool\nwidgetSetGLCapability widget glconfig shareList direct renderType =\n liftM toBool $\n {# call gtk_widget_set_gl_capability #}\n (toWidget widget)\n (toGLConfig glconfig)\n (maybe (mkGLContext nullForeignPtr) toGLContext shareList)\n (fromBool direct)\n ((fromIntegral . fromEnum) renderType)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"49b2de0b0f3022bac61384d22c557ab49ad6d9e8","subject":"change exception throwing order","message":"change exception throwing order\n\nIgnore-this: c65dd373c9c50d0b67b310a77e6fee4\n- however, the error log may still be inaccessible\n\ndarcs-hash:20091216073039-9241b-3b2ed93f757616ff1cd81486e723766051880b4f.gz\n","repos":"mwu-tow\/cuda,phaazon\/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 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(..), JITResult(..),\n getFun, loadFile, loadData, loadDataEx, unload\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.Exec\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-- 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 where peekMod = liftM Module . peek\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 , useBS* `ByteString' } -> ` Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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 , useBS* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) 2009 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(..), JITResult(..),\n getFun, loadFile, loadData, loadDataEx, unload\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.Exec\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-- 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 where peekMod = liftM Module . peek\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 , useBS* `ByteString' } -> ` Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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 mdl <- resultIfOk =<< 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 return (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 , useBS* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n where\n peekMod = liftM Module . peek\n useBS bs act = B.useAsCString bs $ \\p -> act (castPtr p)\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9c205cf7d6e1393332bb6b3733309f30e4df2dd1","subject":"Pass VisualType to xine_open_video_driver","message":"Pass VisualType to xine_open_video_driver\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(..),\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.\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\npeekEngine = liftM Engine . newForeignPtr_\n\npeekAudioPort = liftM AudioPort . newForeignPtr_\n\npeekVideoPort = liftM VideoPort . newForeignPtr_\n\npeekStream = liftM Stream . newForeignPtr_\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'} -> `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'} -> `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'} -> `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\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\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.\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\npeekEngine = liftM Engine . newForeignPtr_\n\npeekAudioPort = liftM AudioPort . newForeignPtr_\n\npeekVideoPort = liftM VideoPort . newForeignPtr_\n\npeekStream = liftM Stream . newForeignPtr_\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'} -> `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 ,fromIntegral `Int'\n ,withData- `Data'} -> `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'} -> `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\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\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":"c74a92c22720786693463c633705845ccb2d0f9e","subject":"sourceBufferSet\/GetLanguage should pass\/return 'Maybe SourceLanguage'.","message":"sourceBufferSet\/GetLanguage should pass\/return 'Maybe SourceLanguage'.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBuffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n sb \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBuffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBuffer \n -> SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBuffer \n -> IO SourceStyleScheme -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBuffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBuffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n buffer \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n buffer\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n buffer\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBuffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: Signal SourceBuffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: Signal SourceBuffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: Signal SourceBuffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBuffer \n -> SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. The\n-- returned object should not be unreferenced by the user.\nsourceBufferGetLanguage :: SourceBuffer \n -> IO SourceLanguage -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBuffer \n -> SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBuffer \n -> IO SourceStyleScheme -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBuffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBuffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n buffer \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n buffer\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n buffer\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBuffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: Signal SourceBuffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: Signal SourceBuffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: Signal SourceBuffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"84ca5bb694e0a8d7a05512814c6141414e9592da","subject":"gstreamer: M.S.G.Core.Element: document everything, use new signal types","message":"gstreamer: M.S.G.Core.Element: document everything, use new signal types","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Element.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 pipeline elements.\nmodule Media.Streaming.GStreamer.Core.Element (\n\n-- * Detail\n\n -- | 'Element' is the abstract base class needed to construct an\n -- element that can be used in a GStreamer pipeline.\n -- \n -- All elements have pads (of the type 'Pad'). These pads link to\n -- pads on other elements. 'Buffer's flow between these linked\n -- pads. An 'Element' has a 'Pad' for each input (or sink) and\n -- output (or source).\n -- \n -- An element's pad can be retrieved by name with\n -- 'elementGetStaticPad' or 'elementGetRequestPad'. An 'Iterator'\n -- over all an element's pads can be retrieved with\n -- 'elementIteratePads'.\n -- \n -- Elements can be linked through their pads. If the link is\n -- straightforward, use the 'elementLink' convenience function to\n -- link two elements. Use 'elementLinkFiltered' to link two\n -- elements constrained by a specified set of 'Caps'. For finer\n -- control, use 'elementLinkPads' and 'elementLinkPadsFiltered' to\n -- specify the pads to link on each element by name.\n -- \n -- Each element has a 'State'. You can get and set the state of an\n -- element with 'elementGetState' and 'elementSetState'. To get a\n -- string representation of a 'State', use 'elementStateGetName'.\n -- \n -- You can get and set a 'Clock' on an element using\n -- 'elementGetClock' and 'elementSetClock'. Some elements can\n -- provide a clock for the pipeline if 'elementProvidesClock'\n -- returns 'True'. With the 'elementProvideClock' method one can\n -- retrieve the clock provided by such an element. Not all\n -- elements require a clock to operate correctly. If\n -- 'elementRequiresClock' returns 'True', a clock should be set on\n -- the element with 'elementSetClock'.\n -- \n -- Note that clock slection and distribution is normally handled\n -- by the toplevel 'Pipeline' so the clock functions should only\n -- be used in very specific situations.\n\n-- * Types \n Element,\n ElementClass,\n castToElement,\n toElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n\n-- * Element Operations\n elementAddPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n elementNoMorePads,\n elementPadAdded,\n elementPadRemoved,\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on the element.\nelementGetFlags :: ElementClass elementT\n => elementT\n -> IO [ElementFlags]\nelementGetFlags = mkObjectGetFlags\n\n-- | Set the given flags on the element.\nelementSetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementSetFlags = mkObjectSetFlags\n\n-- | Unset the given flags on the element.\nelementUnsetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementUnsetFlags = mkObjectUnsetFlags\n\n-- | Add a pad (link point) to an element. The pad's parent will be set to\n-- @element@.\n-- \n-- Pads are not automatically activated so elements should perform\n-- the needed steps to activate the pad in case this pad is added in\n-- the 'StatePaused' or 'StatePlaying' state. See 'padSetActive' for\n-- more information about activating pads.\n-- \n-- This function will emit the 'elementPadAdded' signal on the\n-- element.\nelementAddPad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\n-- | Look for an unlinked pad to which the given pad can link. It is not\n-- guaranteed that linking the pads will work, though it should work in most\n-- cases.\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - the element for\n -- which a pad should be found\n -> padT -- ^ @pad@ - the pad to find\n -- a compatible one for\n -> Caps -- ^ @caps@ - the 'Caps' to\n -- use as a filter\n -> IO (Maybe Pad) -- ^ the compatible 'Pad', or\n -- 'Nothing' if none was found\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek takeObject\n\n-- | Retrieve a pad template from @element@ that is compatible with\n-- @padTemplate@. Pads from compatible templates can be linked\n-- together.\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT)\n => elementT -- ^ @element@ - \n -> padTemplateT -- ^ @padTemplate@ - \n -> IO (Maybe PadTemplate) -- ^ the compatible'PadTemplate',\n -- or 'Nothing' if none was found\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek takeObject\n\n-- | Retrieve a pad from the element by name. This version only\n-- retrieves request pads. The pad should be released with\n-- 'elementReleaseRequestPad'.\nelementGetRequestPad :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> String -- ^ @name@ - \n -> IO (Maybe Pad) -- ^ the requested 'Pad' if\n -- found, otherwise 'Nothing'.\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek peekObject\n\n-- | Retreive a pad from @element@ by name. This version only\n-- retrieves already-existing (i.e. \"static\") pads.\nelementGetStaticPad :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> String -- ^ @name@ - \n -> IO (Maybe Pad) -- ^ the requested 'Pad' if\n -- found, otherwise 'Nothing'.\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek takeObject\n\n-- | Release a request pad that was previously obtained with\n-- 'elementGetRequestPad'.\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\n-- | Remove @pad@ from @element@.\n-- \n-- This function is used by plugin developers and should not be used\n-- by applications. Pads that were dynamically requested from\n-- elements with 'elementGetRequestPad' should be released with the\n-- 'elementReleaseRequestPad' function instead.\n-- \n-- Pads are not automatically deactivated so elements should perform the needed\n-- steps to deactivate the pad in case this pad is removed in the PAUSED or\n-- PLAYING state. See 'padSetActive' for more information about\n-- deactivating pads.\n-- \n-- The pad and the element should be unlocked when calling this function.\n-- \n-- This function will emit the 'padRemoved' signal on the element.\n-- \n-- Returns: 'True' if the pad could be removed. Can return 'False' if the\n-- pad does not belong to the provided element.\nelementRemovePad :: (ElementClass elementT, PadClass padT)\n => elementT -- ^ @element@ - \n -> padT -- ^ @pad@ - \n -> IO Bool -- ^ 'True' if the pad was succcessfully\n -- removed, otherwise 'False'\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\n-- | Retrieve an 'Iterator' over @element@'s pads.\nelementIteratePads :: (ElementClass elementT)\n => elementT -- ^ @element@ - \n -> IO (Iterator Pad) -- ^ an iterator over the element's pads.\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= takeIterator\n\n\n-- | Retrieve an 'Iterator' over @element@'s sink pads.\nelementIterateSinkPads :: (ElementClass elementT)\n => elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\n-- | Retrieve an 'Iterator' over @element@'s src pads.\nelementIterateSrcPads :: (ElementClass elementT)\n => elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\n-- | Link @src@ to @sink@. The link must be from source to\n-- sink; the other direction will not be tried. The function\n-- looks for existing pads that aren't linked yet. It will request\n-- new pads if necessary. Such pads must be released manually (with\n-- 'elementReleaseRequestPad') when unlinking. If multiple links are\n-- possible, only one is established.\n-- \n-- Make sure you have added your elements to a 'Bin' or 'Pipeline'\n-- with 'binAdd' before trying to link them.\nelementLink :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> sinkT -- ^ @sink@ - \n -> IO Bool -- ^ 'True' if the pads could be linked,\n -- otherwise 'False'\nelementLink src sink =\n liftM toBool $ {# call element_link #} (toElement src) (toElement sink)\n\n-- | Unlink all source pads of the @src@ from all sink pads of the\n-- @sink@.\nelementUnlink :: (ElementClass srcT, ElementClass sinkT)\n => srcT\n -> sinkT\n -> IO ()\nelementUnlink src sink =\n {# call element_unlink #} (toElement src) (toElement sink)\n\n-- | Link the named pads of @src@ and @sink@.\nelementLinkPads :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - the element containing the source pad\n -> Maybe String -- ^ @srcPadName@ - the name of the source pad, or 'Nothing' for any pad\n -> sinkT -- ^ @sink@ - the element containing the sink pad\n -> Maybe String -- ^ @sinkPadName@ - the name of the sink pad, or 'Nothing' for any pad\n -> IO Bool -- ^ 'True' if the pads could be linked, otherwise 'False'\nelementLinkPads src srcPadName sink sinkPadName =\n maybeWith withUTFString sinkPadName $ \\cSinkPadName ->\n maybeWith withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement sink) cSinkPadName\n\n-- | Unlink the named pads of @src@ and @sink@.\nelementUnlinkPads :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> String -- ^ @srcPadName@ - \n -> sinkT -- ^ @sink@ - \n -> String -- ^ @sinkPadName@ - \n -> IO ()\nelementUnlinkPads src srcPadName sink sinkPadName =\n withUTFString sinkPadName $ \\cSinkPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement sink) cSinkPadName\n\n-- | Link the named pads of @src@ and @sink@. A side effect is that if\n-- one of the pads has no parent, it becomes a child of the parent\n-- of the other element. If they have different parents, the link\n-- will fail. If @caps@ is not 'Nothing', make sure that the 'Caps'\n-- of the link is a subset of @caps@.\nelementLinkPadsFiltered :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> Maybe String -- ^ @srcPadName@ - \n -> sinkT -- ^ @sink@ - \n -> Maybe String -- ^ @sinkPadName@ - \n -> Caps -- ^ @caps@ - \n -> IO Bool -- ^ 'True' if the pads could be\n -- linked, otherwise 'False'\nelementLinkPadsFiltered src srcPadName sink sinkPadName filter =\n maybeWith withUTFString sinkPadName $ \\cSinkPadName ->\n maybeWith withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement sink) cSinkPadName filter\n\n-- | Link @src@ to @dest@ using the given 'Caps' as a filter. The link\n-- must be from source to sink; the other direction will not be\n-- tried. The function looks for existing pads that aren't linked\n-- yet. If will request new pads if necessary. If multiple links are\n-- possible, only one is established.\n-- \n-- Make sure you have added your elements to a 'Bin' or 'Pipeline'\n-- with 'binAdd' before trying to link them.\nelementLinkFiltered :: (ElementClass srcT, ElementClass sinkT)\n => srcT -- ^ @src@ - \n -> sinkT -- ^ @sink@ - \n -> Maybe Caps -- ^ @caps@ - \n -> IO Bool -- ^ 'True' if the pads could be\n -- linked, otherwise 'False'\nelementLinkFiltered src sink filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement src) (toElement sink) $\n fromMaybe (Caps nullForeignPtr) filter\n\n-- | Set the base time of @element@. See 'elementGetBaseTime' for more\n-- information.\nelementSetBaseTime :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> ClockTimeDiff -- ^ @time@ - \n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\n-- | Return the base time of @element@. The base time is the absolute\n-- time of the clock when this element was last set to\n-- 'StatePlaying'. Subtract the base time from the clock time to get\n-- the stream time of the element.\nelementGetBaseTime :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ClockTimeDiff -- ^ the base time of the element\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\n-- | Set the 'Bus' used by @element@. For internal use only, unless\n-- you're testing elements.\nelementSetBus :: (ElementClass elementT, BusClass busT)\n => elementT -- ^ @element@ - \n -> busT -- ^ @bus@ - \n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\n-- | Get the bus of @element@. Not that only a 'Pipeline' will\n-- provide a bus for the application.\nelementGetBus :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bus -- ^ the bus used by the element\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= takeObject\n\n-- | Get the factory used to create @element@.\nelementGetFactory :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ElementFactory -- ^ the factory that created @element@\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= peekObject\n\n-- | Set the 'Index' used by @element@.\nelementSetIndex :: (ElementClass elementT, IndexClass indexT)\n => elementT -- ^ @element@ - \n -> indexT -- ^ @index@ - \n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\n-- | Get the 'Index' used by @element@.\nelementGetIndex :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Index) -- ^ the index, or 'Nothing' if @element@ has none\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek takeObject\n\n-- | Determine whether @element@ can be indexed.\nelementIsIndexable :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element can be indexed\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\n-- | Determine whether @element@ requires a clock.\nelementRequiresClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element requires a clock\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\n-- | Set the 'Clock' used by @element@.\nelementSetClock :: (ElementClass elementT, ClockClass clockT)\n => elementT -- ^ @element@ - \n -> clockT -- ^ @clock@ - \n -> IO Bool -- ^ 'True' if the element accepted the clock\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\n-- | Get the 'Clock' used by @element@.\nelementGetClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Clock) -- ^ the clock, or 'Nothing' if @element@ has none\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek takeObject\n\n-- | Determine whether @element@ provides a clock. A 'Clock' provided\n-- by an element can be used as the global clock for a pipeline. An\n-- element that can provide a clock is only required to do so in the\n-- 'StatePaused' state, meaning that it is fully negotiated and has\n-- allocated the resources needed to operate the clock.\nelementProvidesClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element provides a clock\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\n-- | Get the 'Clock' provided by @element@.\n-- \n-- Note that an element is only required to provide a clock in the\n-- 'StatePaused' state. Some elements can provide a clock in other\n-- states.\nelementProvideClock :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO (Maybe Clock) -- ^ a 'Clock', or 'Nothing' if\n -- none could be provided\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek takeObject\n\n-- | Set the state of @element@ to @state@. This function will try to\n-- set the requested state by going through all the intermediary\n-- states and calling the class's state change function for each.\n-- \n-- This function can return 'StateChangeAsync', in which case the\n-- element will perform the remainder of the state change\n-- asynchronously in another thread. An application can use\n-- 'elementGetState' to wait for the completion of the state change\n-- or it can wait for a state change message on the bus.\nelementSetState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> State -- ^ @state@ - \n -> IO StateChangeReturn -- ^ the result of the state change\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\n-- | Get the state of @element@.\n-- \n-- For elements that performed an asynchronous state change, as\n-- reported by 'elementSetState', this function will block up to the\n-- specified timeout value for the state change to complete. If the\n-- element completes the state change or goes into an error, this\n-- function returns immediately with a return value of\n-- 'StateChangeSuccess' or 'StateChangeFailure', respectively.\n-- \n-- This function returns 'StateChangeNoPreroll' if the element\n-- successfully changed its state but is not able to provide data\n-- yet. This mostly happens for live sources that not only produce\n-- data in the 'StatePlaying' state. While the state change return\n-- is equivalent to 'StateChangeSuccess', it is returned to the\n-- application to signal that some sink elements might not be able\n-- to somplete their state change because an element is not\n-- producing data to complete the preroll. When setting the element\n-- to playing, the preroll will complete and playback will start.\nelementGetState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> ClockTime -- ^ @timeout@ - \n -> IO (StateChangeReturn, Maybe State, Maybe State)\n -- ^ the result of the state change, the current\n -- state, and the pending state\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do poke statePtr (-1) -- -1 is not use by any enum value\n poke pendingPtr (-1)\n result <- {# call element_get_state #} (toElement element)\n statePtr\n pendingPtr\n (fromIntegral timeout)\n state <- unmarshalState statePtr\n pending <- unmarshalState pendingPtr\n return (toEnum $ fromIntegral result, state, pending)\n where unmarshalState statePtr = do\n cState <- peek statePtr\n if cState \/= -1\n then return $ Just $ toEnum $ fromIntegral cState\n else return Nothing\n\n-- | Lock the state of @element@, so state changes in the parent don't\n-- affect this element any longer.\nelementSetLockedState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> Bool -- ^ @lockedState@ - 'True' for locked, 'False' for unlocked\n -> IO Bool -- ^ 'True' if the state was changed, 'False' if bad\n -- parameters were given or no change was needed\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\n-- | Determine whether @element@'s state is locked.\nelementIsLockedState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if @element@'s state is locked, 'False' otherwise\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\n-- | Abort @element@'s state change. This function is used by elements\n-- that do asynchronous state changes and find out something is wrong.\n-- \n-- This function should be called with the state lock held.\nelementAbortState :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\n-- | Get a string representation of @state@.\nelementStateGetName :: State -- ^ @state@ - \n -> String -- ^ the name of @state@\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\n-- | Get a string representation of @stateRet@.\nelementStateChangeReturnGetName :: StateChangeReturn -- ^ @stateRet@ - \n -> String -- ^ the name of @stateRet@\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\n-- | Try to change the state of @element@ to the same as its\n-- parent. If this function returns 'False', the state of the\n-- element is undefined.\nelementSyncStateWithParent :: ElementClass elementT\n => elementT -- ^ @element@ - \n -> IO Bool -- ^ 'True' if the element's state could be\n -- synced with its parent's state\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\n-- | Perform a query on the given element.\n-- \n-- For elements that don't implement a query handler, this function\n-- forwards the query to a random srcpad or to the peer of a random\n-- linked sinkpad of this element.\nelementQuery :: (ElementClass element, QueryClass query)\n => element -- ^ @element@ - \n -> query -- ^ @query@ - \n -> IO Bool -- ^ 'True' if the query could be performed\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n fmap toBool $ {# call element_query #} (toElement element) $ Query query'\n\n-- | Query an element for the convertion of a value from one format to\n-- another.\nelementQueryConvert :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @srcFormat@ - the format to convert from\n -> Int64 -- ^ @srcVal@ - the value to convert\n -> Format -- ^ @destFormat@ - the format to convert to\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryConvert element srcFormat srcVal destFormat =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do poke destFormatPtr $ fromIntegral $ fromEnum destFormat\n success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\n-- | Query an element for its stream position.\nelementQueryPosition :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @format@ - the format requested\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryPosition element format =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\n-- | Query an element for its stream duration.\nelementQueryDuration :: ElementClass element\n => element -- ^ @element@ - the element to query\n -> Format -- ^ @format@ - the format requested\n -> IO (Maybe (Format, Word64)) -- ^ the resulting format and value\nelementQueryDuration element format =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\n-- | Send an event to an element.\n-- \n-- If the element doesn't implement an event handler, the event will\n-- be pushed to a random linked sink pad for upstream events or a\n-- random linked source pad for downstream events.\nelementSendEvent :: (ElementClass element, EventClass event)\n => element -- ^ @element@ - the element to send the event to\n -> event -- ^ @event@ - the event to send\n -> IO Bool -- ^ 'True' if the event was handled\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\n-- | Perform a seek on the given element. This function only supports\n-- seeking to a position relative to the start of the stream. For\n-- more complex operations like segment seeks (such as for looping),\n-- or changing the playback rate, or seeking relative to the last\n-- configured playback segment you should use 'elementSeek'.\n-- \n-- In a completely prerolled pipeline in the 'StatePaused' or\n-- 'StatePlaying' states, seeking is always guaranteed to return\n-- 'True' on a seekable media type, or 'False' when the media type\n-- is certainly not seekable (such as a live stream).\n-- \n-- Some elements allow for seeking in the 'StateReady' state, in\n-- which case they will store the seek event and execute it when\n-- they are put into the 'StatePaused' state. If the element\n-- supports seek in \"StateReady\", it will always return 'True' when\n-- it recieves the event in the 'StateReady' state.\nelementSeekSimple :: ElementClass element\n => element -- ^ @element@ - the element to seek on\n -> Format -- ^ @format@ - the 'Format' to evecute the seek in,\n -- such as 'FormatTime'\n -> [SeekFlags] -- ^ @seekFlags@ - seek options; playback applications\n -- will usually want to use\n -- @['SeekFlagFlush','SeekFlagKeyUnit']@\n -> Int64 -- ^ @seekPos@ - the position to seek to, relative to\n -- start; if you are doing a seek in\n -- 'FormatTime' this value is in nanoseconds;\n -- see 'second', 'msecond', 'usecond', &\n -- 'nsecond'\n -> IO Bool -- ^ 'True' if the seek operation succeeded\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\n-- | Send a seek event to an element. See\n-- 'Media.Streaming.GStreamer.Core.Event.eventNewSeek' for the\n-- details of the parameters. The seek event is sent to the element\n-- using 'elementSendEvent'.\nelementSeek :: ElementClass element\n => element -- ^ @element@ - the element to seek on\n -> Double -- ^ @rate@ - the new playback rate\n -> Format -- ^ @format@ - the format of the seek values\n -> [SeekFlags] -- ^ @seekFlags@ - the options to use\n -> SeekType -- ^ @curType@ - type and flags for the new current position\n -> Int64 -- ^ @cur@ - the value of the new current position\n -> SeekType -- ^ @stopType@ - type and flags for the new stop position\n -> Int64 -- ^ @stop@ - the value of the new stop position\n -> IO Bool -- ^ 'True' if the event was handled\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\n-- | The signal emitted when an element will not generate more dynamic\n-- pads.\nelementNoMorePads :: (ElementClass element)\n => Signal element (IO ())\nelementNoMorePads =\n Signal $ connect_NONE__NONE \"no-more-pads\"\n\n-- | The signal emitted when a new 'Pad' has been added to the\n-- element.\nelementPadAdded :: (ElementClass element)\n => Signal element (Pad -> IO ())\nelementPadAdded =\n Signal $ connect_OBJECT__NONE \"pad-added\"\n\n-- | The signal emitted when a 'Pad' has been removed from the\n-- element.\nelementPadRemoved :: (ElementClass element)\n => Signal element (Pad -> IO ())\nelementPadRemoved =\n Signal $ connect_OBJECT__NONE \"pad-removed\"\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.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementGetFlags :: ElementClass elementT\n => elementT\n -> IO [ElementFlags]\nelementGetFlags = mkObjectGetFlags\n\nelementSetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementSetFlags = mkObjectSetFlags\n\nelementUnsetFlags :: ElementClass elementT\n => elementT\n -> [ElementFlags]\n -> IO ()\nelementUnsetFlags = mkObjectUnsetFlags\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek takeObject\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek takeObject\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek takeObject\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek peekObject\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek takeObject\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= takeIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= takeIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= takeObject\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= peekObject\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek takeObject\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek takeObject\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek takeObject\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM Just $ withForeignPtr query' $ takeMiniObject . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Word64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> Format\n -> IO (Maybe (Format, Word64))\nelementQueryPosition element format =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> Format\n -> IO (Maybe (Format, Word64))\nelementQueryDuration element format =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum format\n success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b1b4709009f661b838a4a2c83d5442ecc9a1a1ec","subject":"remove special-casing of ruby 1.9","message":"remove special-casing of ruby 1.9\n","repos":"mwotton\/Hubris-Haskell,mwotton\/Hubris-Haskell,mwotton\/Hubris-Haskell","old_file":"Language\/Ruby\/Hubris\/Binding.chs","new_file":"Language\/Ruby\/Hubris\/Binding.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, TypeSynonymInstances #-}\n\n{- TODO\n\nRip the array trnaslation stuff out to a utility function. same with hashes.\n\ninstall as package. This is a bit iffy for GHC\/JHC compatibility - if we commit to\nCabal, that leaves JHC out in the cold.\n\nperhaps need cabal file for ghc and equivalent for jhc.\n\nalso: do we want to support different versions of ruby? for the moment, you just get\nwhichever ruby.h is first in the search place.\n\n-}\n\n\nmodule Language.Ruby.Hubris.Binding where\n#include \"rshim.h\"\n#include \n\nimport Control.Applicative\n-- import Control.Monad\nimport Data.Word\n-- import Foreign.Ptr\nimport Foreign.C.Types\t\nimport Foreign.C.String\n-- import Foreign.Storable\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- import Foreign.Marshal.Array\n\n{# context lib=\"rshim\" #}\n\n{# enum RubyType {} deriving (Eq, Show) #} -- maybe Ord?\nrubyType :: Value -> RubyType\nrubyType = toEnum . rtype\n\nconstToRuby :: RubyConst -> Value\nconstToRuby = fromIntegral . fromEnum \n-- RUBY_VERSION_CODE <= 187\ndata RubyConst = RUBY_Qfalse \n | RUBY_Qtrue \n | RUBY_Qnil \n | RUBY_Qundef \n\ninstance Enum RubyConst where\n fromEnum RUBY_Qfalse = 0\n fromEnum RUBY_Qtrue = 2\n fromEnum RUBY_Qnil = 4\n fromEnum RUBY_Qundef = 6\n\n toEnum 0 = RUBY_Qfalse\n toEnum 2 = RUBY_Qtrue\n toEnum 4 = RUBY_Qnil\n toEnum 6 = RUBY_Qundef\n toEnum 12 = RUBY_Qnil\n-- {# enum ruby_special_consts as RubyConst {} deriving (Eq,Show) #}\n\nstr2cstr str = rb_str2cstr str 0\ntype Value = CULong -- FIXME, we'd prefer to import the type VALUE directly\nforeign import ccall safe \"ruby.h rb_str2cstr\" rb_str2cstr :: Value -> CInt -> IO CString\nforeign import ccall safe \"ruby.h rb_str_new2\" rb_str_new2 :: CString -> IO Value\nforeign import ccall safe \"ruby.h rb_str_new2\" rb_str_new_ :: CString -> Int -> IO Value \nforeign import ccall safe \"ruby.h rb_ary_new2\" rb_ary_new2 :: CLong -> IO Value\nforeign import ccall safe \"ruby.h rb_ary_push\" rb_ary_push :: Value -> Value -> IO ()\nforeign import ccall safe \"ruby.h rb_float_new\" rb_float_new :: Double -> Value\nforeign import ccall safe \"ruby.h rb_big2str\" rb_big2str :: Value -> Int -> IO Value\nforeign import ccall safe \"ruby.h rb_str_to_inum\" rb_str_to_inum :: Value -> Int -> Int -> Value\n-- foreign import ccall safe \"ruby.h ruby_init\" ruby_init :: IO ()\n\nrb_str_new = uncurry rb_str_new_\n\n-- we're being a bit filthy here - the interface is all macros, so we're digging in to find what it actually is\nforeign import ccall safe \"rshim.h rb_ary_len\" rb_ary_len :: Value -> CUInt\nforeign import ccall safe \"rshim.h rtype\" rtype :: Value -> Int\n\nforeign import ccall safe \"rshim.h int2fix\" int2fix :: Int -> Value\nforeign import ccall safe \"rshim.h fix2int\" fix2int :: Value -> Int\nforeign import ccall safe \"rshim.h num2dbl\" num2dbl :: Value -> Double -- technically CDoubles, but jhc promises they're the same\nforeign import ccall safe \"rshim.h keys\" rb_keys :: Value -> IO Value\nforeign import ccall safe \"rshim.h buildException\" buildException :: CString -> IO Value\n-- foreign import ccall safe \"ruby.h rb_funcall\" rb_funcall :: Value -> ID ->\n\n-- this line crashes jhc\nforeign import ccall safe \"intern.h rb_ary_entry\" rb_ary_entry :: Value -> CLong -> IO Value\n\nforeign import ccall safe \"ruby.h rb_raise\" rb_raise :: Value -> CString -> IO ()\nforeign import ccall safe \"ruby.h rb_eval_string\" rb_eval_string :: CString -> IO Value\n\nforeign import ccall safe \"intern.h rb_hash_aset\" rb_hash_aset :: Value -> Value -> Value -> IO ()\nforeign import ccall safe \"intern.h rb_hash_new\" rb_hash_new :: IO Value\nforeign import ccall safe \"intern.h rb_hash_aref\" rb_hash_aref :: Value -> Value -> IO Value\n\n\ncreateException :: String -> IO Value\ncreateException s = newCAString s >>= buildException -- (\"puts HaskellError.methods(); HaskellError.new\") >>= rb_eval_string\n\n\n\n-- data RValue = T_NIL \n-- | T_FLOAT Double\n-- | T_STRING Value\n\n-- -- List is non-ideal. Switch to uvector? Array? There's always going\n-- -- to be an extraction step to pull the RValues out.\n-- | T_ARRAY [RValue]\n-- | T_FIXNUM Int \n-- | T_HASH Value -- Int -- definitely FIXME - native ruby hashes, or going to transliterate into Data.Map?\n-- | T_BIGNUM Integer \n\n-- -- technically, these are mapping over the types True and False,\n-- -- I'm going to treat them as values, though.\n-- | T_TRUE \n-- | T_FALSE \n-- | T_OBJECT Value\n-- | T_CLASS Value\n-- -- | T_EXCEPTION String\n-- | T_SYMBOL Word -- interned string\n-- deriving (Eq, Show)\n-- These are the other basic Ruby structures that we're not handling yet.\n-- | T_REGEXP \n-- | T_FILE\n-- | T_STRUCT \n-- | T_DATA \n\n\n-- | T_MODULE \n-- -- leaky as hell\n-- fromRVal :: RValue -> Value\n-- fromRVal r = case r of\n-- T_FLOAT d -> rb_float_new d\n-- -- need to take the address of the cstr, just cast it to a value\n-- -- sadly no bytestrings yet - unpack it to a list. yeah it's ugly.\n-- T_STRING str -> str -- unsafePerformIO $ newCAString str >>= rb_str_new2\n-- T_FIXNUM i -> int2fix i\n\n-- -- so this is just bizarre - there's no boolean type. True and False have their own types\n-- -- as well as their own values.\n-- T_TRUE -> constToRuby RUBY_Qtrue\n-- T_FALSE -> constToRuby RUBY_Qfalse\n-- T_NIL -> constToRuby RUBY_Qnil\n-- T_HASH h -> h\n-- T_ARRAY l -> unsafePerformIO $ do\n-- ary <- rb_ary_new2 $ fromIntegral $ length l\n-- mapM_ (rb_ary_push ary . fromRVal) l\n-- return ary\n-- T_OBJECT v -> v\n-- -- T_CLASS v -> v\n-- T_BIGNUM b -> rb_str_to_inum (unsafePerformIO $ (newCAString $ show b) >>= rb_str_new2) 10 1\n-- _ -> error \"sorry, haven't implemented that yet.\"\n\n\n\n-- fromVal :: Value -> RValue\n-- fromVal v = case target of\n-- RT_NIL -> T_NIL\n-- RT_FIXNUM -> T_FIXNUM $ fix2int v\n-- RT_STRING -> T_STRING v -- $ unsafePerformIO $ str2cstr >>= peekCString \n-- RT_FLOAT -> T_FLOAT $ num2dbl v\n-- RT_BIGNUM -> T_BIGNUM $ read $ unsafePerformIO (rb_big2str v 10 >>= str2cstr >>= peekCString)\n-- RT_TRUE -> T_TRUE\n-- RT_FALSE -> T_FALSE\n-- RT_HASH -> T_HASH v\n-- RT_ARRAY -> T_ARRAY $ map fromVal $ unsafePerformIO $ mapM (rb_ary_entry v . fromIntegral) [0..(rb_ary_len v) - 1]\n-- RT_OBJECT -> T_OBJECT v\n-- -- RT_CLASS -> T_CLASS v\n-- _ -> error (\"didn't work: \" ++ show target)\n-- where target :: RubyType\n-- target = toEnum $ rtype v\n\n\n\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, TypeSynonymInstances #-}\n\n{- TODO\n\nRip the array trnaslation stuff out to a utility function. same with hashes.\n\ninstall as package. This is a bit iffy for GHC\/JHC compatibility - if we commit to\nCabal, that leaves JHC out in the cold.\n\nperhaps need cabal file for ghc and equivalent for jhc.\n\nalso: do we want to support different versions of ruby? for the moment, you just get\nwhichever ruby.h is first in the search place.\n\n-}\n\n\nmodule Language.Ruby.Hubris.Binding where\n#include \"rshim.h\"\n#include \n\nimport Control.Applicative\n-- import Control.Monad\nimport Data.Word\n-- import Foreign.Ptr\nimport Foreign.C.Types\t\nimport Foreign.C.String\n-- import Foreign.Storable\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- import Foreign.Marshal.Array\n\n{# context lib=\"rshim\" #}\n\n{# enum RubyType {} deriving (Eq, Show) #} -- maybe Ord?\nrubyType :: Value -> RubyType\nrubyType = toEnum . rtype\n\nconstToRuby :: RubyConst -> Value\nconstToRuby = fromIntegral . fromEnum \n-- RUBY_VERSION_CODE <= 187\n#if 0\ndata RubyConst = RUBY_Qfalse \n | RUBY_Qtrue \n | RUBY_Qnil \n | RUBY_Qundef \n\ninstance Enum RubyConst where\n fromEnum RUBY_Qfalse = 0\n fromEnum RUBY_Qtrue = 2\n fromEnum RUBY_Qnil = 4\n fromEnum RUBY_Qundef = 6\n\n toEnum 0 = RUBY_Qfalse\n toEnum 2 = RUBY_Qtrue\n toEnum 4 = RUBY_Qnil\n toEnum 6 = RUBY_Qundef\n toEnum 12 = RUBY_Qnil\n#else\n{# enum ruby_special_consts as RubyConst {} deriving (Eq,Show) #}\n#endif\n\nstr2cstr str = rb_str2cstr str 0\ntype Value = CULong -- FIXME, we'd prefer to import the type VALUE directly\nforeign import ccall safe \"ruby.h rb_str2cstr\" rb_str2cstr :: Value -> CInt -> IO CString\nforeign import ccall safe \"ruby.h rb_str_new2\" rb_str_new2 :: CString -> IO Value\nforeign import ccall safe \"ruby.h rb_str_new2\" rb_str_new_ :: CString -> Int -> IO Value \nforeign import ccall safe \"ruby.h rb_ary_new2\" rb_ary_new2 :: CLong -> IO Value\nforeign import ccall safe \"ruby.h rb_ary_push\" rb_ary_push :: Value -> Value -> IO ()\nforeign import ccall safe \"ruby.h rb_float_new\" rb_float_new :: Double -> Value\nforeign import ccall safe \"ruby.h rb_big2str\" rb_big2str :: Value -> Int -> IO Value\nforeign import ccall safe \"ruby.h rb_str_to_inum\" rb_str_to_inum :: Value -> Int -> Int -> Value\n-- foreign import ccall safe \"ruby.h ruby_init\" ruby_init :: IO ()\n\nrb_str_new = uncurry rb_str_new_\n\n-- we're being a bit filthy here - the interface is all macros, so we're digging in to find what it actually is\nforeign import ccall safe \"rshim.h rb_ary_len\" rb_ary_len :: Value -> CUInt\nforeign import ccall safe \"rshim.h rtype\" rtype :: Value -> Int\n\nforeign import ccall safe \"rshim.h int2fix\" int2fix :: Int -> Value\nforeign import ccall safe \"rshim.h fix2int\" fix2int :: Value -> Int\nforeign import ccall safe \"rshim.h num2dbl\" num2dbl :: Value -> Double -- technically CDoubles, but jhc promises they're the same\nforeign import ccall safe \"rshim.h keys\" rb_keys :: Value -> IO Value\nforeign import ccall safe \"rshim.h buildException\" buildException :: CString -> IO Value\n-- foreign import ccall safe \"ruby.h rb_funcall\" rb_funcall :: Value -> ID ->\n\n-- this line crashes jhc\nforeign import ccall safe \"intern.h rb_ary_entry\" rb_ary_entry :: Value -> CLong -> IO Value\n\nforeign import ccall safe \"ruby.h rb_raise\" rb_raise :: Value -> CString -> IO ()\nforeign import ccall safe \"ruby.h rb_eval_string\" rb_eval_string :: CString -> IO Value\n\nforeign import ccall safe \"intern.h rb_hash_aset\" rb_hash_aset :: Value -> Value -> Value -> IO ()\nforeign import ccall safe \"intern.h rb_hash_new\" rb_hash_new :: IO Value\nforeign import ccall safe \"intern.h rb_hash_aref\" rb_hash_aref :: Value -> Value -> IO Value\n\n\ncreateException :: String -> IO Value\ncreateException s = newCAString s >>= buildException -- (\"puts HaskellError.methods(); HaskellError.new\") >>= rb_eval_string\n\n\n\n-- data RValue = T_NIL \n-- | T_FLOAT Double\n-- | T_STRING Value\n\n-- -- List is non-ideal. Switch to uvector? Array? There's always going\n-- -- to be an extraction step to pull the RValues out.\n-- | T_ARRAY [RValue]\n-- | T_FIXNUM Int \n-- | T_HASH Value -- Int -- definitely FIXME - native ruby hashes, or going to transliterate into Data.Map?\n-- | T_BIGNUM Integer \n\n-- -- technically, these are mapping over the types True and False,\n-- -- I'm going to treat them as values, though.\n-- | T_TRUE \n-- | T_FALSE \n-- | T_OBJECT Value\n-- | T_CLASS Value\n-- -- | T_EXCEPTION String\n-- | T_SYMBOL Word -- interned string\n-- deriving (Eq, Show)\n-- These are the other basic Ruby structures that we're not handling yet.\n-- | T_REGEXP \n-- | T_FILE\n-- | T_STRUCT \n-- | T_DATA \n\n\n-- | T_MODULE \n-- -- leaky as hell\n-- fromRVal :: RValue -> Value\n-- fromRVal r = case r of\n-- T_FLOAT d -> rb_float_new d\n-- -- need to take the address of the cstr, just cast it to a value\n-- -- sadly no bytestrings yet - unpack it to a list. yeah it's ugly.\n-- T_STRING str -> str -- unsafePerformIO $ newCAString str >>= rb_str_new2\n-- T_FIXNUM i -> int2fix i\n\n-- -- so this is just bizarre - there's no boolean type. True and False have their own types\n-- -- as well as their own values.\n-- T_TRUE -> constToRuby RUBY_Qtrue\n-- T_FALSE -> constToRuby RUBY_Qfalse\n-- T_NIL -> constToRuby RUBY_Qnil\n-- T_HASH h -> h\n-- T_ARRAY l -> unsafePerformIO $ do\n-- ary <- rb_ary_new2 $ fromIntegral $ length l\n-- mapM_ (rb_ary_push ary . fromRVal) l\n-- return ary\n-- T_OBJECT v -> v\n-- -- T_CLASS v -> v\n-- T_BIGNUM b -> rb_str_to_inum (unsafePerformIO $ (newCAString $ show b) >>= rb_str_new2) 10 1\n-- _ -> error \"sorry, haven't implemented that yet.\"\n\n\n\n-- fromVal :: Value -> RValue\n-- fromVal v = case target of\n-- RT_NIL -> T_NIL\n-- RT_FIXNUM -> T_FIXNUM $ fix2int v\n-- RT_STRING -> T_STRING v -- $ unsafePerformIO $ str2cstr >>= peekCString \n-- RT_FLOAT -> T_FLOAT $ num2dbl v\n-- RT_BIGNUM -> T_BIGNUM $ read $ unsafePerformIO (rb_big2str v 10 >>= str2cstr >>= peekCString)\n-- RT_TRUE -> T_TRUE\n-- RT_FALSE -> T_FALSE\n-- RT_HASH -> T_HASH v\n-- RT_ARRAY -> T_ARRAY $ map fromVal $ unsafePerformIO $ mapM (rb_ary_entry v . fromIntegral) [0..(rb_ary_len v) - 1]\n-- RT_OBJECT -> T_OBJECT v\n-- -- RT_CLASS -> T_CLASS v\n-- _ -> error (\"didn't work: \" ++ show target)\n-- where target :: RubyType\n-- target = toEnum $ rtype v\n\n\n\n\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"a56a9db6990dc59ce82ed08d59057c33d246a141","subject":"TRIVIAL: Reordered Functions","message":"TRIVIAL: Reordered Functions\n","repos":"weissi\/hs-shonky-crypt","old_file":"src-hs\/Codec\/ShonkyCrypt\/ShonkyCryptFFI.chs","new_file":"src-hs\/Codec\/ShonkyCrypt\/ShonkyCryptFFI.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"204ed8759a4dfab4ec16be20defd953f54791496","subject":"fixed the C-errors","message":"fixed the C-errors\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport Data.ByteString\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype Signature = ByteString\n\nsignature :: FilePath -> IO (Either String Signature)\nsignature p = undefined\n\n\n\n-- | Given a file, and a handle h, opened in binary Read-Write mode, indicating\n-- where to write the signature to. Generate the signature. The signature is\n-- written to the file corresponding to handle h. The handle is moved to the\n-- beginning of the file. The function returns a Maybe String, indicating if\n-- something goes wrong. If the result is Nothing, the operation succeeded.\nhSignature :: FilePath -> Handle -> IO (Maybe String)\nhSignature p h = copyHandleToFd h >>= cGenSig p >>= \\r -> case r of\n RsDone -> hSeek h AbsoluteSeek 0 >> return Nothing\n _ -> return $ Just \"some error\"\n\n{#fun unsafe genSig as cGenSig\n { `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n #}\n\n-- We first implement a function to generate the signature which is easy to\n-- call\n#c\nrs_result genSig(char* filePath, int fd) {\n FILE* f;\n FILE* sigFile;\n rs_stats_t stats;\n rs_result result;\n\n f = fopen(filePath, \"rb\");\n sigFile = fdopen(fd, \"wb\");\n\n result = rs_sig_file(f, sigFile,\n RS_DEFAULT_BLOCK_LEN, RS_DEFAULT_STRONG_LEN, &stats);\n rs_file_close(f);\n\n \/\/ Note that we leave the sigfile open\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n-- | Given a handle refering to the sginature, in (at least) binary Read mode,\n-- positioned at the beginning of the file, a file path to a file, and a handle\n-- in binary read write mode. Compute the delta, and write the result to the\n-- file indicated by the second handle. The handle is repositioned to the\n-- beginning of the file. The result of this function is a Maybe String\n-- indicating any error messages. Nothing means the operation succeeded.\ncGenDelta :: Handle -> FilePath -> Handle -> IO (Maybe String)\ncGenDelta sigHandle p deltaHandle = undefined\n\n\n{#fun unsafe genDelta as genDelta'\n { fromIntegral `Fd'\n , `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n\n #}\n\n#c\n\/\/ generate a delta, based on the implementation of rdiff\nrs_result genDelta(int sigFd, char* filePath, int deltaFd) {\n FILE* sigFile;\n FILE* f;\n FILE* deltaFile;\n rs_result result;\n rs_signature_t* sumset;\n rs_stats_t stats;\n\n sigFile = fdopen(sigFd, \"rb\");\n f = fopen(filePath, \"rb\");\n deltaFile = fdopen(deltaFd, \"wb\");\n\n result = rs_loadsig_file(sigFile, &sumset, &stats);\n if (result != RS_DONE)\n return result;\n\n if ((result = rs_build_hash_table(sumset)) != RS_DONE)\n return result;\n\n result = rs_delta_file(sumset, f, deltaFile, &stats);\n\n rs_free_sumset(sumset);\n\n \/\/ rs_file_close(deltaFile);\n rs_file_close(f);\n rs_file_close(sigFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n{#fun unsafe applyPatch as applyPatch'\n { fromIntegral `Fd'\n , `String'\n , `String'\n } -> `Result' cIntToEnum\n #}\n\n\n#c\nrs_result applyPatch(int deltaFd, char* inputPath, char* outputPath) {\n FILE* deltaFile;\n FILE* inputFile;\n FILE* outputFile;\n rs_stats_t stats;\n rs_result result;\n\n inputFile = fopen(inputPath, \"rb\");\n deltaFile = fdopen(deltaFd, \"rb\");\n outputFile = fopen(outputPath, \"wb\");\n\n result = rs_patch_file(inputFile, deltaFile, outputFile, &stats);\n\n rs_file_close(inputFile);\n \/\/ keep the delta file open\n rs_file_close(outputFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n\ncopyHandleToFd h = hDuplicate h >>= handleToFd\n\ntest = do\n h <- openBinaryFile \"\/tmp\/signature\" ReadWriteMode\n r <- hSignature \"\/Users\/frank\/tmp\/httpd-error.log\" h\n print r\n hClose h\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Network.LibRSync.Internal where\n\nimport Data.ByteString\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \n#include \"librsync.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\n-- data Target = Target { t :: CUShort , i :: CInt }\n-- deriving (Show, Eq)\n\n-- {#pointer *rs_target as TargetPtr -> Target #}\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype Signature = ByteString\n\nsignature :: FilePath -> IO (Either String Signature)\nsignature p = undefined\n\n\n\n-- | Given a file, and a handle h, opened in binary Read-Write mode, indicating\n-- where to write the signature to. Generate the signature. The signature is\n-- written to the file corresponding to handle h. The handle is moved to the\n-- beginning of the file. The function returns a Maybe String, indicating if\n-- something goes wrong. If the result is Nothing, the operation succeeded.\nhSignature :: FilePath -> Handle -> IO (Maybe String)\nhSignature p h = copyHandleToFd h >>= cGenSig p >>= \\r -> case r of\n RsDone -> hSeek h AbsoluteSeek 0 >> return Nothing\n _ -> return $ Just \"some error\"\n\n{#fun unsafe genSig as cGenSig\n { `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n #}\n\n-- We first implement a function to generate the signature which is easy to\n-- call\n#c\nrs_result genSig(char* filePath, int fd) {\n FILE* f, sigFile;\n rs_stats_t stats;\n rs_result result;\n\n f = rs_file_open(filePath, \"rb\");\n sigFile = fdopen(fd, \"wb\");\n\n result = rs_sig_file(f, sigFile, &stats);\n rs_file_close(f);\n\n \/\/ Note that we leave the sigfile open\n\n return result;\n}\n#endc\n\n\n-- -- | Loading signatures\n-- -- the c-function is:\n-- -- rs_result rs_loadsig_file(FILE *, rs_signature_t **, rs_stats_t *);\n-- {#fun unsafe rs_loadsig_file as cRSLoadSigFile\n-- { id `Ptr CFile'\n-- , alloca- `SignaturePtr' peek*\n-- , alloca- `StatsPtr'\n-- } -> `Result' cIntToEnum\n-- #}\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\ncGenDelta :: Handle -> FilePath -> Handle -> IO (Handle, Result)\ncGenDelta sigHandle p deltaHandle = undefined\n\n\n{#fun unsafe genDelta as genDelta'\n { fromIntegral `Fd'\n , `String'\n , fromIntegral `Fd'\n } -> `Result' cIntToEnum\n\n #}\n\n#c\n\/\/ generate a delta, based on the implementation of rdiff\nrs_result genDelta(int sigFd, char* filePath, int deltaFd) {\n FILE* sigFile, f, deltaFile;\n rs_result result;\n rs_signature_t* sumset;\n rs_stats_t stats;\n\n sigFile = fdopen(sigFd, \"rb\");\n f = rs_open_file(filePath, \"rb\");\n deltaFile = fdopen(deltaFd, \"wb\");\n\n result = rs_loadsig_file(sigFile, &sumset, &stats);\n if (result != RS_DONE)\n return result;\n\n if ((result = rs_build_hash_table(sumset)) != RS_DONE)\n return result;\n\n result = rs_delta_file(sumset, f, deltaFile, &stats);\n\n rs_free_sumset(sumset);\n\n \/\/ rs_file_close(deltaFile);\n rs_file_close(f);\n rs_file_close(sigFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n{#fun unsafe applyPatch as applyPatch'\n { fromIntegral `Fd'\n , `String'\n , `String'\n } -> `Result' cIntToEnum\n #}\n\n\n#c\nrs_result applyPatch(int deltaFd, char* inputPath, char* outputPath) {\n FILE* deltaFile, inputFile, outputFile;\n rs_stats_t stats;\n rs_result result;\n\n inputFile = rs_file_open(inputPath, \"rb\");\n deltaFile = fdopen(deltaFd, \"rb\");\n outputFile = rs_file_open(outputPath, \"wb\");\n\n result = rs_patch_file(inputFile, deltaFile, outputFile, &stats);\n\n rs_file_close(inputFile);\n \/\/ keep the delta file open\n rs_file_close(outputFile);\n\n return result;\n}\n#endc\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n\ncopyHandleToFd h = hDuplicate h >>= handleToFd\n\ntest = do\n h <- openBinaryFile \"\/tmp\/signature\" ReadWriteMode\n r <- hSignature \"\/Users\/frank\/tmp\/httpd-error.log\" h\n print r\n hClose h\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"db254aff21b913c63b4a8a64d6f625dc4b48ad53","subject":"Some more refactoring","message":"Some more refactoring\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Tree.chs","new_file":"src\/haskell\/Data\/HGit2\/Tree.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Tree where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.OID\nimport Data.HGit2.Repository\nimport Data.HGit2.Errors\nimport Data.HGit2.Types\nimport Data.HGit2.Object\nimport Data.HGit2.Index\nimport Foreign\nimport Foreign.C\n\nnewtype Tree = Tree CPtr\nnewtype TreeEntry = TreeEntry CPtr\nnewtype TreeBuilder = TreeBuilder CPtr\n\ninstance CWrapper Tree where\n unwrap (Tree t) = t\n\ninstance CWrapper TreeEntry where\n unwrap (TreeEntry te) = te\n\ninstance CWrapper TreeBuilder where\n unwrap (TreeBuilder tb) = tb\n\nioIntRet :: Integral a => IO a -> IO Int\nioIntRet f = return . fromIntegral =<< f\n\n-- | Get the id of a tree.\ntreeId :: Tree -> OID\ntreeId (Tree t) = unsafePerformIO $\n return . OID =<< {#call git_tree_id#} t\n\n-- | Get the number of entries listed in a tree\nentryCount :: Tree -> IO Int\nentryCount (Tree t) = ioIntRet $ {#call git_tree_entrycount#} t\n\n-- | Lookup a tree entry by its filename\nentryByName :: Tree -> String -> IO TreeEntry\nentryByName (Tree t) fn =\n fmap TreeEntry $ {#call git_tree_entry_byname#} t =<< newCString fn\n\n-- | Lookup a tree entry by its position in the tree\nentryByIndex :: Tree -> Int -> IO TreeEntry\nentryByIndex (Tree t) n =\n fmap TreeEntry $ {#call git_tree_entry_byindex#} t (fromIntegral n)\n\n-- | Get the UNIX file attributes of a tree entry\nattributes :: TreeEntry -> IO Int\nattributes (TreeEntry e) = ioIntRet $ {#call git_tree_entry_attributes#} e\n\n-- | Get the filename of a tree entry\nname :: TreeEntry -> IO String\nname (TreeEntry t) = peekCString =<< {#call git_tree_entry_name#} t\n\n-- | Get the id of the object pointed by the entry\nentryId :: TreeEntry -> IO OID\nentryId (TreeEntry t) = fmap OID $ {#call git_tree_entry_id#} t\n\n-- | Get the type of the object pointed by the entry\nentryType :: TreeEntry -> IO OType\nentryType (TreeEntry t) =\n fmap (toEnum . fromIntegral) $ {#call git_tree_entry_type#} t\n\n-- | Convert a tree entry to the git_object it points too.\nentryToObj :: Repository -> TreeEntry -> IO (Either GitError GitObj)\nentryToObj (Repository r) (TreeEntry t) = alloca $ \\obj -> do\n res <- {#call git_tree_entry_2object#} obj r t\n retEither res $ fmap (Right . GitObj) $ peek obj\n\n-- Write a tree to the ODB from the index file\ncreateFromIndex :: OID -> Index -> IO (Maybe GitError)\ncreateFromIndex (OID o) (Index i) =\n retMaybe =<< {#call git_tree_create_fromindex#} o i\n\n-- | Create a new tree builder\ncreateTreeBuilder :: Maybe Tree -> IO (Either GitError TreeBuilder)\ncreateTreeBuilder tr = alloca $ \\builder -> do\n res <- {#call git_treebuilder_create#} builder t\n retEither res $ fmap (Right . TreeBuilder) $ peek builder\n where t = case tr of\n Nothing -> nullPtr\n Just (Tree x) -> x\n\n-- | Clear all the entires in the builder\nclearTreeBuilder :: TreeBuilder -> IO ()\nclearTreeBuilder (TreeBuilder t) = {#call git_treebuilder_clear#} t\n\n-- | Free a tree builder\nfreeTreeBuilder :: TreeBuilder -> IO ()\nfreeTreeBuilder (TreeBuilder t) = {#call git_treebuilder_free#} t\n\n-- Get an entry from the builder from its filename\ngetTreeBuilder :: TreeBuilder -> String -> IO (Maybe TreeEntry)\ngetTreeBuilder (TreeBuilder b) fn =\n retRes TreeEntry =<< {#call git_treebuilder_get#} b =<< newCString fn\n\n-- | Add or update an entry to the builder\ninsertTreeBuilder :: TreeBuilder -> String -> OID -> Int\n -> IO (Either GitError TreeEntry)\ninsertTreeBuilder (TreeBuilder b) fn (OID o) as = alloca $ \\entry -> do\n fn' <- newCString fn\n res <- {#call git_treebuilder_insert#} entry b fn' o (fromIntegral as)\n retEither res $ fmap (Right . TreeEntry) $ peek entry\n\n-- | Remove an entry from the builder by its filename\nremoveTreeBuilder :: TreeBuilder -> String -> IO (Maybe GitError)\nremoveTreeBuilder (TreeBuilder t) fn =\n retMaybe =<< {#call git_treebuilder_remove#} t =<< newCString fn\n\n{-\n\/**\n * Filter the entries in the tree\n *\n * The `filter` callback will be called for each entry\n * in the tree with a pointer to the entry and the\n * provided `payload`: if the callback returns 1, the\n * entry will be filtered (removed from the builder).\n *\n * @param bld Tree builder\n * @param filter Callback to filter entries\n *\/\nGIT_EXTERN(void) git_treebuilder_filter(git_treebuilder *bld, int (*filter)(const git_tree_entry *, void *), void *payload);\nTODO: How to handle callbacks?\n-- TODO: what do we make these CPtrs?\n-}\n-- filterTreeBuilder :: TreeBuilder -> TreeEntry -> CPtr -> CPtr -> IO ()\n-- filterTreeBuilder (TreeBuilder b) (TreeEntry e) v p = {#call git_treebuilder_filter#} b -- TODO: What? (FunPtr e v) p\n\n-- | Write the contents of the tree builder as a tree object\nwriteTreeBuilder :: OID -> Repository -> TreeBuilder -> IO (Maybe GitError)\nwriteTreeBuilder (OID o) (Repository r) (TreeBuilder t) =\n retMaybe =<< {#call git_treebuilder_write#} o r t\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Tree where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.OID\nimport Data.HGit2.Repository\nimport Data.HGit2.Errors\nimport Data.HGit2.Types\nimport Data.HGit2.Object\nimport Data.HGit2.Index\nimport Foreign\nimport Foreign.C\n\nnewtype Tree = Tree CPtr\nnewtype TreeEntry = TreeEntry CPtr\nnewtype TreeBuilder = TreeBuilder CPtr\n\ninstance CWrapper Tree where\n unwrap (Tree t) = t\n\ninstance CWrapper TreeEntry where\n unwrap (TreeEntry te) = te\n\ninstance CWrapper TreeBuilder where\n unwrap (TreeBuilder tb) = tb\n\nioIntRet :: Integral a => IO a -> IO Int\nioIntRet f = return . fromIntegral =<< f\n\n-- | Get the id of a tree.\ntreeId :: Tree -> OID\ntreeId (Tree t) = unsafePerformIO $\n return . OID =<< {#call git_tree_id#} t\n\n-- | Get the number of entries listed in a tree\nentryCount :: Tree -> IO Int\nentryCount (Tree t) = ioIntRet $ {#call git_tree_entrycount#} t\n\n-- | Lookup a tree entry by its filename\nentryByName :: Tree -> String -> IO TreeEntry\nentryByName (Tree t) fn = do\n fn' <- newCString fn\n fmap TreeEntry $ {#call git_tree_entry_byname#} t fn'\n\n-- | Lookup a tree entry by its position in the tree\nentryByIndex :: Tree -> Int -> IO TreeEntry\nentryByIndex (Tree t) n =\n fmap TreeEntry $ {#call git_tree_entry_byindex#} t (fromIntegral n)\n\n-- | Get the UNIX file attributes of a tree entry\nattributes :: TreeEntry -> IO Int\nattributes (TreeEntry e) = ioIntRet $ {#call git_tree_entry_attributes#} e\n\n-- | Get the filename of a tree entry\nname :: TreeEntry -> IO String\nname (TreeEntry t) = peekCString =<< {#call git_tree_entry_name#} t\n\n-- | Get the id of the object pointed by the entry\nentryId :: TreeEntry -> IO OID\nentryId (TreeEntry t) = fmap OID $ {#call git_tree_entry_id#} t\n\n-- | Get the type of the object pointed by the entry\nentryType :: TreeEntry -> IO OType\nentryType (TreeEntry t) =\n fmap (toEnum . fromIntegral) $ {#call git_tree_entry_type#} t\n\n-- | Convert a tree entry to the git_object it points too.\nentryToObj :: Repository -> TreeEntry -> IO (Either GitError GitObj)\nentryToObj (Repository r) (TreeEntry t) = alloca $ \\obj -> do\n res <- {#call git_tree_entry_2object#} obj r t\n retEither res $ fmap (Right . GitObj) $ peek obj\n\n-- Write a tree to the ODB from the index file\ncreateFromIndex :: OID -> Index -> IO (Maybe GitError)\ncreateFromIndex (OID o) (Index i) =\n retMaybe =<< {#call git_tree_create_fromindex#} o i\n\n-- | Create a new tree builder\ncreateTreeBuilder :: Maybe Tree -> IO (Either GitError TreeBuilder)\ncreateTreeBuilder tr = alloca $ \\builder -> do\n res <- {#call git_treebuilder_create#} builder t\n retEither res $ fmap (Right . TreeBuilder) $ peek builder\n where t = case tr of\n Nothing -> nullPtr\n Just (Tree x) -> x\n\n-- | Clear all the entires in the builder\nclearTreeBuilder :: TreeBuilder -> IO ()\nclearTreeBuilder (TreeBuilder t) = {#call git_treebuilder_clear#} t\n\n-- | Free a tree builder\nfreeTreeBuilder :: TreeBuilder -> IO ()\nfreeTreeBuilder (TreeBuilder t) = {#call git_treebuilder_free#} t\n\n-- Get an entry from the builder from its filename\ngetTreeBuilder :: TreeBuilder -> String -> IO (Maybe TreeEntry)\ngetTreeBuilder (TreeBuilder b) fn =\n retRes TreeEntry =<< {#call git_treebuilder_get#} b =<< newCString fn\n\n-- | Add or update an entry to the builder\ninsertTreeBuilder :: TreeBuilder -> String -> OID -> Int\n -> IO (Either GitError TreeEntry)\ninsertTreeBuilder (TreeBuilder b) fn (OID o) as = alloca $ \\entry -> do\n fn' <- newCString fn\n res <- {#call git_treebuilder_insert#} entry b fn' o (fromIntegral as)\n retEither res $ fmap (Right . TreeEntry) $ peek entry\n\n-- | Remove an entry from the builder by its filename\nremoveTreeBuilder :: TreeBuilder -> String -> IO (Maybe GitError)\nremoveTreeBuilder (TreeBuilder t) fn = do\n str <- newCString fn\n retMaybe =<< {#call git_treebuilder_remove#} t str\n\n{-\n\/**\n * Filter the entries in the tree\n *\n * The `filter` callback will be called for each entry\n * in the tree with a pointer to the entry and the\n * provided `payload`: if the callback returns 1, the\n * entry will be filtered (removed from the builder).\n *\n * @param bld Tree builder\n * @param filter Callback to filter entries\n *\/\nGIT_EXTERN(void) git_treebuilder_filter(git_treebuilder *bld, int (*filter)(const git_tree_entry *, void *), void *payload);\nTODO: How to handle callbacks?\n-- TODO: what do we make these CPtrs?\n-}\n-- filterTreeBuilder :: TreeBuilder -> TreeEntry -> CPtr -> CPtr -> IO ()\n-- filterTreeBuilder (TreeBuilder b) (TreeEntry e) v p = {#call git_treebuilder_filter#} b -- TODO: What? (FunPtr e v) p\n\n-- | Write the contents of the tree builder as a tree object\nwriteTreeBuilder :: OID -> Repository -> TreeBuilder -> IO (Maybe GitError)\nwriteTreeBuilder (OID o) (Repository r) (TreeBuilder t) =\n retMaybe =<< {#call git_treebuilder_write#} o r t\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7efce9df087f56173d5ad888245c154fac11f137","subject":"Remove spurious ',' which upset haddock","message":"Remove spurious ',' which upset haddock\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/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":"98bf9be3c0bc98cc31baa1e69f541e36383294b5","subject":"Config","message":"Config\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Config.chs","new_file":"src\/haskell\/Data\/HGit2\/Config.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Config where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Foreign\nimport Foreign.C\n\nnewtype Config = Config CPtr\nnewtype ConfigFile = ConfigFile CPtr\n\n\ninstance CWrapper Config where\n unwrap (Config c) = c\n\ninstance CWrapper ConfigFile where\n unwrap (ConfigFile cf) = cf\n\n-- | Locate the path to the global configuration file\n--\n-- The user or global configuration file is usually located in\n-- `$HOME\/.gitconfig`.\n--\n-- This method will try to guess the full path to that file, if the file\n-- exists. The returned path may be used on any `git_config` call to load the\n-- global configuration file.\nfindGlobalConfig :: IO (Maybe String)\nfindGlobalConfig = alloca $ \\pth -> do\n res <- {#call git_config_find_global#} pth\n if res == 0\n then fmap Just $ peekCString pth\n else return Nothing\n\n-- | Open the global configuration file\nopenGlobalConfig :: IOEitherErr Config\nopenGlobalConfig = callPeek Config {#call git_config_open_global#}\n\n-- | Create a configuration file backend for ondisk files\n--\n-- These are the normal `.gitconfig` files that Core Git processes. Note that\n-- you first have to add this file to a configuration object before you can\n-- query it for configuration variables.\ncreateOnDisk :: String -> IOEitherErr ConfigFile\ncreateOnDisk str =\n withCString str $ \\str' ->\n callPeek ConfigFile (\\out -> {#call git_config_file__ondisk#} out str')\n\n-- | Allocate a new configuration object\n--\n-- This object is empty, so you have to add a file to it before you can do\n-- anything with it.\nnewConfig :: IOEitherErr Config\nnewConfig = callPeek Config {#call git_config_new#}\n\n-- | Add a generic config file instance to an existing config\n--\n-- Note that the configuration object will free the file automatically.\n--\n-- Further queries on this config object will access each of the config file\n-- instances in order. Instances with a higher priority will be accessed first.\naddFile :: Config -> ConfigFile -> Int -> IO GitError\naddFile (Config cfp) (ConfigFile ffp) pr =\n withForeignPtr cfp $ \\c ->\n withForeignPtr ffp $ \\f ->\n retEnum $ {#call git_config_add_file#} c f (fromIntegral pr)\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 parsed; it's\n-- expected to be a native Git config file following the default Git config\n-- syntax (see man git-config).\n--\n-- Note that the configuration object will free the file automatically.\n--\n-- Further queries on this config object will access each of the config file\n-- instances in order. Instances with a higher priority will be accessed first.\naddOnDisk :: Config -> String -> Int -> IO GitError\naddOnDisk (Config cfp) pth pr =\n withForeignPtr cfp $ \\c ->\n withCString pth $ \\pth' ->\n retEnum $ {#call git_config_add_file_ondisk#} c pth' (fromIntegral pr)\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 of calls:\n-- - newConfig\n-- - addOnDisk\nopenOnDisk :: String -> IOEitherErr Config\nopenOnDisk str =\n withCString str $ \\str' ->\n callPeek Config (\\out -> {#call git_config_open_ondisk#} out str')\n\n-- | Get the value of an integer config variable.\nconfigInt :: Config -> String -> IOEitherErr Int\nconfigInt (Config cfp) str = alloca $ \\out ->\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' -> do\n res <- {#call git_config_get_int#} c str' out\n num <- peek out\n retEither res $ return . Right $ fromIntegral num\n\n-- | Get the value of an integer config variable.\nconfigInteger :: Config -> String -> IOEitherErr Integer\nconfigInteger (Config cfp) str = alloca $ \\out ->\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' -> do\n res <- {#call git_config_get_long#} c str' out\n num <- peek out\n retEither res $ return . Right $ fromIntegral num\n\n-- | Get the value of a boolean config variable.\nconfigBool :: Config -> String -> IO (Either GitError Bool)\nconfigBool (Config cfp) str =\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' -> alloca $ \\out -> do\n res <- {#call git_config_get_bool#} c str' out\n retEither res $ fmap (Right . toBool) $ peek out\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 user.\nconfigString :: Config -> String -> IO (Either GitError String)\nconfigString (Config cfp) vn =\n withForeignPtr cfp $ \\c ->\n withCString vn $ \\vn' -> alloca $ \\out -> do\n res <- {#call git_config_get_string#} c vn' out\n retEither res $ fmap Right $ peekCString =<< peek out\n\n-- | Set the value of an integer config variable.\nsetConfigInt :: Config -> String -> Int -> IOCanFail\nsetConfigInt conf vn val =\n mConfig {#call git_config_set_int#} conf vn (fromIntegral val)\n\n-- | Set the value of a long integer config variable.\nsetConfigInteger :: Config -> String -> Integer -> IOCanFail\nsetConfigInteger conf vn val =\n mConfig {#call git_config_set_long#} conf vn (fromIntegral val)\n\n-- | Set the value of a boolean config variable.\nsetConfigBool :: Config -> String -> Bool -> IOCanFail\nsetConfigBool conf vn val =\n mConfig {#call git_config_set_bool#} conf vn (fromBool val)\n\n-- | Set the value of a string config variable.\nsetConfigString :: Config -> String -> String -> IOCanFail\nsetConfigString conf vn val = withCString val $ \\val' ->\n mConfig {#call git_config_set_string#} conf vn val'\n\n-- | Delete a config variable\ndelConfig :: Config -> String -> IOCanFail\ndelConfig (Config cfp) vn =\n withForeignPtr cfp $ \\c ->\n withCString vn $ \\str ->\n retMaybe =<< {#call git_config_delete#} c str\n\nmConfig :: (Ptr () -> CString -> t -> IO CInt) -> Config -> String -> t\n -> IOCanFail\nmConfig call (Config cfp) vn val =\n withForeignPtr cfp $ \\c ->\n withCString vn $ \\str ->\n retMaybe =<< call c str val\n\n-- TODO: foreachConfig :: Config ->\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Config where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Foreign\nimport Foreign.C\n\nnewtype Config = Config CPtr\nnewtype ConfigFile = ConfigFile CPtr\n\n\ninstance CWrapper Config where\n unwrap (Config c) = c\n\ninstance CWrapper ConfigFile where\n unwrap (ConfigFile cf) = cf\n\n-- | Locate the path to the global configuration file\n--\n-- The user or global configuration file is usually located in\n-- `$HOME\/.gitconfig`.\n--\n-- This method will try to guess the full path to that file, if the file\n-- exists. The returned path may be used on any `git_config` call to load the\n-- global configuration file.\nfindGlobalConfig :: IO (Maybe String)\nfindGlobalConfig = alloca $ \\pth -> do\n res <- {#call git_config_find_global#} pth\n if res == 0\n then fmap Just $ peekCString pth\n else return Nothing\n\n-- | Open the global configuration file\nopenGlobalConfig :: IOEitherErr Config\nopenGlobalConfig = callPeek Config {#call git_config_open_global#}\n\n-- | Create a configuration file backend for ondisk files\n--\n-- These are the normal `.gitconfig` files that Core Git processes. Note that\n-- you first have to add this file to a configuration object before you can\n-- query it for configuration variables.\ncreateOnDisk :: String -> IOEitherErr ConfigFile\ncreateOnDisk str = withCString str $ \\str' ->\n callPeek ConfigFile (\\out -> {#call git_config_file__ondisk#} out str')\n\n-- | Allocate a new configuration object\n--\n-- This object is empty, so you have to add a file to it before you can do\n-- anything with it.\nnewConfig :: IOEitherErr Config\nnewConfig = callPeek Config {#call git_config_new#}\n\n-- | Add a generic config file instance to an existing config\n--\n-- Note that the configuration object will free the file automatically.\n--\n-- Further queries on this config object will access each of the config file\n-- instances in order. Instances with a higher priority will be accessed first.\naddFile :: Config -> ConfigFile -> Int -> IO GitError\naddFile (Config cfp) (ConfigFile ffp) pr =\n withForeignPtr cfp $ \\c ->\n withForeignPtr ffp $ \\f ->\n retEnum $ {#call git_config_add_file#} c f (fromIntegral pr)\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 parsed; it's\n-- expected to be a native Git config file following the default Git config\n-- syntax (see man git-config).\n--\n-- Note that the configuration object will free the file automatically.\n--\n-- Further queries on this config object will access each of the config file\n-- instances in order. Instances with a higher priority will be accessed first.\naddOnDisk :: Config -> String -> Int -> IO GitError\naddOnDisk (Config cfp) pth pr =\n withForeignPtr cfp $ \\c ->\n withCString pth $ \\pth' ->\n retEnum $ {#call git_config_add_file_ondisk#} c pth' (fromIntegral pr)\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 of calls:\n-- - newConfig\n-- - addOnDisk\nopenOnDisk :: String -> IOEitherErr Config\nopenOnDisk str =\n withCString str $ \\str' ->\n callPeek Config (\\out -> {#call git_config_open_ondisk#} out str')\n\n-- | Get the value of an integer config variable.\nconfigInt :: Config -> String -> IOEitherErr Int\nconfigInt (Config cfp) str =\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' ->\n undefined\n {- callPeek fromIntegral ({#call git_config_get_int#} c str')-}\n\n-- | Get the value of an integer config variable.\nconfigInteger :: Config -> String -> IOEitherErr Integer\nconfigInteger (Config cfp) str =\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' ->\n undefined\n {- callPeek fromIntegral ({#call git_config_get_long#} c str')-}\n\n-- | Get the value of a boolean config variable.\nconfigBool :: Config -> String -> IO (Either GitError Bool)\nconfigBool (Config cfp) str =\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' -> alloca $ \\out -> do\n res <- {#call git_config_get_bool#} c str' out\n retEither res $ fmap (Right . toBool) $ peek out\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 user.\nconfigString :: Config -> String -> IO (Either GitError String)\nconfigString (Config cfp) vn =\n withForeignPtr cfp $ \\c ->\n withCString vn $ \\vn' -> alloca $ \\out -> do\n res <- {#call git_config_get_string#} c vn' out\n retEither res $ fmap Right $ peekCString =<< peek out\n\n-- | Set the value of an integer config variable.\nsetConfigInt :: Config -> String -> Int -> IOCanFail\nsetConfigInt conf vn val =\n mConfig {#call git_config_set_int#} conf vn (fromIntegral val)\n\n-- | Set the value of a long integer config variable.\nsetConfigInteger :: Config -> String -> Integer -> IOCanFail\nsetConfigInteger conf vn val =\n mConfig {#call git_config_set_long#} conf vn (fromIntegral val)\n\n-- | Set the value of a boolean config variable.\nsetConfigBool :: Config -> String -> Bool -> IOCanFail\nsetConfigBool conf vn val =\n mConfig {#call git_config_set_bool#} conf vn (fromBool val)\n\n-- | Set the value of a string config variable.\nsetConfigString :: Config -> String -> String -> IOCanFail\nsetConfigString conf vn val = withCString val $ \\val' ->\n mConfig {#call git_config_set_string#} conf vn val'\n\n-- | Delete a config variable\ndelConfig :: Config -> String -> IOCanFail\ndelConfig (Config cfp) vn =\n withForeignPtr cfp $ \\c ->\n withCString vn $ \\str ->\n retMaybe =<< {#call git_config_delete#} c str\n\n{- mConfig :: (CPtr -> CString -> t -> IO CInt) -> Config -> String -> t-}\n {- -> IO (Maybe GitError)-}\nmConfig :: (Ptr () -> CString -> t -> IO CInt) -> Config -> String -> t\n -> IOCanFail\nmConfig call (Config cfp) vn val =\n withForeignPtr cfp $ \\c ->\n withCString vn $ \\str ->\n retMaybe =<< call c str val\n\n-- TODO: foreachConfig :: Config ->\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"726a59ad913f12fa6800acb80810f85b361ac6c0","subject":"warning police: orphans","message":"warning police: orphans\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Device.chs","new_file":"Foreign\/CUDA\/Runtime\/Device.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyCase #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Device (\n\n -- * Device Management\n Device, DeviceFlag(..), DeviceProperties(..), Compute(..), ComputeMode(..),\n choose, get, count, props, set, setFlags, setOrder, reset, sync,\n\n -- * Peer Access\n PeerFlag,\n accessible, add, remove,\n\n -- * Cache Configuration\n Limit(..),\n getLimit, setLimit\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n-- System\nimport Foreign\nimport Foreign.C\n\n#c\ntypedef struct cudaDeviceProp cudaDeviceProp;\n\ntypedef enum\n{\n cudaDeviceFlagScheduleAuto = cudaDeviceScheduleAuto,\n cudaDeviceFlagScheduleSpin = cudaDeviceScheduleSpin,\n cudaDeviceFlagScheduleYield = cudaDeviceScheduleYield,\n cudaDeviceFlagBlockingSync = cudaDeviceBlockingSync,\n cudaDeviceFlagMapHost = cudaDeviceMapHost,\n#if CUDART_VERSION >= 3000\n cudaDeviceFlagLMemResizeToMax = cudaDeviceLmemResizeToMax\n#endif\n} cudaDeviceFlags;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A device identifier\n--\ntype Device = Int\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlag { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"no instance for Foreign.Storable.poke DeviceProperties\"\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n#if CUDART_VERSION >= 3000\n ck <- cToBool `fmap` {#get cudaDeviceProp.concurrentKernels#} p\n u1 <- cIntConv `fmap` {#get cudaDeviceProp.maxTexture1D#} p\n#endif\n#if CUDART_VERSION >= 3010\n ee <- cToBool `fmap` {#get cudaDeviceProp.ECCEnabled#} p\n#endif\n#if CUDART_VERSION >= 4000\n ae <- cIntConv `fmap` {#get cudaDeviceProp.asyncEngineCount#} p\n l2 <- cIntConv `fmap` {#get cudaDeviceProp.l2CacheSize#} p\n tm <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerMultiProcessor#} p\n mw <- cIntConv `fmap` {#get cudaDeviceProp.memoryBusWidth#} p\n mc <- cIntConv `fmap` {#get cudaDeviceProp.memoryClockRate#} p\n pb <- cIntConv `fmap` {#get cudaDeviceProp.pciBusID#} p\n pd <- cIntConv `fmap` {#get cudaDeviceProp.pciDeviceID#} p\n pm <- cIntConv `fmap` {#get cudaDeviceProp.pciDomainID#} p\n tc <- cToBool `fmap` {#get cudaDeviceProp.tccDriver#} p\n ua <- cToBool `fmap` {#get cudaDeviceProp.unifiedAddressing#} p\n#endif\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n#if CUDART_VERSION >= 3000\n (u21:u22:_) <- map cIntConv `fmap` peekArray 2 (p `plusPtr` devMaxTexture2DOffset :: Ptr CInt)\n (u31:u32:u33:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxTexture3DOffset :: Ptr CInt)\n#endif\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = Compute v1 v2,\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxBlockSize = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n#if CUDART_VERSION >= 3000\n concurrentKernels = ck,\n maxTextureDim1D = u1,\n maxTextureDim2D = (u21,u22),\n maxTextureDim3D = (u31,u32,u33),\n#endif\n#if CUDART_VERSION >= 3010\n eccEnabled = ee,\n#endif\n#if CUDART_VERSION >= 3000 && CUDART_VERSION < 3010\n -- not visible from runtime API < 3.1\n eccEnabled = False,\n#endif\n#if CUDART_VERSION >= 4000\n asyncEngineCount = ae,\n cacheMemL2 = l2,\n maxThreadsPerMultiProcessor = tm,\n memBusWidth = mw,\n memClockRate = mc,\n tccDriverEnabled = tc,\n unifiedAddressing = ua,\n pciInfo = PCI pb pd pm,\n#endif\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\n{-# INLINEABLE choose #-}\nchoose :: DeviceProperties -> IO Device\nchoose !dev = resultIfOk =<< cudaChooseDevice dev\n\n{-# INLINE cudaChooseDevice #-}\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv*\n , withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n\n-- |\n-- Returns which device is currently being used\n--\n{-# INLINEABLE get #-}\nget :: IO Device\nget = resultIfOk =<< cudaGetDevice\n\n{-# INLINE cudaGetDevice #-}\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\n{-# INLINEABLE count #-}\ncount :: IO Int\ncount = resultIfOk =<< cudaGetDeviceCount\n\n{-# INLINE cudaGetDeviceCount #-}\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Return information about the selected compute device\n--\n{-# INLINEABLE props #-}\nprops :: Device -> IO DeviceProperties\nprops !n = resultIfOk =<< cudaGetDeviceProperties n\n\n{-# INLINE cudaGetDeviceProperties #-}\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek*\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set device to be used for GPU execution\n--\n{-# INLINEABLE set #-}\nset :: Device -> IO ()\nset !n = nothingIfOk =<< cudaSetDevice n\n\n{-# INLINE cudaSetDevice #-}\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set flags to be used for device executions\n--\n{-# INLINEABLE setFlags #-}\nsetFlags :: [DeviceFlag] -> IO ()\nsetFlags !f = nothingIfOk =<< cudaSetDeviceFlags (combineBitMasks f)\n\n{-# INLINE cudaSetDeviceFlags #-}\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\n{-# INLINEABLE setOrder #-}\nsetOrder :: [Device] -> IO ()\nsetOrder !l = nothingIfOk =<< cudaSetValidDevices l (length l)\n\n{-# INLINE cudaSetValidDevices #-}\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]'\n , `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\n-- |\n-- Block until the device has completed all preceding requested tasks. Returns\n-- an error if one of the tasks fails.\n--\n{-# INLINEABLE sync #-}\nsync :: IO ()\n#if CUDART_VERSION < 4000\n{-# INLINE cudaThreadSynchronize #-}\nsync = nothingIfOk =<< cudaThreadSynchronize\n{# fun cudaThreadSynchronize { } -> `Status' cToEnum #}\n#else\n{-# INLINE cudaDeviceSynchronize #-}\nsync = nothingIfOk =<< cudaDeviceSynchronize\n{# fun cudaDeviceSynchronize { } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Explicitly destroys and cleans up all runtime resources associated with the\n-- current device in the current process. Any subsequent API call will\n-- reinitialise the device.\n--\n-- Note that this function will reset the device immediately. It is the caller\u2019s\n-- responsibility to ensure that the device is not being accessed by any other\n-- host threads from the process when this function is called.\n--\n{-# INLINEABLE reset #-}\nreset :: IO ()\n#if CUDART_VERSION >= 4000\n{-# INLINE cudaDeviceReset #-}\nreset = nothingIfOk =<< cudaDeviceReset\n{# fun unsafe cudaDeviceReset { } -> `Status' cToEnum #}\n#else\n{-# INLINE cudaThreadExit #-}\nreset = nothingIfOk =<< cudaThreadExit\n{# fun unsafe cudaThreadExit { } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Peer Access\n--------------------------------------------------------------------------------\n\n-- |\n-- Possible option values for direct peer memory access\n--\ndata PeerFlag\ninstance Enum PeerFlag where\n toEnum x = case x of {}\n fromEnum x = case x of {}\n\n-- |\n-- Queries if the first device can directly access the memory of the second. If\n-- direct access is possible, it can then be enabled with 'add'. Requires\n-- cuda-4.0.\n--\n{-# INLINEABLE accessible #-}\naccessible :: Device -> Device -> IO Bool\n#if CUDART_VERSION < 4000\naccessible _ _ = requireSDK 4.0 \"accessible\"\n#else\naccessible !dev !peer = resultIfOk =<< cudaDeviceCanAccessPeer dev peer\n\n{-# INLINE cudaDeviceCanAccessPeer #-}\n{# fun unsafe cudaDeviceCanAccessPeer\n { alloca- `Bool' peekBool*\n , cIntConv `Device'\n , cIntConv `Device' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- If the devices of both the current and supplied contexts support unified\n-- addressing, then enable allocations in the supplied context to be accessible\n-- by the current context. Requires cuda-4.0.\n--\n{-# INLINEABLE add #-}\nadd :: Device -> [PeerFlag] -> IO ()\n#if CUDART_VERSION < 4000\nadd _ _ = requireSDK 4.0 \"add\"\n#else\nadd !dev !flags = nothingIfOk =<< cudaDeviceEnablePeerAccess dev flags\n\n{-# INLINE cudaDeviceEnablePeerAccess #-}\n{# fun unsafe cudaDeviceEnablePeerAccess\n { cIntConv `Device'\n , combineBitMasks `[PeerFlag]' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Disable direct memory access from the current context to the supplied\n-- context. Requires cuda-4.0.\n--\n{-# INLINEABLE remove #-}\nremove :: Device -> IO ()\n#if CUDART_VERSION < 4000\nremove _ = requireSDK 4.0 \"remove\"\n#else\nremove !dev = nothingIfOk =<< cudaDeviceDisablePeerAccess dev\n\n{-# INLINE cudaDeviceDisablePeerAccess #-}\n{# fun unsafe cudaDeviceDisablePeerAccess\n { cIntConv `Device' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Cache Configuration\n--------------------------------------------------------------------------------\n\n-- |\n-- Device limit flags\n--\n#if CUDART_VERSION < 3010\ndata Limit\n#else\n{# enum cudaLimit as Limit\n { underscoreToCase }\n with prefix=\"cudaLimit\" deriving (Eq, Show) #}\n#endif\n\n\n-- |\n-- Query compute 2.0 call stack limits. Requires cuda-3.1.\n--\n{-# INLINEABLE getLimit #-}\ngetLimit :: Limit -> IO Int\n#if CUDART_VERSION < 3010\ngetLimit _ = requireSDK 3.1 \"getLimit\"\n#elif CUDART_VERSION < 4000\ngetLimit !l = resultIfOk =<< cudaThreadGetLimit l\n\n{-# INLINE cudaThreadGetLimit #-}\n{# fun unsafe cudaThreadGetLimit\n { alloca- `Int' peekIntConv*\n , cFromEnum `Limit' } -> `Status' cToEnum #}\n#else\ngetLimit !l = resultIfOk =<< cudaDeviceGetLimit l\n\n{-# INLINE cudaDeviceGetLimit #-}\n{# fun unsafe cudaDeviceGetLimit\n { alloca- `Int' peekIntConv*\n , cFromEnum `Limit' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Set compute 2.0 call stack limits. Requires cuda-3.1.\n--\n{-# INLINEABLE setLimit #-}\nsetLimit :: Limit -> Int -> IO ()\n#if CUDART_VERSION < 3010\nsetLimit _ _ = requireSDK 3.1 \"setLimit\"\n#elif CUDART_VERSION < 4000\nsetLimit !l !n = nothingIfOk =<< cudaThreadSetLimit l n\n\n{-# INLINE cudaThreadSetLimit #-}\n{# fun unsafe cudaThreadSetLimit\n { cFromEnum `Limit'\n , cIntConv `Int' } -> `Status' cToEnum #}\n#else\nsetLimit !l !n = nothingIfOk =<< cudaDeviceSetLimit l n\n\n{-# INLINE cudaDeviceSetLimit #-}\n{# fun unsafe cudaDeviceSetLimit\n { cFromEnum `Limit'\n , cIntConv `Int' } -> `Status' cToEnum #}\n#endif\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyCase #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Device (\n\n -- * Device Management\n Device, DeviceFlag(..), DeviceProperties(..), Compute(..), ComputeMode(..),\n choose, get, count, props, set, setFlags, setOrder, reset, sync,\n\n -- * Peer Access\n PeerFlag,\n accessible, add, remove,\n\n -- * Cache Configuration\n Limit(..),\n getLimit, setLimit\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n-- System\nimport Foreign\nimport Foreign.C\n\n#c\ntypedef struct cudaDeviceProp cudaDeviceProp;\n\ntypedef enum\n{\n cudaDeviceFlagScheduleAuto = cudaDeviceScheduleAuto,\n cudaDeviceFlagScheduleSpin = cudaDeviceScheduleSpin,\n cudaDeviceFlagScheduleYield = cudaDeviceScheduleYield,\n cudaDeviceFlagBlockingSync = cudaDeviceBlockingSync,\n cudaDeviceFlagMapHost = cudaDeviceMapHost,\n#if CUDART_VERSION >= 3000\n cudaDeviceFlagLMemResizeToMax = cudaDeviceLmemResizeToMax\n#endif\n} cudaDeviceFlags;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A device identifier\n--\ntype Device = Int\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlag { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"no instance for Foreign.Storable.poke DeviceProperties\"\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n#if CUDART_VERSION >= 3000\n ck <- cToBool `fmap` {#get cudaDeviceProp.concurrentKernels#} p\n u1 <- cIntConv `fmap` {#get cudaDeviceProp.maxTexture1D#} p\n#endif\n#if CUDART_VERSION >= 3010\n ee <- cToBool `fmap` {#get cudaDeviceProp.ECCEnabled#} p\n#endif\n#if CUDART_VERSION >= 4000\n ae <- cIntConv `fmap` {#get cudaDeviceProp.asyncEngineCount#} p\n l2 <- cIntConv `fmap` {#get cudaDeviceProp.l2CacheSize#} p\n tm <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerMultiProcessor#} p\n mw <- cIntConv `fmap` {#get cudaDeviceProp.memoryBusWidth#} p\n mc <- cIntConv `fmap` {#get cudaDeviceProp.memoryClockRate#} p\n pb <- cIntConv `fmap` {#get cudaDeviceProp.pciBusID#} p\n pd <- cIntConv `fmap` {#get cudaDeviceProp.pciDeviceID#} p\n pm <- cIntConv `fmap` {#get cudaDeviceProp.pciDomainID#} p\n tc <- cToBool `fmap` {#get cudaDeviceProp.tccDriver#} p\n ua <- cToBool `fmap` {#get cudaDeviceProp.unifiedAddressing#} p\n#endif\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n#if CUDART_VERSION >= 3000\n (u21:u22:_) <- map cIntConv `fmap` peekArray 2 (p `plusPtr` devMaxTexture2DOffset :: Ptr CInt)\n (u31:u32:u33:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxTexture3DOffset :: Ptr CInt)\n#endif\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = Compute v1 v2,\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxBlockSize = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n#if CUDART_VERSION >= 3000\n concurrentKernels = ck,\n maxTextureDim1D = u1,\n maxTextureDim2D = (u21,u22),\n maxTextureDim3D = (u31,u32,u33),\n#endif\n#if CUDART_VERSION >= 3010\n eccEnabled = ee,\n#endif\n#if CUDART_VERSION >= 3000 && CUDART_VERSION < 3010\n -- not visible from runtime API < 3.1\n eccEnabled = False,\n#endif\n#if CUDART_VERSION >= 4000\n asyncEngineCount = ae,\n cacheMemL2 = l2,\n maxThreadsPerMultiProcessor = tm,\n memBusWidth = mw,\n memClockRate = mc,\n tccDriverEnabled = tc,\n unifiedAddressing = ua,\n pciInfo = PCI pb pd pm,\n#endif\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\n{-# INLINEABLE choose #-}\nchoose :: DeviceProperties -> IO Device\nchoose !dev = resultIfOk =<< cudaChooseDevice dev\n\n{-# INLINE cudaChooseDevice #-}\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv*\n , withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n\n-- |\n-- Returns which device is currently being used\n--\n{-# INLINEABLE get #-}\nget :: IO Device\nget = resultIfOk =<< cudaGetDevice\n\n{-# INLINE cudaGetDevice #-}\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\n{-# INLINEABLE count #-}\ncount :: IO Int\ncount = resultIfOk =<< cudaGetDeviceCount\n\n{-# INLINE cudaGetDeviceCount #-}\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Return information about the selected compute device\n--\n{-# INLINEABLE props #-}\nprops :: Device -> IO DeviceProperties\nprops !n = resultIfOk =<< cudaGetDeviceProperties n\n\n{-# INLINE cudaGetDeviceProperties #-}\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek*\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set device to be used for GPU execution\n--\n{-# INLINEABLE set #-}\nset :: Device -> IO ()\nset !n = nothingIfOk =<< cudaSetDevice n\n\n{-# INLINE cudaSetDevice #-}\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set flags to be used for device executions\n--\n{-# INLINEABLE setFlags #-}\nsetFlags :: [DeviceFlag] -> IO ()\nsetFlags !f = nothingIfOk =<< cudaSetDeviceFlags (combineBitMasks f)\n\n{-# INLINE cudaSetDeviceFlags #-}\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\n{-# INLINEABLE setOrder #-}\nsetOrder :: [Device] -> IO ()\nsetOrder !l = nothingIfOk =<< cudaSetValidDevices l (length l)\n\n{-# INLINE cudaSetValidDevices #-}\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]'\n , `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\n-- |\n-- Block until the device has completed all preceding requested tasks. Returns\n-- an error if one of the tasks fails.\n--\n{-# INLINEABLE sync #-}\nsync :: IO ()\n#if CUDART_VERSION < 4000\n{-# INLINE cudaThreadSynchronize #-}\nsync = nothingIfOk =<< cudaThreadSynchronize\n{# fun cudaThreadSynchronize { } -> `Status' cToEnum #}\n#else\n{-# INLINE cudaDeviceSynchronize #-}\nsync = nothingIfOk =<< cudaDeviceSynchronize\n{# fun cudaDeviceSynchronize { } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Explicitly destroys and cleans up all runtime resources associated with the\n-- current device in the current process. Any subsequent API call will\n-- reinitialise the device.\n--\n-- Note that this function will reset the device immediately. It is the caller\u2019s\n-- responsibility to ensure that the device is not being accessed by any other\n-- host threads from the process when this function is called.\n--\n{-# INLINEABLE reset #-}\nreset :: IO ()\n#if CUDART_VERSION >= 4000\n{-# INLINE cudaDeviceReset #-}\nreset = nothingIfOk =<< cudaDeviceReset\n{# fun unsafe cudaDeviceReset { } -> `Status' cToEnum #}\n#else\n{-# INLINE cudaThreadExit #-}\nreset = nothingIfOk =<< cudaThreadExit\n{# fun unsafe cudaThreadExit { } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Peer Access\n--------------------------------------------------------------------------------\n\n-- |\n-- Possible option values for direct peer memory access\n--\ndata PeerFlag\ninstance Enum PeerFlag where\n toEnum x = case x of {}\n fromEnum x = case x of {}\n\n-- |\n-- Queries if the first device can directly access the memory of the second. If\n-- direct access is possible, it can then be enabled with 'add'. Requires\n-- cuda-4.0.\n--\n{-# INLINEABLE accessible #-}\naccessible :: Device -> Device -> IO Bool\n#if CUDART_VERSION < 4000\naccessible _ _ = requireSDK 4.0 \"accessible\"\n#else\naccessible !dev !peer = resultIfOk =<< cudaDeviceCanAccessPeer dev peer\n\n{-# INLINE cudaDeviceCanAccessPeer #-}\n{# fun unsafe cudaDeviceCanAccessPeer\n { alloca- `Bool' peekBool*\n , cIntConv `Device'\n , cIntConv `Device' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- If the devices of both the current and supplied contexts support unified\n-- addressing, then enable allocations in the supplied context to be accessible\n-- by the current context. Requires cuda-4.0.\n--\n{-# INLINEABLE add #-}\nadd :: Device -> [PeerFlag] -> IO ()\n#if CUDART_VERSION < 4000\nadd _ _ = requireSDK 4.0 \"add\"\n#else\nadd !dev !flags = nothingIfOk =<< cudaDeviceEnablePeerAccess dev flags\n\n{-# INLINE cudaDeviceEnablePeerAccess #-}\n{# fun unsafe cudaDeviceEnablePeerAccess\n { cIntConv `Device'\n , combineBitMasks `[PeerFlag]' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Disable direct memory access from the current context to the supplied\n-- context. Requires cuda-4.0.\n--\n{-# INLINEABLE remove #-}\nremove :: Device -> IO ()\n#if CUDART_VERSION < 4000\nremove _ = requireSDK 4.0 \"remove\"\n#else\nremove !dev = nothingIfOk =<< cudaDeviceDisablePeerAccess dev\n\n{-# INLINE cudaDeviceDisablePeerAccess #-}\n{# fun unsafe cudaDeviceDisablePeerAccess\n { cIntConv `Device' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Cache Configuration\n--------------------------------------------------------------------------------\n\n-- |\n-- Device limit flags\n--\n#if CUDART_VERSION < 3010\ndata Limit\n#else\n{# enum cudaLimit as Limit\n { underscoreToCase }\n with prefix=\"cudaLimit\" deriving (Eq, Show) #}\n#endif\n\n\n-- |\n-- Query compute 2.0 call stack limits. Requires cuda-3.1.\n--\n{-# INLINEABLE getLimit #-}\ngetLimit :: Limit -> IO Int\n#if CUDART_VERSION < 3010\ngetLimit _ = requireSDK 3.1 \"getLimit\"\n#elif CUDART_VERSION < 4000\ngetLimit !l = resultIfOk =<< cudaThreadGetLimit l\n\n{-# INLINE cudaThreadGetLimit #-}\n{# fun unsafe cudaThreadGetLimit\n { alloca- `Int' peekIntConv*\n , cFromEnum `Limit' } -> `Status' cToEnum #}\n#else\ngetLimit !l = resultIfOk =<< cudaDeviceGetLimit l\n\n{-# INLINE cudaDeviceGetLimit #-}\n{# fun unsafe cudaDeviceGetLimit\n { alloca- `Int' peekIntConv*\n , cFromEnum `Limit' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Set compute 2.0 call stack limits. Requires cuda-3.1.\n--\n{-# INLINEABLE setLimit #-}\nsetLimit :: Limit -> Int -> IO ()\n#if CUDART_VERSION < 3010\nsetLimit _ _ = requireSDK 3.1 \"setLimit\"\n#elif CUDART_VERSION < 4000\nsetLimit !l !n = nothingIfOk =<< cudaThreadSetLimit l n\n\n{-# INLINE cudaThreadSetLimit #-}\n{# fun unsafe cudaThreadSetLimit\n { cFromEnum `Limit'\n , cIntConv `Int' } -> `Status' cToEnum #}\n#else\nsetLimit !l !n = nothingIfOk =<< cudaDeviceSetLimit l n\n\n{-# INLINE cudaDeviceSetLimit #-}\n{# fun unsafe cudaDeviceSetLimit\n { cFromEnum `Limit'\n , cIntConv `Int' } -> `Status' cToEnum #}\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e0f6197868d470e5bf9a4b5d9c7909a6e3cd2088","subject":"Index","message":"Index\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Index.chs","new_file":"src\/haskell\/Data\/HGit2\/Index.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Index where\n\nimport Data.Bits\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Data.Maybe()\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nnewtype Index = Index CPtr\nnewtype IndexEntry = IndexEntry CPtr\nnewtype IndexEntryUnMerged = IndexEntryUnMerged CPtr\n\ninstance CWrapper Index where\n unwrap (Index i) = i\n\ninstance CWrapper IndexEntry where\n unwrap (IndexEntry ie) = ie\n\ninstance CWrapper IndexEntryUnMerged where\n unwrap (IndexEntryUnMerged ieu) = ieu\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 -> IOEitherErr Index\nopenIndex path =\n withCString path $ \\pth ->\n callPeek Index (\\out -> {#call git_index_open#} out pth)\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 ifp) =\n withForeignPtr ifp $ {#call git_index_clear#}\n\n-- | Update the contents of an existing index object in memory by reading from\n-- the hard disk.\nreadIndex :: Index -> IOCanFail\nreadIndex (Index ifp) =\n withForeignPtr ifp $ \\i ->\n retMaybe =<< {#call git_index_read#} i\n\n-- | Write an existing index object from memory back to disk using an atomic\n-- file lock.\nwriteIndex :: Index -> IOCanFail\nwriteIndex (Index ifp) =\n withForeignPtr ifp $ \\i ->\n retMaybe =<< {#call git_index_write#} i\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 ifp) path =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\path' -> do\n res <- {#call git_index_find#} idx path'\n return $ if res >= 0\n then Just $ fromIntegral res\n else Nothing\n\n-- | Remove all entries with equal path except last added\nuniqIndex :: Index -> IO ()\nuniqIndex (Index ifp) =\n withForeignPtr ifp $ {#call git_index_uniq#}\n\n-- | Add or update an index entry from a file in disk\naddIndex :: Index -> String -> Int -> IO (Maybe GitError)\naddIndex (Index ifp) path stage =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\pth ->\n retMaybe =<< {#call git_index_add#} idx pth (fromIntegral stage)\n\n-- | Add or update an index entry from an in-memory struct\naddIndex2 :: Index -> IndexEntry -> IO (Maybe GitError)\naddIndex2 (Index ifp) (IndexEntry efp) =\n withForeignPtr ifp $ \\idx ->\n withForeignPtr efp $ \\ie ->\n retMaybe =<< {#call git_index_add2#} idx ie\n\n-- | Add (append) an index entry from a file in disk\nappendIndex :: Index -> String -> Int -> IO (Maybe GitError)\nappendIndex (Index ifp) path stage =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\pth ->\n retMaybe =<< {#call git_index_append#} idx pth (fromIntegral stage)\n\n-- | Add (append) an index entry from an in-memory struct\nappendIndex2 :: Index -> IndexEntry -> IO (Maybe GitError)\nappendIndex2 (Index ifp) (IndexEntry efp) =\n withForeignPtr ifp $ \\idx ->\n withForeignPtr efp $ \\ie ->\n retMaybe =<< {#call git_index_append2#} idx ie\n\n-- | Remove an entry from the index\nremove :: Index -> Int -> IO (Maybe GitError)\nremove (Index ifp) n =\n withForeignPtr ifp $ \\idx ->\n retMaybe =<< {#call git_index_remove#} idx (fromIntegral n)\n\n-- | Get a pointer to one of the entries in the index\ngetIndex :: Index -> Int -> IO (Maybe IndexEntry)\ngetIndex (Index ifp) n =\n withForeignPtr ifp $ \\idx -> do\n res <- {#call git_index_get#} idx (fromIntegral n)\n retRes IndexEntry =<< mkFPtr res\n\n-- | Get the count of entries currently in the index\nentryCount :: Index -> IO Int\nentryCount (Index ifp) =\n withForeignPtr ifp $ retNum . {#call git_index_entrycount#}\n\n-- | Get the count of unmerged entries currently in the index\nentryCountUnMerged :: Index -> IO Int\nentryCountUnMerged (Index ifp) =\n withForeignPtr ifp $ retNum . {#call git_index_entrycount_unmerged#}\n\nretIEU :: Ptr () -> IO (Maybe IndexEntryUnMerged)\nretIEU ptr = retRes IndexEntryUnMerged =<< mkFPtr ptr\n\n-- | Get an unmerged entry from the index.\nunmergedByPath :: Index -> String -> IO (Maybe IndexEntryUnMerged)\nunmergedByPath (Index ifp) path =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\pth ->\n retIEU =<< {#call git_index_get_unmerged_bypath#} idx pth\n\n-- | Get an unmerged entry from the index.\nunmergedByIndex :: Index -> Int -> IO (Maybe IndexEntryUnMerged)\nunmergedByIndex (Index ifp) n =\n withForeignPtr ifp $ \\idx ->\n retIEU =<< {#call git_index_get_unmerged_byindex#} idx (fromIntegral n)\n\n-- | Return the stage number from a git index entry\nentryStage :: IndexEntry -> IO Int\nentryStage (IndexEntry ifp) =\n withForeignPtr ifp $ retNum . {#call git_index_entry_stage#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Index where\n\nimport Data.Bits\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Data.Maybe()\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nnewtype Index = Index CPtr\nnewtype IndexEntry = IndexEntry CPtr\nnewtype IndexEntryUnMerged = IndexEntryUnMerged CPtr\n\ninstance CWrapper Index where\n unwrap (Index i) = i\n\ninstance CWrapper IndexEntry where\n unwrap (IndexEntry ie) = ie\n\ninstance CWrapper IndexEntryUnMerged where\n unwrap (IndexEntryUnMerged ieu) = ieu\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 -> IOEitherErr Index\nopenIndex path = withCString path $ \\pth ->\n callPeek Index (\\out -> {#call git_index_open#} out pth)\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 ifp) =\n withForeignPtr ifp $ {#call git_index_clear#}\n\n-- | Update the contents of an existing index object in memory by reading from\n-- the hard disk.\nreadIndex :: Index -> IOCanFail\nreadIndex = undefined -- callRetMaybe {#call git_index_read#}\n\n-- | Write an existing index object from memory back to disk using an atomic\n-- file lock.\nwriteIndex :: Index -> IOCanFail\nwriteIndex = undefined -- callRetMaybe {#call git_index_write#}\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 ifp) path =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\path' -> do\n res <- {#call git_index_find#} idx path'\n return $ if res >= 0\n then Just $ fromIntegral res\n else Nothing\n\n-- | Remove all entries with equal path except last added\nuniqIndex :: Index -> IO ()\nuniqIndex (Index ifp) =\n withForeignPtr ifp $ {#call git_index_uniq#}\n\n-- | Add or update an index entry from a file in disk\naddIndex :: Index -> String -> Int -> IO (Maybe GitError)\naddIndex (Index ifp) path stage =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\pth ->\n retMaybe =<< {#call git_index_add#} idx pth (fromIntegral stage)\n\n-- | Add or update an index entry from an in-memory struct\naddIndex2 :: Index -> IndexEntry -> IO (Maybe GitError)\naddIndex2 (Index ifp) (IndexEntry efp) =\n withForeignPtr ifp $ \\idx ->\n withForeignPtr efp $ \\ie ->\n retMaybe =<< {#call git_index_add2#} idx ie\n\n-- | Add (append) an index entry from a file in disk\nappendIndex :: Index -> String -> Int -> IO (Maybe GitError)\nappendIndex (Index ifp) path stage =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\pth ->\n retMaybe =<< {#call git_index_append#} idx pth (fromIntegral stage)\n\n-- | Add (append) an index entry from an in-memory struct\nappendIndex2 :: Index -> IndexEntry -> IO (Maybe GitError)\nappendIndex2 (Index ifp) (IndexEntry efp) =\n withForeignPtr ifp $ \\idx ->\n withForeignPtr efp $ \\ie ->\n retMaybe =<< {#call git_index_append2#} idx ie\n\n-- | Remove an entry from the index\nremove :: Index -> Int -> IO (Maybe GitError)\nremove (Index ifp) n =\n withForeignPtr ifp $ \\idx ->\n retMaybe =<< {#call git_index_remove#} idx (fromIntegral n)\n\n-- | Get a pointer to one of the entries in the index\ngetIndex :: Index -> Int -> IO (Maybe IndexEntry)\ngetIndex (Index ifp) n =\n withForeignPtr ifp $ \\idx ->\n undefined\n {- retRes IndexEntry =<< {#call git_index_get#} idx (fromIntegral n)-}\n\n-- | Get the count of entries currently in the index\nentryCount :: Index -> IO Int\nentryCount = undefined -- callRetNum {#call git_index_entrycount#}\n\n-- | Get the count of unmerged entries currently in the index\nentryCountUnMerged :: Index -> IO Int\nentryCountUnMerged = undefined -- callRetNum {#call git_index_entrycount_unmerged#}\n\nretIEU :: CPtr -> IO (Maybe IndexEntryUnMerged)\nretIEU = undefined -- retRes IndexEntryUnMerged\n\n-- | Get an unmerged entry from the index.\nunmergedByPath :: Index -> String -> IO (Maybe IndexEntryUnMerged)\nunmergedByPath (Index ifp) path =\n withForeignPtr ifp $ \\idx ->\n withCString path $ \\pth ->\n undefined\n {- retIEU =<< {#call git_index_get_unmerged_bypath#} idx pth-}\n\n-- | Get an unmerged entry from the index.\nunmergedByIndex :: Index -> Int -> IO (Maybe IndexEntryUnMerged)\nunmergedByIndex (Index ifp) n =\n withForeignPtr ifp $ \\idx ->\n undefined -- retIEU =<< {#call git_index_get_unmerged_byindex#} idx (fromIntegral n)\n\n-- | Return the stage number from a git index entry\nentryStage :: IndexEntry -> IO Int\nentryStage = undefined -- callRetNum {#call git_index_entry_stage#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"470c3b2940d886bf6261830da8172357b3cf9d74","subject":"use stronger types for convertTo. Add YUV support.","message":"use stronger types for convertTo. Add YUV support.\n","repos":"aleator\/CV,aleator\/CV,TomMD\/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, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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 -- | 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 :: 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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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":"f3d315aa9deca211f890d36e486d4a32c8495795","subject":"fix instance Control.DeepSeq.NFData BDD for GHC 7.10 with deepseq >= 1.4","message":"fix instance Control.DeepSeq.NFData BDD for GHC 7.10 with deepseq >= 1.4\n","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, rnf )\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 where\n rnf x = seq x ()\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 ifthenelse 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 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 ifthenelse 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":"c80452dd7fe34a687c9dd8c54868eb8ed84ad6d3","subject":"commsec-test: fixup interopTest to build against cipher-aes-0.2.3","message":"commsec-test: fixup interopTest to build against cipher-aes-0.2.3\n","repos":"GaloisInc\/ivory-tower-stm32,GaloisInc\/ivory-tower-stm32,GaloisInc\/ivory-tower-stm32","old_file":"apps\/commsec-test\/interopTest.chs","new_file":"apps\/commsec-test\/interopTest.chs","new_contents":"{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls #-}\n\n{- interopTest.hs\n - This interoperability test is not ment to replace KATs and other\n - validation techniques that should be applied prior to fielding of the\n - associated AES-GCM code and 'commsec' encapsulation.\n -\n - However, this test routine does serve to demonstrate interoperability\n - with a completely separate implementation of AES that, in at least one\n - version, was shown to be correct against a large set of KATs.\n -\n - Function: Test: Notes:\n - securePkg_init correct keyExpand implicit\n - securePkg_zero nada\n - securePkg_enc_in_place correctness interop\n - securePkg_dec correctness interop\n - securePkg_enc correctness interop\n -}\nmodule Main where\n\nimport Control.Monad\nimport Data.Word\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Storable\nimport Foreign.Marshal (allocaBytes)\nimport Foreign.Marshal.Utils (copyBytes)\nimport Foreign.Marshal.Alloc (mallocBytes)\nimport Test.QuickCheck.Arbitrary\nimport Test.QuickCheck.Monadic\nimport Test.QuickCheck\n\nimport qualified Data.ByteString as B\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Internal as BI\nimport qualified Data.ByteString.Unsafe as BC\n\nimport Crypto.Cipher.AES -- Vincent's GCM routine\nimport Crypto.Cipher.Types\nimport Control.Concurrent.MVar\nimport Data.Serialize\n\nimport Debug.Trace\n\n#include \"aeslib\/commsec.h\"\n\n----------------------------------------------------------------------\n-- Foreign import the securePkg_* calls which should be used\n-- by HACMS\/SMACCMS\n\n-- If this were production code you would want to track the SecureContext\n-- being zeroed and throw a run-time error when using a zeroed Ctx.\nnewtype SecureContext = SCtx (ForeignPtr Ctx)\n\ndata Ctx\n\nnewtype BaseId = BaseId Word32\n deriving (Eq, Ord, Show)\n\ninstance Storable BaseId where\n sizeOf ~(BaseId x) = sizeOf x\n peek = fmap BaseId . peek . castPtr\n poke ptr (BaseId x) = poke (castPtr ptr) x\n alignment ~(BaseId x) = alignment x\n\ninstance Arbitrary BaseId where\n arbitrary = (BaseId . (`rem` 16) . abs) `fmap` arbitrary\n\ninstance Arbitrary ByteString where\n arbitrary = do\n len0 <- arbitrary\n let len = abs len0 `rem` 128\n B.pack `fmap` replicateM len arbitrary\n\ninstance Serialize BaseId where\n get = BaseId `fmap` getWord32be\n put (BaseId x) = putWord32be x\n\nforeign import ccall \"securePkg_size_of_message\"\n c_securePkg_size_of_message :: CInt -> CInt\n\nsecPkg_size_of_message :: Int -> Int\nsecPkg_size_of_message =\n fromIntegral . c_securePkg_size_of_message . fromIntegral\n\nforeign import ccall \"securePkg_size_of_package\"\n c_securePkg_size_of_package :: CInt -> CInt\nsecPkg_size_of_package :: Int -> Int\nsecPkg_size_of_package =\n fromIntegral . c_securePkg_size_of_package . fromIntegral\n\nforeign import ccall \"securePkg_init\"\n c_securePkg_init :: Ptr Ctx -> BaseId ->\n Word32 -> Ptr Word8 -> -- Decrypt Key\n Word32 -> Ptr Word8 -> -- Encrypt Key\n IO Word32\n\nsecPkgInit :: BaseId -> Word32 -> ByteString -> Word32 -> ByteString\n -> IO SecureContext\nsecPkgInit bid dsalt dkey esalt ekey = do\n -- FIXME sizeof is giving bad values!\n fptr <- mallocForeignPtrBytes ({#sizeof commsec_ctx#} + 10000)\n b <- withForeignPtr fptr $ \\ctx ->\n BC.unsafeUseAsCString dkey $ \\ptrD ->\n BC.unsafeUseAsCString ekey $ \\ptrE ->\n c_securePkg_init ctx bid dsalt (castPtr ptrD) esalt (castPtr ptrE)\n if b == 0 then return (SCtx fptr) else error \"secPkgInit failed\"\n\nforeign import ccall \"securePkg_zero\"\n c_securePkg_zero :: Ptr Ctx -> IO ()\n\nsecPkgZero :: SecureContext -> IO ()\nsecPkgZero (SCtx ptr) = withForeignPtr ptr c_securePkg_zero\n\nforeign import ccall \"securePkg_enc_in_place\"\n c_securePkg_enc_in_place :: Ptr Ctx -> -- Cipher ctx\n Ptr Word8 -> -- Buffer\n Word32 -> -- Msg start index\n Word32 -> -- Msg Length\n IO Word32\n\n-- Encrypting data in place requires room for the header (8 bytes)\n-- and room for the trailing tag (8 bytes)\nsecPkgEncInPlace :: SecureContext -> ByteString -> IO (Maybe ByteString)\nsecPkgEncInPlace (SCtx c) pt = do\n let pkgSz = secPkg_size_of_package . B.length $ pt\n pkg <- BI.mallocByteString pkgSz\n b <- withForeignPtr pkg $ \\ptrCT ->\n BC.unsafeUseAsCStringLen pt $ \\(ptrPT,lenPT) -> do\n copyBytes (castPtr ptrCT `plusPtr` 8) ptrPT lenPT\n withForeignPtr c $ \\ctxPtr ->\n c_securePkg_enc_in_place\n ctxPtr\n (castPtr ptrCT)\n 8\n (fromIntegral lenPT)\n let b = 0\n return (if b == 0 then Just (BI.fromForeignPtr pkg 0 pkgSz)\n else Nothing)\n\nforeign import ccall \"securePkg_enc\"\n c_securePkg_enc :: Ptr Ctx -> -- Cipher ctx\n Ptr Word8 -> -- PT Buffer (in) CT Buffer (out)\n Word32 -> -- PT Len\n Ptr Word8 -> -- Header Buffer (8 bytes, min)\n Ptr Word8 -> -- Tag buffer (8 bytes, min)\n IO Word32\n\n-- Encrypting data in place requires room for the header (8 bytes)\n-- and room for the trailing tag (8 bytes)\nsecPkgEnc :: SecureContext -> ByteString\n -> IO (Maybe (ByteString,ByteString,ByteString))\nsecPkgEnc (SCtx c) pt = do\n let tagLen = 8 -- C and IVORY could should use the C #define\n hdrLen = 8\n lenCT = B.length pt\n ct <- BI.mallocByteString lenCT\n hdr <- BI.mallocByteString hdrLen\n tag <- BI.mallocByteString tagLen\n b <- withForeignPtr ct $ \\ptrCT ->\n BC.unsafeUseAsCStringLen pt $ \\(ptrPT,lenPT) ->\n withForeignPtr tag $ \\ptrTag ->\n withForeignPtr hdr $ \\ptrHdr ->\n withForeignPtr c $ \\ctxPtr -> do\n copyBytes (castPtr ptrCT) (castPtr ptrPT) lenPT\n c_securePkg_enc ctxPtr ptrCT (fromIntegral lenPT) ptrHdr ptrTag\n let tagBS = BI.fromForeignPtr tag 0 tagLen\n hdrBS = BI.fromForeignPtr hdr 0 hdrLen\n ctBS = BI.fromForeignPtr ct 0 lenCT\n return (if b == 0 then Just (hdrBS,ctBS,tagBS) else Nothing)\n\nforeign import ccall \"securePkg_dec\"\n c_securePkg_dec :: Ptr Ctx ->\n Ptr Word8 ->\n Word32 ->\n IO Word32\n\nsecPkgDec :: SecureContext -> ByteString -> IO (Maybe ByteString)\nsecPkgDec (SCtx c) ct =\n BC.unsafeUseAsCStringLen ct $ \\(ptrPKG,lenPKG) -> do\n let lenW32 = fromIntegral lenPKG\n lenPT = secPkg_size_of_message lenPKG\n fpPT <- BI.mallocByteString lenPT\n b <- allocaBytes lenPKG $ \\tmpPtr -> do\n copyBytes tmpPtr ptrPKG lenPKG\n withForeignPtr c $ \\ctxPtr -> do\n res <- c_securePkg_dec ctxPtr (castPtr tmpPtr) lenW32\n withForeignPtr fpPT $ \\ptrPT -> do\n copyBytes ptrPT (tmpPtr `plusPtr` 8) lenPT\n return res\n return (if b == 0 then Just (BI.fromForeignPtr fpPT 0 lenPT)\n else Nothing)\n\n----------------------------------------------------------------------\n-- Haskell re-implementation of the SecurePkg format. This code uses\n-- a completely separate C AES routine. This is NOT a reference\n-- in that it is easy to read, it is simply a re-implementation which\n-- serves as a light sanity check on the functionallity of the prior\n-- implementation.\n\n-- Key, salt, station ID, counter\ntype OutContext = (AES,Word32,BaseId,Word32)\ntype InContext = (AES,Word32,[(BaseId,Word32)])\ndata SecureContext_HS = SC { inbound :: InContext\n , outbound :: OutContext }\ntype ReferenceContext = MVar SecureContext_HS\n\nrefPkg :: OutContext -> ByteString\n -> (OutContext, Maybe (ByteString,ByteString,ByteString))\nrefPkg ctx@(key,salt,bid,ctr) pt\n | ctr == maxBound = (ctx, Nothing)\n | otherwise =\n let iv = runPut (putWord32be salt >> put bid >> putWord32be ctr)\n new = (key,salt,bid,ctr+1)\n aad = B.empty\n (ct, AuthTag tag) = encryptGCM key iv aad pt\n tagLen = 8\n header = runPut (put bid >> putWord32be ctr)\n in (new, Just (header, ct, B.take tagLen tag))\n\nrefDec :: InContext -> ByteString -> (InContext, Maybe ByteString)\nrefDec old@(key,salt,bidList) pkg =\n let aad = B.empty\n -- Get the iv out of the send package.\n Right (bid,newCtr,ct,tag) =\n runGet (do bid' <- get\n newCtr' <- getWord32be\n pt' <- getByteString . (subtract 8) =<< remaining\n tag' <- getByteString =<< remaining\n return (bid',newCtr',pt',tag')\n ) pkg\n -- Serialize the salt I have with the sent baseID and updated counter.\n iv = runPut (putWord32be salt >> put bid >> putWord32be newCtr)\n -- Replace the BaseID\/Counter pair in the list with the updated pair.\n newBids = (bid,newCtr) : filter ((\/= bid) . fst) bidList\n new = (key, salt, newBids)\n -- Decrypt the message. I get the sent message and auth. tag, if all\n -- goes well.\n (pt, AuthTag decTag) = decryptGCM key iv aad ct\n in case lookup bid bidList of\n Nothing -> (old, Nothing)\n Just cnt\n -- Counter is too high or old.\n | cnt == maxBound || cnt >= newCtr -> (old,Nothing)\n -- Return my updated inContext with the decrypted message.\n | B.take (B.length tag) decTag == tag -> (new,Just pt)\n | otherwise -> (old,Nothing)\n\n\nrefInitOutContext :: ByteString -> Word32 -> BaseId -> OutContext\nrefInitOutContext key salt bid = (initAES key, salt, bid, 1)\n\nrefInitInContext :: ByteString -> Word32 -> InContext\nrefInitInContext key salt\n = (initAES key, salt, zip (map BaseId [0..]) (replicate 16 0))\n\nsecPkgInit_HS :: BaseId -> Word32 -> ByteString -> Word32 -> ByteString\n -> IO ReferenceContext\nsecPkgInit_HS b dsalt dkey esalt ekey\n = newMVar (SC (refInitInContext dkey dsalt)\n (refInitOutContext ekey esalt b))\n\nsecPkgEncInPlace_HS :: ReferenceContext -> ByteString -> IO (Maybe ByteString)\nsecPkgEncInPlace_HS rc pt = do\n r <- secPkgEnc_HS rc pt\n case r of\n Just (a,b,c) -> return (Just (B.concat [a,b,c]))\n Nothing -> return Nothing\n\n----------------------------------------------------------------------\n-- Lifting the reference implementation to match the API\nsecPkgEnc_HS :: ReferenceContext -> ByteString\n -> IO (Maybe (ByteString,ByteString,ByteString))\nsecPkgEnc_HS rc pt =\n modifyMVar rc $ \\(SC _in outbound) ->\n let (newOut,res) = refPkg outbound pt in do\n return (SC _in newOut,res)\n\nsecPkgDec_HS :: ReferenceContext -> ByteString -> IO (Maybe ByteString)\nsecPkgDec_HS rc pkg =\n modifyMVar rc $ \\(SC inbound _out) ->\n let (newIn, res) = refDec inbound pkg in return (SC newIn _out, res)\n\n-----------------------------------------------------------------------\n-- Quickcheck tests showing compatability of the two implementations.\n\n-- FIXME more tests, use monadic guard to not test trivial pt==null case.\n\nprop_encEq :: ByteString -> ByteString -> ByteString -> Word32 -> Word32\n -> Word32 -> Property\nprop_encEq dKeySmall eKeySmall ptSmall dsalt esalt ctr\n = monadicIO $ do\n let dkey = B.take 16 (B.append dKeySmall (B.replicate 16 0))\n let ekey = B.take 16 (B.append eKeySmall (B.replicate 16 0))\n let pt = B.take (max (B.length ptSmall) 1)\n (B.append ptSmall (B.replicate 1 1))\n sctx <- run $ secPkgInit (BaseId 0) dsalt dkey esalt ekey\n rctx <- run $ secPkgInit_HS (BaseId 0) dsalt dkey esalt ekey\n rPKG <- run $ secPkgEnc_HS rctx pt\n sPKG <- run $ secPkgEnc sctx pt\n assert $ sPKG == rPKG\n\nprop_decCompat :: ByteString -> ByteString -> ByteString -> Word32\n -> Word32 -> Word32 -> Property\nprop_decCompat dKeySmall eKeySmall ptSmall dsalt esalt ctr\n = monadicIO $ do\n let dkey = B.take 16 (B.append dKeySmall (B.replicate 16 0))\n let ekey = B.take 16 (B.append eKeySmall (B.replicate 16 0))\n let pt = B.take (max (B.length ptSmall) 1)\n (B.append ptSmall (B.replicate 1 1))\n sctx <- run $ secPkgInit (BaseId 0) dsalt dkey esalt ekey\n rctx <- run $ secPkgInit_HS (BaseId 0) dsalt dkey esalt ekey\n Just rPKG <- run $ secPkgEncInPlace_HS rctx pt\n Just sPKG <- run $ secPkgEncInPlace sctx pt\n dec1 <- run $ secPkgDec_HS rctx sPKG\n dec2 <- run $ secPkgDec sctx rPKG\n assert $ sPKG == rPKG && dec1 == dec2\n\nprop_decFail :: ByteString -> ByteString -> ByteString -> Word32 -> Word32\n -> Word32 -> Property\nprop_decFail dKeySmall eKeySmall ptSmall dsalt esalt ctr\n = monadicIO $ do\n let dkey = B.take 16 (B.append dKeySmall (B.replicate 16 0))\n let ekey = B.take 16 (B.append eKeySmall (B.replicate 16 0))\n let pt = B.take (max (B.length ptSmall) 1)\n (B.append ptSmall (B.replicate 1 1))\n sctx <- run $ secPkgInit (BaseId 0) dsalt dkey esalt ekey\n rctx <- run $ secPkgInit_HS (BaseId 0) dsalt dkey esalt ekey\n Just sPKG0 <- run $ secPkgEncInPlace sctx pt\n i <- pick $ fmap ((`rem` B.length sPKG0) . abs) arbitrary\n let sPKG = B.pack . incIth i . B.unpack $ sPKG0\n dec1 <- run $ secPkgDec_HS rctx sPKG\n dec2 <- run $ secPkgDec sctx sPKG\n assert $ dec1 == dec2 && dec1 == Nothing\n where\n incIth i ls = take i ls ++ [(ls !! i) + 1] ++ drop (i+1) ls\n\ndata Test = forall a. Testable a => T a String\n\ntests = [T prop_encEq \"prop_encEq\"\n ,T prop_decFail \"prop_decFail\"\n ,T prop_decCompat \"prop_decCompat\"\n ]\n\nrunTest :: Test -> IO ()\nrunTest (T a s) = putStrLn (\"Testing: \" ++ s) >> quickCheck a\n\nrunTests :: [Test] -> IO ()\nrunTests = mapM_ runTest\n\nmain :: IO ()\nmain = runTests tests\n{-\nmain = do\n putStrLn \"Notice the commsec_ctx structure is ~9k, depending on configuration. However, c2hs believes it is smaller (see the below number) so we manually ad 10K to make this test work. This is a definite FIXME.\"\n print {#sizeof commsec_ctx#}\n let key = B.replicate 16 0\n ctx <- secPkgInit (BaseId 0) 1 key 1 key\n ctx2 <- secPkgInit_HS (BaseId 0) 1 key 1 key\n Just pkg1 <- secPkgEncInPlace_HS ctx2 (B.pack [1..100])\n Just pkg2 <- secPkgEncInPlace ctx (B.pack [1..100])\n Just pkg3 <- secPkgEncInPlace ctx (B.pack [1..100])\n print pkg1\n print pkg2\n print pkg3\n secPkgDec_HS ctx2 pkg1 >>= print\n secPkgDec ctx pkg2 >>= print\n secPkgDec ctx pkg3 >>= print\n return ()\n-}\n","old_contents":"{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls #-}\n\n{- interopTest.hs\n - This interoperability test is not ment to replace KATs and other\n - validation techniques that should be applied prior to fielding of the\n - associated AES-GCM code and 'commsec' encapsulation.\n -\n - However, this test routine does serve to demonstrate interoperability\n - with a completely separate implementation of AES that, in at least one\n - version, was shown to be correct against a large set of KATs.\n -\n - Function: Test: Notes:\n - securePkg_init correct keyExpand implicit\n - securePkg_zero nada\n - securePkg_enc_in_place correctness interop\n - securePkg_dec correctness interop\n - securePkg_enc correctness interop\n -}\nmodule Main where\n\nimport Control.Monad\nimport Data.Word\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Storable\nimport Foreign.Marshal (allocaBytes)\nimport Foreign.Marshal.Utils (copyBytes)\nimport Foreign.Marshal.Alloc (mallocBytes)\nimport Test.QuickCheck.Arbitrary\nimport Test.QuickCheck.Monadic\nimport Test.QuickCheck\n\nimport qualified Data.ByteString as B\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Internal as BI\nimport qualified Data.ByteString.Unsafe as BC\n\nimport Crypto.Cipher.AES -- Vincent's GCM routine\nimport Control.Concurrent.MVar\nimport Data.Serialize\n\nimport Debug.Trace\n\n#include \"aeslib\/commsec.h\"\n\n----------------------------------------------------------------------\n-- Foreign import the securePkg_* calls which should be used\n-- by HACMS\/SMACCMS\n\n-- If this were production code you would want to track the SecureContext\n-- being zeroed and throw a run-time error when using a zeroed Ctx.\nnewtype SecureContext = SCtx (ForeignPtr Ctx)\n\ndata Ctx\n\nnewtype BaseId = BaseId Word32\n deriving (Eq, Ord, Show)\n\ninstance Storable BaseId where\n sizeOf ~(BaseId x) = sizeOf x\n peek = fmap BaseId . peek . castPtr\n poke ptr (BaseId x) = poke (castPtr ptr) x\n alignment ~(BaseId x) = alignment x\n\ninstance Arbitrary BaseId where\n arbitrary = (BaseId . (`rem` 16) . abs) `fmap` arbitrary\n\ninstance Arbitrary ByteString where\n arbitrary = do\n len0 <- arbitrary\n let len = abs len0 `rem` 128\n B.pack `fmap` replicateM len arbitrary\n\ninstance Serialize BaseId where\n get = BaseId `fmap` getWord32be\n put (BaseId x) = putWord32be x\n\nforeign import ccall \"securePkg_size_of_message\"\n c_securePkg_size_of_message :: CInt -> CInt\n\nsecPkg_size_of_message :: Int -> Int\nsecPkg_size_of_message =\n fromIntegral . c_securePkg_size_of_message . fromIntegral\n\nforeign import ccall \"securePkg_size_of_package\"\n c_securePkg_size_of_package :: CInt -> CInt\nsecPkg_size_of_package :: Int -> Int\nsecPkg_size_of_package =\n fromIntegral . c_securePkg_size_of_package . fromIntegral\n\nforeign import ccall \"securePkg_init\"\n c_securePkg_init :: Ptr Ctx -> BaseId ->\n Word32 -> Ptr Word8 -> -- Decrypt Key\n Word32 -> Ptr Word8 -> -- Encrypt Key\n IO Word32\n\nsecPkgInit :: BaseId -> Word32 -> ByteString -> Word32 -> ByteString\n -> IO SecureContext\nsecPkgInit bid dsalt dkey esalt ekey = do\n -- FIXME sizeof is giving bad values!\n fptr <- mallocForeignPtrBytes ({#sizeof commsec_ctx#} + 10000)\n b <- withForeignPtr fptr $ \\ctx ->\n BC.unsafeUseAsCString dkey $ \\ptrD ->\n BC.unsafeUseAsCString ekey $ \\ptrE ->\n c_securePkg_init ctx bid dsalt (castPtr ptrD) esalt (castPtr ptrE)\n if b == 0 then return (SCtx fptr) else error \"secPkgInit failed\"\n\nforeign import ccall \"securePkg_zero\"\n c_securePkg_zero :: Ptr Ctx -> IO ()\n\nsecPkgZero :: SecureContext -> IO ()\nsecPkgZero (SCtx ptr) = withForeignPtr ptr c_securePkg_zero\n\nforeign import ccall \"securePkg_enc_in_place\"\n c_securePkg_enc_in_place :: Ptr Ctx -> -- Cipher ctx\n Ptr Word8 -> -- Buffer\n Word32 -> -- Msg start index\n Word32 -> -- Msg Length\n IO Word32\n\n-- Encrypting data in place requires room for the header (8 bytes)\n-- and room for the trailing tag (8 bytes)\nsecPkgEncInPlace :: SecureContext -> ByteString -> IO (Maybe ByteString)\nsecPkgEncInPlace (SCtx c) pt = do\n let pkgSz = secPkg_size_of_package . B.length $ pt\n pkg <- BI.mallocByteString pkgSz\n b <- withForeignPtr pkg $ \\ptrCT ->\n BC.unsafeUseAsCStringLen pt $ \\(ptrPT,lenPT) -> do\n copyBytes (castPtr ptrCT `plusPtr` 8) ptrPT lenPT\n withForeignPtr c $ \\ctxPtr ->\n c_securePkg_enc_in_place\n ctxPtr\n (castPtr ptrCT)\n 8\n (fromIntegral lenPT)\n let b = 0\n return (if b == 0 then Just (BI.fromForeignPtr pkg 0 pkgSz)\n else Nothing)\n\nforeign import ccall \"securePkg_enc\"\n c_securePkg_enc :: Ptr Ctx -> -- Cipher ctx\n Ptr Word8 -> -- PT Buffer (in) CT Buffer (out)\n Word32 -> -- PT Len\n Ptr Word8 -> -- Header Buffer (8 bytes, min)\n Ptr Word8 -> -- Tag buffer (8 bytes, min)\n IO Word32\n\n-- Encrypting data in place requires room for the header (8 bytes)\n-- and room for the trailing tag (8 bytes)\nsecPkgEnc :: SecureContext -> ByteString\n -> IO (Maybe (ByteString,ByteString,ByteString))\nsecPkgEnc (SCtx c) pt = do\n let tagLen = 8 -- C and IVORY could should use the C #define\n hdrLen = 8\n lenCT = B.length pt\n ct <- BI.mallocByteString lenCT\n hdr <- BI.mallocByteString hdrLen\n tag <- BI.mallocByteString tagLen\n b <- withForeignPtr ct $ \\ptrCT ->\n BC.unsafeUseAsCStringLen pt $ \\(ptrPT,lenPT) ->\n withForeignPtr tag $ \\ptrTag ->\n withForeignPtr hdr $ \\ptrHdr ->\n withForeignPtr c $ \\ctxPtr -> do\n copyBytes (castPtr ptrCT) (castPtr ptrPT) lenPT\n c_securePkg_enc ctxPtr ptrCT (fromIntegral lenPT) ptrHdr ptrTag\n let tagBS = BI.fromForeignPtr tag 0 tagLen\n hdrBS = BI.fromForeignPtr hdr 0 hdrLen\n ctBS = BI.fromForeignPtr ct 0 lenCT\n return (if b == 0 then Just (hdrBS,ctBS,tagBS) else Nothing)\n\nforeign import ccall \"securePkg_dec\"\n c_securePkg_dec :: Ptr Ctx ->\n Ptr Word8 ->\n Word32 ->\n IO Word32\n\nsecPkgDec :: SecureContext -> ByteString -> IO (Maybe ByteString)\nsecPkgDec (SCtx c) ct =\n BC.unsafeUseAsCStringLen ct $ \\(ptrPKG,lenPKG) -> do\n let lenW32 = fromIntegral lenPKG\n lenPT = secPkg_size_of_message lenPKG\n fpPT <- BI.mallocByteString lenPT\n b <- allocaBytes lenPKG $ \\tmpPtr -> do\n copyBytes tmpPtr ptrPKG lenPKG\n withForeignPtr c $ \\ctxPtr -> do\n res <- c_securePkg_dec ctxPtr (castPtr tmpPtr) lenW32\n withForeignPtr fpPT $ \\ptrPT -> do\n copyBytes ptrPT (tmpPtr `plusPtr` 8) lenPT\n return res\n return (if b == 0 then Just (BI.fromForeignPtr fpPT 0 lenPT)\n else Nothing)\n\n----------------------------------------------------------------------\n-- Haskell re-implementation of the SecurePkg format. This code uses\n-- a completely separate C AES routine. This is NOT a reference\n-- in that it is easy to read, it is simply a re-implementation which\n-- serves as a light sanity check on the functionallity of the prior\n-- implementation.\n\n-- Key, salt, station ID, counter\ntype OutContext = (Key,Word32,BaseId,Word32)\ntype InContext = (Key,Word32,[(BaseId,Word32)])\ndata SecureContext_HS = SC { inbound :: InContext\n , outbound :: OutContext }\ntype ReferenceContext = MVar SecureContext_HS\n\nrefPkg :: OutContext -> ByteString\n -> (OutContext, Maybe (ByteString,ByteString,ByteString))\nrefPkg ctx@(key,salt,bid,ctr) pt\n | ctr == maxBound = (ctx, Nothing)\n | otherwise =\n let iv = runPut (putWord32be salt >> put bid >> putWord32be ctr)\n new = (key,salt,bid,ctr+1)\n aad = B.empty\n (ct,tag) = encryptGCM key (IV iv) aad pt\n tagLen = 8\n header = runPut (put bid >> putWord32be ctr)\n in (new, Just (header, ct, B.take tagLen tag))\n\nrefDec :: InContext -> ByteString -> (InContext, Maybe ByteString)\nrefDec old@(key,salt,bidList) pkg =\n let iv = runPut (putWord32be salt >> put bid >> putWord32be newCtr)\n aad = B.empty\n Right (bid,newCtr,ct,tag) =\n runGet (do bid <- get\n newCtr <- getWord32be\n pt <- getByteString . (subtract 8) =<< remaining\n tag <- getByteString =<< remaining\n return (bid,newCtr,pt,tag)\n ) pkg\n newBids = (bid,newCtr) : filter ((\/= bid) . fst) bidList\n new = (key,salt,newBids)\n (pt,decTag) = decryptGCM key (IV iv) aad ct\n in case lookup bid bidList of\n Nothing -> (old, Nothing)\n Just cnt | cnt == maxBound || cnt >= newCtr -> (old,Nothing)\n | B.take (B.length tag) decTag == tag -> (new,Just pt)\n | otherwise -> (old,Nothing)\n\n\nrefInitOutContext :: ByteString -> Word32 -> BaseId -> OutContext\nrefInitOutContext key salt bid = (initKey key, salt, bid, 1)\n\nrefInitInContext :: ByteString -> Word32 -> InContext\nrefInitInContext key salt\n = (initKey key, salt, zip (map BaseId [0..]) (replicate 16 0))\n\nsecPkgInit_HS :: BaseId -> Word32 -> ByteString -> Word32 -> ByteString\n -> IO ReferenceContext\nsecPkgInit_HS b dsalt dkey esalt ekey\n = newMVar (SC (refInitInContext dkey dsalt)\n (refInitOutContext ekey esalt b))\n\nsecPkgEncInPlace_HS :: ReferenceContext -> ByteString -> IO (Maybe ByteString)\nsecPkgEncInPlace_HS rc pt = do\n r <- secPkgEnc_HS rc pt\n case r of\n Just (a,b,c) -> return (Just (B.concat [a,b,c]))\n Nothing -> return Nothing\n\n----------------------------------------------------------------------\n-- Lifting the reference implementation to match the API\nsecPkgEnc_HS :: ReferenceContext -> ByteString\n -> IO (Maybe (ByteString,ByteString,ByteString))\nsecPkgEnc_HS rc pt =\n modifyMVar rc $ \\(SC _in outbound) ->\n let (newOut,res) = refPkg outbound pt in do\n return (SC _in newOut,res)\n\nsecPkgDec_HS :: ReferenceContext -> ByteString -> IO (Maybe ByteString)\nsecPkgDec_HS rc pkg =\n modifyMVar rc $ \\(SC inbound _out) ->\n let (newIn, res) = refDec inbound pkg in return (SC newIn _out, res)\n\n-----------------------------------------------------------------------\n-- Quickcheck tests showing compatability of the two implementations.\n\n-- FIXME more tests, use monadic guard to not test trivial pt==null case.\n\nprop_encEq :: ByteString -> ByteString -> ByteString -> Word32 -> Word32\n -> Word32 -> Property\nprop_encEq dKeySmall eKeySmall ptSmall dsalt esalt ctr\n = monadicIO $ do\n let dkey = B.take 16 (B.append dKeySmall (B.replicate 16 0))\n let ekey = B.take 16 (B.append eKeySmall (B.replicate 16 0))\n let pt = B.take (max (B.length ptSmall) 1)\n (B.append ptSmall (B.replicate 1 1))\n sctx <- run $ secPkgInit (BaseId 0) dsalt dkey esalt ekey\n rctx <- run $ secPkgInit_HS (BaseId 0) dsalt dkey esalt ekey\n rPKG <- run $ secPkgEnc_HS rctx pt\n sPKG <- run $ secPkgEnc sctx pt\n assert $ sPKG == rPKG\n\nprop_decCompat :: ByteString -> ByteString -> ByteString -> Word32\n -> Word32 -> Word32 -> Property\nprop_decCompat dKeySmall eKeySmall ptSmall dsalt esalt ctr\n = monadicIO $ do\n let dkey = B.take 16 (B.append dKeySmall (B.replicate 16 0))\n let ekey = B.take 16 (B.append eKeySmall (B.replicate 16 0))\n let pt = B.take (max (B.length ptSmall) 1)\n (B.append ptSmall (B.replicate 1 1))\n sctx <- run $ secPkgInit (BaseId 0) dsalt dkey esalt ekey\n rctx <- run $ secPkgInit_HS (BaseId 0) dsalt dkey esalt ekey\n Just rPKG <- run $ secPkgEncInPlace_HS rctx pt\n Just sPKG <- run $ secPkgEncInPlace sctx pt\n dec1 <- run $ secPkgDec_HS rctx sPKG\n dec2 <- run $ secPkgDec sctx rPKG\n assert $ sPKG == rPKG && dec1 == dec2\n\nprop_decFail :: ByteString -> ByteString -> ByteString -> Word32 -> Word32\n -> Word32 -> Property\nprop_decFail dKeySmall eKeySmall ptSmall dsalt esalt ctr\n = monadicIO $ do\n let dkey = B.take 16 (B.append dKeySmall (B.replicate 16 0))\n let ekey = B.take 16 (B.append eKeySmall (B.replicate 16 0))\n let pt = B.take (max (B.length ptSmall) 1)\n (B.append ptSmall (B.replicate 1 1))\n sctx <- run $ secPkgInit (BaseId 0) dsalt dkey esalt ekey\n rctx <- run $ secPkgInit_HS (BaseId 0) dsalt dkey esalt ekey\n Just sPKG0 <- run $ secPkgEncInPlace sctx pt\n i <- pick $ fmap ((`rem` B.length sPKG0) . abs) arbitrary\n let sPKG = B.pack . incIth i . B.unpack $ sPKG0\n dec1 <- run $ secPkgDec_HS rctx sPKG\n dec2 <- run $ secPkgDec sctx sPKG\n assert $ dec1 == dec2 && dec1 == Nothing\n where\n incIth i ls = take i ls ++ [(ls !! i) + 1] ++ drop (i+1) ls\n\ndata Test = forall a. Testable a => T a String\n\ntests = [T prop_encEq \"prop_encEq\"\n ,T prop_decFail \"prop_decFail\"\n ,T prop_decCompat \"prop_decCompat\"\n ]\n\nrunTest :: Test -> IO ()\nrunTest (T a s) = putStrLn (\"Testing: \" ++ s) >> quickCheck a\n\nrunTests :: [Test] -> IO ()\nrunTests = mapM_ runTest\n\nmain :: IO ()\nmain = runTests tests\n{-\nmain = do\n putStrLn \"Notice the commsec_ctx structure is ~9k, depending on configuration. However, c2hs believes it is smaller (see the below number) so we manually ad 10K to make this test work. This is a definite FIXME.\"\n print {#sizeof commsec_ctx#}\n let key = B.replicate 16 0\n ctx <- secPkgInit (BaseId 0) 1 key 1 key\n ctx2 <- secPkgInit_HS (BaseId 0) 1 key 1 key\n Just pkg1 <- secPkgEncInPlace_HS ctx2 (B.pack [1..100])\n Just pkg2 <- secPkgEncInPlace ctx (B.pack [1..100])\n Just pkg3 <- secPkgEncInPlace ctx (B.pack [1..100])\n print pkg1\n print pkg2\n print pkg3\n secPkgDec_HS ctx2 pkg1 >>= print\n secPkgDec ctx pkg2 >>= print\n secPkgDec ctx pkg3 >>= print\n return ()\n-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3d1b9f18c90472f9795e3a23404a5d0b607fb409","subject":"storable instance for DevicePtr","message":"storable instance for DevicePtr\n\nIgnore-this: b5f768604b0ed1581e6f7f0408d1f761\n- to be used when setting function parameters\n\ndarcs-hash:20091210065234-9241b-d5cbb224cd1b05dae8ef6c1d2c5b5183c5021427.gz\n","repos":"mwu-tow\/cuda,phaazon\/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, withStream)\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 deriving (Show)\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. Note that since the amount of pageable\n-- memory is thusly reduced, overall system performance may suffer. This is best\n-- used sparingly to allocate staging areas for data exchange.\n--\nmallocHost :: [AllocFlag] -> Int -> IO (Either String (HostPtr a))\nmallocHost flags bytes =\n newHostPtr >>= \\hp -> withHostPtr hp $ \\p ->\n cuMemHostAlloc p bytes flags >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right hp\n Just err -> Left err\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 (Maybe String)\nfreeHost hp = withHostPtr hp $ \\p -> (nothingIfOk `fmap` 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 suitably aligned for any type, and is not cleared.\n--\nmalloc :: Int -> IO (Either String (DevicePtr a))\nmalloc bytes = resultIfOk `fmap` cuMemAlloc bytes\n\n{# fun unsafe cuMemAlloc\n { alloca- `DevicePtr a' dptr*\n , `Int' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peekIntConv\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO (Maybe String)\nfree dp = nothingIfOk `fmap` 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 (Maybe String)\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ = nothingIfOk `fmap` 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 (Maybe String)\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyDtoHAsync\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPoke x _ = nothingIfOk `fmap` 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 (Maybe String)\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n dopoke x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk `fmap` cuMemsetD8 dptr val n\n 2 -> nothingIfOk `fmap` cuMemsetD16 dptr val n\n 4 -> nothingIfOk `fmap` cuMemsetD32 dptr val n\n _ -> return $ Just \"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 (Either String (DevicePtr a))\ngetDevicePtr flags hptr = withHostPtr hptr $ \\hp -> (resultIfOk `fmap` 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 . peekIntConv\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, withStream)\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 deriving (Show)\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. Note that since the amount of pageable\n-- memory is thusly reduced, overall system performance may suffer. This is best\n-- used sparingly to allocate staging areas for data exchange.\n--\nmallocHost :: [AllocFlag] -> Int -> IO (Either String (HostPtr a))\nmallocHost flags bytes =\n newHostPtr >>= \\hp -> withHostPtr hp $ \\p ->\n cuMemHostAlloc p bytes flags >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right hp\n Just err -> Left err\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 (Maybe String)\nfreeHost hp = withHostPtr hp $ \\p -> (nothingIfOk `fmap` 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 suitably aligned for any type, and is not cleared.\n--\nmalloc :: Int -> IO (Either String (DevicePtr a))\nmalloc bytes = resultIfOk `fmap` cuMemAlloc bytes\n\n{# fun unsafe cuMemAlloc\n { alloca- `DevicePtr a' dptr*\n , `Int' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peekIntConv\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO (Maybe String)\nfree dp = nothingIfOk `fmap` 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 (Maybe String)\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ = nothingIfOk `fmap` 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 (Maybe String)\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPeek x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyDtoHAsync\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n doPoke x _ = nothingIfOk `fmap` 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 (Maybe String)\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO (Maybe String)\n dopoke x _ =\n nothingIfOk `fmap` case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) nullPtr\n Just st -> (withStream st $ \\s -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) s)\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int'\n , castPtr `Ptr 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 (Maybe String)\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk `fmap` cuMemsetD8 dptr val n\n 2 -> nothingIfOk `fmap` cuMemsetD16 dptr val n\n 4 -> nothingIfOk `fmap` cuMemsetD32 dptr val n\n _ -> return $ Just \"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 (Either String (DevicePtr a))\ngetDevicePtr flags hptr = withHostPtr hptr $ \\hp -> (resultIfOk `fmap` 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 . peekIntConv\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"45bc30c4bde0dc2b8df753065098b9cfbd975691","subject":"remove deprecated TArg from function parameters","message":"remove deprecated TArg from function parameters\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..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(..))\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-- 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 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--\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\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 (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 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..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 , MAX as CU_FUNC_ATTRIBUTE_MAX } -- ignore\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3827d6be5f090cbbf41959f845110b5574e49a44","subject":"remove constants from types","message":"remove constants from types\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/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_, 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#}\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","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_, 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.Maybe( fromMaybe, mapMaybe )\nimport Data.List( foldl' )\nimport Data.Bits( shiftL, complement, (.|.) )\nimport System.GPU.OpenCL.Util( testMask )\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#}\n\nnewtype ErrorCode = ErrorCode CInt deriving( Eq )\n\n-- -----------------------------------------------------------------------------\ndata CLDeviceType = CL_DEVICE_TYPE_CPU \n -- ^ An OpenCL device that is the host processor. The host \n -- processor runs the OpenCL implementations and is a single \n -- or multi-core CPU.\n | CL_DEVICE_TYPE_GPU\t\n -- ^ An OpenCL device that is a GPU. By this we mean that \n -- the device can also be used to accelerate a 3D API such \n -- as OpenGL or DirectX.\n | CL_DEVICE_TYPE_ACCELERATOR\t\n -- ^ Dedicated OpenCL accelerators (for example the IBM CELL \n -- Blade). These devices communicate with the host processor \n -- using a peripheral interconnect such as PCIe.\n | CL_DEVICE_TYPE_DEFAULT \n -- ^ The default OpenCL device in the system. \n | CL_DEVICE_TYPE_ALL\t\n -- ^ All OpenCL devices available in the system.\n deriving( Eq, Show )\n\ndeviceTypeValues :: [(CLDeviceType,CLDeviceType_)]\ndeviceTypeValues = [ \n (CL_DEVICE_TYPE_CPU, 1 `shiftL` 1), (CL_DEVICE_TYPE_GPU, 1 `shiftL` 2), \n (CL_DEVICE_TYPE_ACCELERATOR, 1 `shiftL` 3), (CL_DEVICE_TYPE_DEFAULT, 1 `shiftL` 0),\n (CL_DEVICE_TYPE_ALL, complement 0) ]\ngetDeviceTypeValue :: CLDeviceType -> CLDeviceType_\ngetDeviceTypeValue info = fromMaybe 0 (lookup info deviceTypeValues)\n\ndata CLCommandQueueProperty = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE\t\n -- ^ Determines whether the commands queued in the \n -- command-queue are executed in-order or \n -- out-of-order. If set, the commands in the \n -- command-queue are executed out-of-order. \n -- Otherwise, commands are executed in-order.\n | CL_QUEUE_PROFILING_ENABLE\t\n -- ^ Enable or disable profiling of commands in\n -- the command-queue. If set, the profiling of \n -- commands is enabled. Otherwise profiling of \n -- commands is disabled. See \n -- 'clGetEventProfilingInfo' for more information.\n deriving( Eq, Show )\n\ncommandQueueProperties :: [(CLCommandQueueProperty,CLCommandQueueProperty_)]\ncommandQueueProperties = [\n (CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, 1 `shiftL` 0),\n (CL_QUEUE_PROFILING_ENABLE, 1 `shiftL` 1)]\n\ndata CLDeviceFPConfig = CL_FP_DENORM -- ^ denorms are supported.\n | CL_FP_INF_NAN -- ^ INF and NaNs are supported.\n | CL_FP_ROUND_TO_NEAREST \n -- ^ round to nearest even rounding mode supported.\n | CL_FP_ROUND_TO_ZERO \n -- ^ round to zero rounding mode supported.\n | CL_FP_ROUND_TO_INF \n -- ^ round to +ve and -ve infinity rounding modes \n -- supported.\n | CL_FP_FMA \n -- ^ IEEE754-2008 fused multiply-add is supported.\n deriving( Show )\n \ndeviceFPValues :: [(CLDeviceFPConfig,CLDeviceFPConfig_)]\ndeviceFPValues = [\n (CL_FP_DENORM, 1 `shiftL` 0), (CL_FP_INF_NAN, 1 `shiftL` 1),\n (CL_FP_ROUND_TO_NEAREST, 1 `shiftL` 2), (CL_FP_ROUND_TO_ZERO, 1 `shiftL` 3),\n (CL_FP_ROUND_TO_INF, 1 `shiftL` 4), (CL_FP_FMA, 1 `shiftL` 5)]\n\ndata CLDeviceExecCapability = CL_EXEC_KERNEL \n -- ^ The OpenCL device can execute OpenCL kernels.\n | CL_EXEC_NATIVE_KERNEL\n -- ^ The OpenCL device can execute native kernels.\n deriving( Show )\n\ndeviceExecValues :: [(CLDeviceExecCapability,CLDeviceExecCapability_)]\ndeviceExecValues = [\n (CL_EXEC_KERNEL, 1 `shiftL` 0), (CL_EXEC_NATIVE_KERNEL, 1 `shiftL` 1)]\n \ndata CLDeviceMemCacheType = CL_NONE | CL_READ_ONLY_CACHE | CL_READ_WRITE_CACHE\n deriving( Show )\ndeviceMemCacheTypes :: [(CLDeviceMemCacheType_,CLDeviceMemCacheType)]\ndeviceMemCacheTypes = [\n (0x0,CL_NONE), (0x1,CL_READ_ONLY_CACHE),(0x2,CL_READ_WRITE_CACHE)]\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType val = lookup val deviceMemCacheTypes\n\ndata CLDeviceLocalMemType = CL_LOCAL | CL_GLOBAL deriving( Show )\n\ndeviceLocalMemTypes :: [(CLDeviceLocalMemType_,CLDeviceLocalMemType)]\ndeviceLocalMemTypes = [(0x1,CL_LOCAL), (0x2,CL_GLOBAL)]\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType val = lookup val deviceLocalMemTypes\n\ndata CLCommandType = CL_COMMAND_NDRANGE_KERNEL | CL_COMMAND_TASK \n | CL_COMMAND_NATIVE_KERNEL | CL_COMMAND_READ_BUFFER\n | CL_COMMAND_WRITE_BUFFER | CL_COMMAND_COPY_BUFFER\n | CL_COMMAND_READ_IMAGE | CL_COMMAND_WRITE_IMAGE\n | CL_COMMAND_COPY_IMAGE | CL_COMMAND_COPY_BUFFER_TO_IMAGE\n | CL_COMMAND_COPY_IMAGE_TO_BUFFER | CL_COMMAND_MAP_BUFFER\n | CL_COMMAND_MAP_IMAGE | CL_COMMAND_UNMAP_MEM_OBJECT\n | CL_COMMAND_MARKER | CL_COMMAND_ACQUIRE_GL_OBJECTS\n | CL_COMMAND_RELEASE_GL_OBJECTS\n deriving( Show )\n\ncommandTypes :: [(CLCommandType_, CLCommandType)]\ncommandTypes = [(0x11F0,CL_COMMAND_NDRANGE_KERNEL),(0x11F1,CL_COMMAND_TASK),\n (0x11F2,CL_COMMAND_NATIVE_KERNEL),(0x11F3,CL_COMMAND_READ_BUFFER),\n (0x11F4,CL_COMMAND_WRITE_BUFFER),(0x11F5,CL_COMMAND_COPY_BUFFER),\n (0x11F6,CL_COMMAND_READ_IMAGE),(0x11F7,CL_COMMAND_WRITE_IMAGE),\n (0x11F8,CL_COMMAND_COPY_IMAGE),(0x11F9,CL_COMMAND_COPY_IMAGE_TO_BUFFER),\n (0x11FA,CL_COMMAND_COPY_BUFFER_TO_IMAGE),(0x11FB,CL_COMMAND_MAP_BUFFER),\n (0x11FC,CL_COMMAND_MAP_IMAGE),(0x11FD,CL_COMMAND_UNMAP_MEM_OBJECT),\n (0x11FE,CL_COMMAND_MARKER),(0x11FF,CL_COMMAND_ACQUIRE_GL_OBJECTS),\n (0x1200,CL_COMMAND_RELEASE_GL_OBJECTS)]\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = (`lookup` commandTypes)\n\ndata CLCommandExecutionStatus = CL_QUEUED \n -- ^ command has been enqueued in the command-queue\n | CL_SUBMITTED \n -- ^ enqueued command has been submitted by the \n -- host to the device associated with the \n -- command-queue\n | CL_RUNNING \n -- ^ device is currently executing this command\n | CL_COMPLETE -- ^ the command has completed\n | CL_EXEC_ERROR \n -- ^ command was abnormally terminated\n \ncommandExecutionStatus :: [(CLint, CLCommandExecutionStatus)]\ncommandExecutionStatus = [(0x0,CL_COMPLETE),(0x1,CL_RUNNING),\n (0x2,CL_SUBMITTED),(0x3,CL_QUEUED)]\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CL_EXEC_ERROR\n | otherwise = lookup n commandExecutionStatus\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 {}#}\n\ngetProfilingInfoValue :: CLProfilingInfo -> CLProfilingInfo_\ngetProfilingInfoValue = fromIntegral . fromEnum\n\n-- -----------------------------------------------------------------------------\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes mask = map fst . filter (testMask mask) $ deviceTypeValues\n\nbitmaskFromDeviceTypes :: [CLDeviceType] -> CLDeviceType_\nbitmaskFromDeviceTypes = foldl' (.|.) 0 . mapMaybe (`lookup` deviceTypeValues)\n \nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = map fst . filter (testMask mask) $ commandQueueProperties\n \nbitmaskFromCommandQueueProperties :: [CLCommandQueueProperty] -> CLCommandQueueProperty_\nbitmaskFromCommandQueueProperties = foldl' (.|.) 0 . mapMaybe (`lookup` commandQueueProperties)\n\nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig mask = map fst . filter (testMask mask) $ deviceFPValues\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability mask = map fst . filter (testMask mask) $ deviceExecValues\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"acb60109adfaf6669da13bfd00725bee56a8787a","subject":"[project @ 2002-07-17 16:07:50 by juhp]","message":"[project @ 2002-07-17 16:07:50 by juhp]\n\nExport timeoutAdd, timeoutRemove, idleAdd, idleRemove and HandlerId.\n\ndarcs-hash:20020717160750-f332a-d66284029be7e8fc11e82e36184f5143524410e1.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 16:07:50 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:13:09 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f76e8466e71545b4d1414468edee7802c86786ef","subject":"Updated XCore architecture header","message":"Updated XCore architecture header\n","repos":"ibabushkin\/hapstone","old_file":"src\/Hapstone\/Internal\/XCore.chs","new_file":"src\/Hapstone\/Internal\/XCore.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-|\nModule : Hapstone.Internal.XCore\nDescription : XCore architecture header ported using C2HS + some boilerplate\nCopyright : (c) Inokentiy Babushkin, 2016\nLicense : BSD3\nMaintainer : Inokentiy Babushkin \nStability : experimental\n\nThis module contains XCore specific datatypes and their respective Storable\ninstances. Most of the types are used internally and can be looked up here.\nSome of them are currently unused, as the headers only define them as symbolic\nconstants whose type is never used explicitly, which poses a problem for a\nmemory-safe port to the Haskell language, this is about to get fixed in a\nfuture version.\n\nApart from that, because the module is generated using C2HS, some of the\ndocumentation is misplaced or rendered incorrectly, so if in doubt, read the\nsource file.\n-}\nmodule Hapstone.Internal.XCore where\n\n#include \n\n{#context lib = \"capstone\"#}\n\nimport Foreign\nimport Foreign.C.Types\n\n-- | operand type for instruction's operands\n{#enum xcore_op_type as XCoreOpType {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- | XCore registers\n{#enum xcore_reg as XCoreReg {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- | memory access operands\n-- associated with 'XcoreOpMem' operand type\ndata XCoreOpMemStruct = XCoreOpMemStruct\n { base :: Word8 -- ^ base register\n , index :: Word8 -- ^ index register\n , disp :: Int32 -- ^ displacement\/offset value\n , direct :: Int32 -- ^ +1: forward, -1: backward\n } deriving (Show, Eq)\n\ninstance Storable XCoreOpMemStruct where\n sizeOf _ = {#sizeof xcore_op_mem#}\n alignment _ = {#alignof xcore_op_mem#}\n peek p = XCoreOpMemStruct\n <$> (fromIntegral <$> {#get xcore_op_mem->base#} p)\n <*> (fromIntegral <$> {#get xcore_op_mem->index#} p)\n <*> (fromIntegral <$> {#get xcore_op_mem->disp#} p)\n <*> (fromIntegral <$> {#get xcore_op_mem->direct#} p)\n poke p (XCoreOpMemStruct b i disp dir) = do\n {#set xcore_op_mem->base#} p (fromIntegral b)\n {#set xcore_op_mem->index#} p (fromIntegral i)\n {#set xcore_op_mem->disp#} p (fromIntegral disp)\n {#set xcore_op_mem->direct#} p (fromIntegral dir)\n\n-- | instruction operand\ndata CsXCoreOp\n = Reg XCoreReg -- ^ register value for 'XcoreOpReg' operands\n | Imm Int32 -- ^ immediate value for 'XcoreOpImm' operands\n | Mem XCoreOpMemStruct -- ^ base\/index\/disp\/direct value for 'XcoreOpMem'\n -- operands\n | Undefined -- ^ invalid operand value, for 'XcoreOpInvalid' operand\n deriving (Show, Eq)\n\ninstance Storable CsXCoreOp where\n sizeOf _ = 16\n alignment _ = 4\n peek p = do\n t <- fromIntegral <$> {#get cs_xcore_op->type#} p\n let bP = plusPtr p 4\n case toEnum t of\n XcoreOpReg -> (Reg . toEnum . fromIntegral) <$> (peek bP :: IO Int32)\n XcoreOpImm -> Imm <$> peek bP\n XcoreOpMem -> Mem <$> peek bP\n _ -> return Undefined\n poke p op = do\n let bP = plusPtr p 4\n setType = {#set cs_xcore_op->type#} p . fromIntegral . fromEnum\n case op of\n Reg r -> do poke bP (fromIntegral $ fromEnum r :: Int32)\n setType XcoreOpReg\n Imm i -> poke bP i >> setType XcoreOpImm\n Mem m -> poke bP m >> setType XcoreOpMem\n _ -> setType XcoreOpInvalid\n\n-- | instruction datatype\nnewtype CsXCore = CsXCore [CsXCoreOp] -- ^ operand list of this instruction,\n -- *MUST* have <= 8 operands, else you'll\n -- get a runtime error when you\n -- (implicitly) try to write it to memory\n -- via it's Storable instance\n deriving (Show, Eq)\n\ninstance Storable CsXCore where\n sizeOf _ = 132\n alignment _ = 4\n peek p = do\n num <- fromIntegral <$> {#get cs_xcore->op_count#} p\n CsXCore <$> peekArray num (plusPtr p {#offsetof cs_xcore.operands#})\n poke p (CsXCore o) = do\n {#set cs_xcore->op_count#} p (fromIntegral $ length o)\n if length o > 8\n then error \"operands overflew 8 elements\"\n else pokeArray (plusPtr p {#offsetof cs_xcore->operands#}) o\n\n-- | XCore instructions\n{#enum xcore_insn as XCoreInsn {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n-- | XCore instruction groups\n{#enum xcore_insn_group as XCoreInsnGroup {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-|\nModule : Hapstone.Internal.XCore\nDescription : XCore architecture header ported using C2HS + some boilerplate\nCopyright : (c) Inokentiy Babushkin, 2016\nLicense : BSD3\nMaintainer : Inokentiy Babushkin \nStability : experimental\n\nThis module contains XCore specific datatypes and their respective Storable\ninstances. Most of the types are used internally and can be looked up here.\nSome of them are currently unused, as the headers only define them as symbolic\nconstants whose type is never used explicitly, which poses a problem for a\nmemory-safe port to the Haskell language, this is about to get fixed in a\nfuture version.\n\nApart from that, because the module is generated using C2HS, some of the\ndocumentation is misplaced or rendered incorrectly, so if in doubt, read the\nsource file.\n-}\nmodule Hapstone.Internal.XCore where\n\n#include \n\n{#context lib = \"capstone\"#}\n\nimport Foreign\nimport Foreign.C.Types\n\n-- | operand type for instruction's operands\n{#enum xcore_op_type as XCoreOpType {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- | memory access operands\n-- associated with 'XcoreOpMem' operand type\ndata XCoreOpMemStruct = XCoreOpMemStruct\n { base :: Word8 -- ^ base register\n , index :: Word8 -- ^ index register\n , disp :: Int32 -- ^ displacement\/offset value\n , direct :: Int32 -- ^ +1: forward, -1: backward\n } deriving (Show, Eq)\n\ninstance Storable XCoreOpMemStruct where\n sizeOf _ = {#sizeof xcore_op_mem#}\n alignment _ = {#alignof xcore_op_mem#}\n peek p = XCoreOpMemStruct\n <$> (fromIntegral <$> {#get xcore_op_mem->base#} p)\n <*> (fromIntegral <$> {#get xcore_op_mem->index#} p)\n <*> (fromIntegral <$> {#get xcore_op_mem->disp#} p)\n <*> (fromIntegral <$> {#get xcore_op_mem->direct#} p)\n poke p (XCoreOpMemStruct b i disp dir) = do\n {#set xcore_op_mem->base#} p (fromIntegral b)\n {#set xcore_op_mem->index#} p (fromIntegral i)\n {#set xcore_op_mem->disp#} p (fromIntegral disp)\n {#set xcore_op_mem->direct#} p (fromIntegral dir)\n\n-- | instruction operand\ndata CsXCoreOp\n = Reg Word32 -- ^ register value for 'XcoreOpReg' operands\n | Imm Int32 -- ^ immediate value for 'XcoreOpImm' operands\n | Mem XCoreOpMemStruct -- ^ base\/index\/disp\/direct value for 'XcoreOpMem'\n -- operands\n | Undefined -- ^ invalid operand value, for 'XcoreOpInvalid' operand\n deriving (Show, Eq)\n\ninstance Storable CsXCoreOp where\n sizeOf _ = 16\n alignment _ = 4\n peek p = do\n t <- fromIntegral <$> {#get cs_xcore_op->type#} p\n let bP = plusPtr p 4\n case toEnum t of\n XcoreOpReg -> Reg <$> peek bP\n XcoreOpImm -> Imm <$> peek bP\n XcoreOpMem -> Mem <$> peek bP\n _ -> return Undefined\n poke p op = do\n let bP = plusPtr p 4\n setType = {#set cs_xcore_op->type#} p . fromIntegral . fromEnum\n case op of\n Reg r -> poke bP r >> setType XcoreOpReg\n Imm i -> poke bP i >> setType XcoreOpImm\n Mem m -> poke bP m >> setType XcoreOpMem\n _ -> setType XcoreOpInvalid\n\n-- | instruction datatype\nnewtype CsXCore = CsXCore [CsXCoreOp] -- ^ operand list of this instruction,\n -- *MUST* have <= 8 operands, else you'll\n -- get a runtime error when you\n -- (implicitly) try to write it to memory\n -- via it's Storable instance\n deriving (Show, Eq)\n\ninstance Storable CsXCore where\n sizeOf _ = 132\n alignment _ = 4\n peek p = do\n num <- fromIntegral <$> {#get cs_xcore->op_count#} p\n CsXCore <$> peekArray num (plusPtr p {#offsetof cs_xcore.operands#})\n poke p (CsXCore o) = do\n {#set cs_xcore->op_count#} p (fromIntegral $ length o)\n if length o > 8\n then error \"operands overflew 8 elements\"\n else pokeArray (plusPtr p {#offsetof cs_xcore->operands#}) o\n\n-- | XCore registers\n{#enum xcore_reg as XCoreReg {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n-- | XCore instructions\n{#enum xcore_insn as XCoreInsn {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n-- | XCore instruction groups\n{#enum xcore_insn_group as XCoreInsnGroup {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"76b41dcbf6205b994d228c83617b34a5000feadd","subject":"Implement pageRectangleNew","message":"Implement pageRectangleNew\n","repos":"YoEight\/poppler_bak","old_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Page.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n--\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n -- pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageAddAnnot,\n pageRemoveAnnot,\n pageRectangleNew\n -- pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page =\n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\n{- pageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into\n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n-}\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page\n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n\n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page\npageGetIndex page =\n liftM fromIntegral $\n {#call poppler_page_get_index #} (toPage page)\n\n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success\n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n\n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile =\n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded)\n -> IO [PopplerRectangle]\npageFindText page text =\n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n\n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page =\n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n\n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1.\npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'.\npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'.\npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'.\npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'.\npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection =\n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #}\n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs\n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background\n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n\npageAddAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageAddAnnot page annot =\n {# call poppler_page_add_annot #} (toPage page) (toAnnot annot)\n\npageRemoveAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageRemoveAnnot page annot =\n {# call poppler_page_remove_annot #} (toPage page) (toAnnot annot)\n\npageRectangleNew :: IO PopplerRectangle\npageRectangleNew =\n (peekPopplerRectangle . castPtr) =<< {# call poppler_rectangle_new #}\n\n\n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\n{-\npageRenderSelectionToPixbuf :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> Color -- ^ @glyphColor@ color to use for drawing glyphs\n -> Color -- ^ @backgroundColor@ color to use for the selection background\n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor =\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n-}\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n--\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Page (\n-- * Types\n Cairo,\n PopplerRectangle (..),\n PopplerColor (..),\n ImageMapping,\n PageTransition,\n LinkMapping,\n FormFieldMapping,\n\n-- * Enums\n SelectionStyle (..),\n\n-- * Methods\n pageRender,\n -- pageRenderToPixbuf,\n pageGetSize,\n pageGetIndex,\n pageGetThumbnail,\n pageGetThumbnailSize,\n pageRenderToPs,\n pageFindText,\n pageGetText,\n pageGetDuration,\n pageGetTransition,\n pageGetLinkMapping,\n pageGetImageMapping,\n pageGetFormFieldMapping,\n pageGetSelectionRegion,\n pageRenderSelection,\n pageAddAnnot,\n pageRemoveAnnot\n -- pageRenderSelectionToPixbuf,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\nimport Control.Monad.Reader (ReaderT(runReaderT), ask, MonadIO, liftIO)\nimport Graphics.Rendering.Cairo.Internal (Render(..), bracketR)\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Render the page to the given cairo context. This function is for rendering a page that will be\n-- displayed. If you want to render a page that will be printed use 'pageRenderForPrinting'\n-- instead\npageRender :: PageClass page => page\n -> Render ()\npageRender page =\n ask >>= \\ x -> liftIO ({#call poppler_page_render #} (toPage page) x)\n\n-- | First scale the document to match the specified pixels per point, then render the rectangle given by\n-- the upper left corner at (@srcX@, @srcY@) and @srcWidth@ and @srcHeight@. This function is for rendering\n-- a page that will be displayed. If you want to render a page that will be printed use\n-- 'pageRenderToPixbufForPrinting' instead\n{- pageRenderToPixbuf :: PageClass page => page\n -> Rectangle -- ^ @rect@ rectangle to render\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render into\n -> IO ()\npageRenderToPixbuf page (Rectangle x y width height) scale rotation pixbuf =\n {#call poppler_page_render_to_pixbuf #}\n (toPage page)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n-}\n\n-- | Gets the size of page at the current scale and rotation.\npageGetSize :: PageClass page => page\n -> IO (Double, Double)\npageGetSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n {#call poppler_page_get_size #}\n (toPage page)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (realToFrac width, realToFrac height)\n\n-- | Returns the index of page\npageGetIndex :: PageClass page => page\n -> IO Int -- ^ returns index value of page\npageGetIndex page =\n liftM fromIntegral $\n {#call poppler_page_get_index #} (toPage page)\n\n-- | Get the embedded thumbnail for the specified page. If the document doesn't have an embedded\n-- thumbnail for the page, this function returns 'Nothing'.\npageGetThumbnail :: PageClass page => page\n -> IO (Maybe Surface) -- ^ returns the tumbnail as a @cairoSurfaceT@ or 'Nothing' if the document doesn't have a thumbnail for this page.\npageGetThumbnail page = do\n surfacePtr <- {#call poppler_page_get_thumbnail #} (toPage page)\n if surfacePtr == nullPtr\n then return Nothing\n else liftM Just (mkSurface surfacePtr)\n\n-- | Returns 'True' if page has a thumbnail associated with it. It also fills in width and height with the\n-- width and height of the thumbnail. The values of width and height are not changed if no appropriate\n-- thumbnail exists.\npageGetThumbnailSize :: PageClass page => page\n -> IO (Maybe (Int, Int))\npageGetThumbnailSize page =\n alloca $ \\ widthPtr ->\n alloca $ \\ heightPtr -> do\n success <- liftM toBool $\n {#call poppler_page_get_thumbnail_size #}\n (toPage page)\n widthPtr\n heightPtr\n if success\n then do\n width <- peek widthPtr\n height <- peek heightPtr\n return $ Just (fromIntegral width, fromIntegral height)\n else return Nothing\n\n-- | Render the page on a postscript file\npageRenderToPs :: (PageClass page, PSFileClass psFile) => page -> psFile -> IO ()\npageRenderToPs page psFile =\n {#call poppler_page_render_to_ps #} (toPage page) (toPSFile psFile)\n\n-- | A GList of rectangles for each occurance of the text on the page. The coordinates are in PDF points.\npageFindText :: PageClass page => page\n -> String -- ^ @text@ the text to search for (UTF-8 encoded)\n -> IO [PopplerRectangle]\npageFindText page text =\n withUTFString text $ \\ textPtr -> do\n glistPtr <- {#call poppler_page_find_text #} (toPage page) textPtr\n list <- fromGList glistPtr\n mapM peekPopplerRectangle list\n\n-- | Retrieves the contents of the specified selection as text.\npageGetText :: PageClass page => page -> IO String -- ^ returns selection string\npageGetText page =\n {#call poppler_page_get_text #} (toPage page)\n >>= peekUTFString\n\n-- | Returns the duration of page\npageGetDuration :: PageClass page => page\n -> IO Double -- ^ returns duration in seconds of page or -1.\npageGetDuration page =\n liftM realToFrac $\n {#call poppler_page_get_duration #} (toPage page)\n\n-- | Returns the transition effect of page\npageGetTransition :: PageClass page => page\n -> IO (Maybe PageTransition) -- ^ returns a 'PageTransition' or 'Nothing'.\npageGetTransition page = do\n ptr <- {#call poppler_page_get_transition #} (toPage page)\n if ptr == nullPtr\n then return Nothing\n else liftM Just $ makeNewPageTransition (castPtr ptr)\n\n{#pointer *PageTransition foreign newtype #}\n\nmakeNewPageTransition :: Ptr PageTransition -> IO PageTransition\nmakeNewPageTransition rPtr = do\n transition <- newForeignPtr rPtr page_transition_free\n return (PageTransition transition)\n\nforeign import ccall unsafe \"&poppler_page_transition_free\"\n page_transition_free :: FinalizerPtr PageTransition\n\n-- | Returns a list of 'LinkMapping' items that map from a location on page to a 'Action'.\npageGetLinkMapping :: PageClass page => page\n -> IO [LinkMapping]\npageGetLinkMapping page = do\n glistPtr <- {#call poppler_page_get_link_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewLinkMapping list\n {#call unsafe poppler_page_free_link_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *LinkMapping foreign newtype #}\n\nmakeNewLinkMapping :: Ptr LinkMapping -> IO LinkMapping\nmakeNewLinkMapping rPtr = do\n linkMapping <- newForeignPtr rPtr poppler_link_mapping_free\n return (LinkMapping linkMapping)\n\nforeign import ccall unsafe \"&poppler_link_mapping_free\"\n poppler_link_mapping_free :: FinalizerPtr LinkMapping\n\n-- | Returns a list of 'ImageMapping' items that map from a location on page to a 'Action'.\npageGetImageMapping :: PageClass page => page\n -> IO [ImageMapping]\npageGetImageMapping page = do\n glistPtr <- {#call poppler_page_get_image_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewImageMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *ImageMapping foreign newtype #}\n\nmakeNewImageMapping :: Ptr ImageMapping -> IO ImageMapping\nmakeNewImageMapping rPtr = do\n imageMapping <- newForeignPtr rPtr poppler_image_mapping_free\n return (ImageMapping imageMapping)\n\nforeign import ccall unsafe \"&poppler_image_mapping_free\"\n poppler_image_mapping_free :: FinalizerPtr ImageMapping\n\n-- | Returns a list of 'FormFieldMapping' items that map from a location on page to a 'Action'.\npageGetFormFieldMapping :: PageClass page => page\n -> IO [FormFieldMapping]\npageGetFormFieldMapping page = do\n glistPtr <- {#call poppler_page_get_form_field_mapping #} (toPage page)\n list <- fromGList glistPtr\n mappings <- mapM makeNewFormFieldMapping list\n {#call unsafe poppler_page_free_image_mapping #} (castPtr glistPtr)\n return mappings\n\n{#pointer *FormFieldMapping foreign newtype #}\n\nmakeNewFormFieldMapping :: Ptr FormFieldMapping -> IO FormFieldMapping\nmakeNewFormFieldMapping rPtr = do\n formFieldMapping <- newForeignPtr rPtr poppler_form_field_mapping_free\n return (FormFieldMapping formFieldMapping)\n\nforeign import ccall unsafe \"&poppler_form_field_mapping_free\"\n poppler_form_field_mapping_free :: FinalizerPtr FormFieldMapping\n\n-- | Returns a region containing the area that would be rendered by 'pageRenderSelection' or\n-- 'pageRenderSelectionToPixbuf' as a GList of PopplerRectangle.\npageGetSelectionRegion :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> IO [PopplerRectangle]\npageGetSelectionRegion page scale style selection =\n with selection $ \\ selectionPtr -> do\n glistPtr <- {#call poppler_page_get_selection_region #}\n (toPage page)\n (realToFrac scale)\n ((fromIntegral . fromEnum) style)\n (castPtr selectionPtr)\n list <- fromGList glistPtr\n rectangles <- mapM peekPopplerRectangle list\n {#call unsafe poppler_page_selection_region_free #} (castPtr glistPtr)\n return rectangles\n\n-- | Render the selection specified by selection for page to the given cairo context. The selection will\n-- be rendered, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered to cairo, in which case\n-- this function will (some day) only render the changed part of the selection.\npageRenderSelection :: PageClass page => page\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> PopplerColor -- ^ @glyphColor@ color to use for drawing glyphs\n -> PopplerColor -- ^ @backgroundColor@ color to use for the selection background\n -> Render ()\npageRenderSelection page selection oldSelection style glyphColor backgroundColor = do\n cairo <- ask\n liftIO $\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection #}\n (toPage page)\n cairo\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n\npageAddAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageAddAnnot page annot =\n {# call poppler_page_add_annot #} (toPage page) (toAnnot annot)\n\npageRemoveAnnot :: (PageClass page, AnnotClass annot) => page -> annot -> IO ()\npageRemoveAnnot page annot =\n {# call poppler_page_remove_annot #} (toPage page) (toAnnot annot)\n\n-- | Render the selection specified by selection for page into pixbuf. The selection will be rendered at\n-- scale, using @glyphColor@ for the glyphs and @backgroundColor@ for the selection background.\n--\n-- If non-'Nothing', @oldSelection@ specifies the selection that is already rendered in pixbuf, in which case\n-- this function will (some day) only render the changed part of the selection.\n{-\npageRenderSelectionToPixbuf :: PageClass page => page\n -> Double -- ^ @scale@ scale specified as pixels per point\n -> Int -- ^ @rotation@ rotate the document by the specified degree\n -> Pixbuf -- ^ @pixbuf@ pixbuf to render to\n -> PopplerRectangle -- ^ @selection@ start and end point of selection as a rectangle\n -> PopplerRectangle -- ^ @oldSelection@ previous selection\n -> SelectionStyle -- ^ @style@ a 'SelectionStyle'\n -> Color -- ^ @glyphColor@ color to use for drawing glyphs\n -> Color -- ^ @backgroundColor@ color to use for the selection background\n -> IO ()\npageRenderSelectionToPixbuf page scale rotation pixbuf selection oldSelection style glyphColor backgroundColor =\n with selection $ \\ selectionPtr ->\n with oldSelection $ \\ oldSelectionPtr ->\n with glyphColor $ \\ glyphColorPtr ->\n with backgroundColor $ \\ backgroundColorPtr ->\n {#call poppler_page_render_selection_to_pixbuf #}\n (toPage page)\n (realToFrac scale)\n (fromIntegral rotation)\n pixbuf\n (castPtr selectionPtr)\n (castPtr oldSelectionPtr)\n ((fromIntegral . fromEnum) style)\n (castPtr glyphColorPtr)\n (castPtr backgroundColorPtr)\n-}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"07c0e56cac22d07bf87d37a3928a8eb90fd8eed6","subject":"[project @ 2002-10-20 14:29:26 by as49] Documentation fixes.","message":"[project @ 2002-10-20 14:29:26 by as49]\nDocumentation fixes.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/gdk\/Drawable.chs","new_file":"gtk\/gdk\/Drawable.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Drawable@\n--\n-- Author : Axel Simon\n-- Created: 22 September 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/10\/20 14:29:26 $\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-- Drawing primitives.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This module defines drawing primitives that can operate on \n-- @ref data DrawWindow@s, @ref data Pixmap@s and \n-- @ref data Bitmap@s.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if gdk_visuals are implemented, do: get_visual\n-- * if gdk_colormaps are implemented, do: set_colormap, get_colormap\n-- * text drawing functions\n--\nmodule Drawable(\n Drawable,\n DrawableClass,\n castToDrawable,\n drawableGetDepth,\n drawableGetSize,\n drawableGetClipRegion,\n drawableGetVisibleRegion,\n drawPoint,\n drawPoints,\n drawLine,\n drawLines,\n drawSegments,\n drawRectangle,\n drawArc,\n drawPolygon,\n drawDrawable) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport GObject\t(makeNewGObject)\nimport Structs (Point)\n{#import Hierarchy#}\n{#import Region#}\t(Region, makeNewRegion)\n\n{# context lib=\"gtk\" prefix=\"gdk\" #}\n\n-- methods\n\n-- @method drawableGetDepth@ Get the size of pixels.\n--\n-- * Returns the number of bits which are use to store information on each\n-- pixels in this @ref data Drawable@.\n--\ndrawableGetDepth :: DrawableClass d => d -> IO Int\ndrawableGetDepth d = liftM fromIntegral $ \n\t\t {#call unsafe drawable_get_depth#} (toDrawable d)\n\n-- @method drawableGetSize@ Retrieve the size of the @ref type Drawable@.\n--\n-- * The result might not be up-to-date if there are still resizing messages\n-- to be processed.\n--\ndrawableGetSize :: DrawableClass d => d -> IO (Int, Int)\ndrawableGetSize d = alloca $ \\wPtr -> alloca $ \\hPtr -> do\n {#call unsafe drawable_get_size#} (toDrawable d) wPtr hPtr\n (w::{#type gint#}) <- peek wPtr\n (h::{#type gint#}) <- peek hPtr\n return (fromIntegral w, fromIntegral h)\n\n-- @method drawableGetClipRegion@ Determine where not to draw.\n--\n-- * Computes the region of a drawable that potentially can be written\n-- to by drawing primitives. This region will not take into account the\n-- clip region for the GC, and may also not take into account other\n-- factors such as if the window is obscured by other windows, but no\n-- area outside of this region will be affected by drawing primitives.\n--\ndrawableGetClipRegion :: DrawableClass d => d -> IO Region\ndrawableGetClipRegion d = do\n rPtr <- {#call unsafe drawable_get_clip_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawableGetVisibleRegion@ Determine what not to redraw.\n--\n-- * Computes the region of a drawable that is potentially visible.\n-- This does not necessarily take into account if the window is obscured\n-- by other windows, but no area outside of this region is visible.\n--\ndrawableGetVisibleRegion :: DrawableClass d => d -> IO Region\ndrawableGetVisibleRegion d = do\n rPtr <- {#call unsafe drawable_get_visible_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawPoint@ Draw a point into a @ref type Drawable@.\n--\ndrawPoint :: DrawableClass d => d -> GC -> Point -> IO ()\ndrawPoint d gc (x,y) = {#call unsafe draw_point#} (toDrawable d)\n (toGC gc) (fromIntegral x) (fromIntegral y)\n\n\n-- @method drawPoints@ Draw several points into a @ref type Drawable@.\n--\n-- * This function is more efficient than calling @ref method drawPoint@ on\n-- several points.\n--\ndrawPoints :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawPoints d gc points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_points#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawLine@ Draw a line into a @ref type Drawable@.\n--\n-- * The parameters are x1, y1, x2, y2.\n--\n-- * Drawing several separate lines can be done more efficiently by\n-- @ref method drawSegments@.\n--\ndrawLine :: DrawableClass d => d -> GC -> Point -> Point -> IO ()\ndrawLine d gc (x1,y1) (x2,y2) = {#call unsafe draw_line#} (toDrawable d)\n (toGC gc) (fromIntegral x1) (fromIntegral y1) (fromIntegral x2) \n (fromIntegral x2)\n\n-- @method drawLines@ Draw several lines.\n--\n-- * The function uses the current line width, dashing and especially the\n-- joining specification in the graphics context (in contrast to\n-- @ref method drawSegments@.\n--\ndrawLines :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawLines d gc points =\n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_lines#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawSegments@ Draw several unconnected lines.\n--\n-- * This method draws several unrelated lines.\n--\ndrawSegments :: DrawableClass d => d -> GC -> [(Point,Point)] -> IO ()\ndrawSegments d gc pps = withArray (concatMap (\\((x1,y1),(x2,y2)) -> \n [fromIntegral x1, fromIntegral y1, fromIntegral x2, fromIntegral y2])\n pps) $ \\(aPtr :: Ptr {#type gint#}) ->\n {#call unsafe draw_segments#} (toDrawable d) (toGC gc)\n (castPtr aPtr) (fromIntegral (length pps))\n\n-- @method drawRectangle@ Draw a rectangular object.\n--\n-- * Draws a rectangular outline or filled rectangle, using the\n-- foreground color and other attributes of the @ref type GC@.\n--\n-- * A rectangle drawn filled is 1 pixel smaller in both dimensions\n-- than a rectangle outlined. Calling @ref method drawRectangle@ w gc\n-- True 0 0 20 20 results in a filled rectangle 20 pixels wide and 20\n-- pixels high. Calling @ref method drawRectangle@ d gc False 0 0 20 20\n-- results in an outlined rectangle with corners at (0, 0), (0, 20), (20,\n-- 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.\n--\ndrawRectangle :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> IO ()\ndrawRectangle d gc filled x y width height = {#call unsafe draw_rectangle#}\n (toDrawable d) (toGC gc) (fromBool filled) (fromIntegral x)\n (fromIntegral y) (fromIntegral width) (fromIntegral height)\n\n-- @method drawArc@ Draws an arc or a filled 'pie slice'.\n--\n-- * The arc is defined by the bounding rectangle of the entire\n-- ellipse, and the start and end angles of the part of the ellipse to be\n-- drawn.\n--\n-- * The starting angle @ref arg aStart@ is relative to the 3 o'clock\n-- position, counter-clockwise, in 1\/64ths of a degree. @ref arg aEnd@\n-- is measured similarly, but relative to @ref arg aStart@.\n--\ndrawArc :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> Int -> Int -> IO ()\ndrawArc d gc filled x y width height aStart aEnd =\n {#call unsafe draw_arc#} (toDrawable d) (toGC gc) (fromBool filled)\n (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)\n (fromIntegral aStart) (fromIntegral aEnd)\n\n-- @method drawPolygon@ Draws an outlined or filled polygon.\n--\n-- * The polygon is closed automatically, connecting the last point to\n-- the first point if necessary.\n--\ndrawPolygon :: DrawableClass d => d -> GC -> Bool -> [Point] -> IO ()\ndrawPolygon d gc filled points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr::Ptr {#type gint#}) -> {#call unsafe draw_polygon#} (toDrawable d)\n (toGC gc) (fromBool filled) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawDrawable@ Copies another @ref type Drawable@.\n--\n-- * Copies the (width,height) region of the @ref arg src@ at coordinates\n-- (@ref arg xSrc@, @ref arg ySrc@) to coordinates (@ref arg xDest@,\n-- @ref arg yDest@) in the @ref arg dest@. The @ref arg width@ and\/or\n-- @ref arg height@ may be given as -1, in which case the entire source\n-- drawable will be copied.\n--\n-- * Most fields in @ref arg gc@ are not used for this operation, but\n-- notably the clip mask or clip region will be honored. The source and\n-- destination drawables must have the same visual and colormap, or\n-- errors will result. (On X11, failure to match visual\/colormap results\n-- in a BadMatch error from the X server.) A common cause of this\n-- problem is an attempt to draw a bitmap to a color drawable. The way to\n-- draw a bitmap is to set the bitmap as a clip mask on your\n-- @ref type GC@, then use @ref method drawRectangle@ to draw a \n-- rectangle clipped to the bitmap.\n--\ndrawDrawable :: (DrawableClass src, DrawableClass dest) => \n\t\tdest -> GC -> src -> Int -> Int -> Int -> Int -> \n\t\tInt -> Int -> IO ()\ndrawDrawable dest gc src xSrc ySrc xDest yDest width height =\n {#call unsafe draw_drawable#} (toDrawable dest) (toGC gc)\n (toDrawable src)\n (fromIntegral xSrc) (fromIntegral ySrc) (fromIntegral xDest)\n (fromIntegral yDest) (fromIntegral width) (fromIntegral height)\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Drawable@\n--\n-- Author : Axel Simon\n-- Created: 22 September 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2002\/10\/06 16:14:07 $\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-- Drawing primitives.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This module defines drawing primitives that can operate on \n-- @ref object DrawWindow@s, @ref object Pixmap@s and \n-- @ref object Bitmap@s.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if gdk_visuals are implemented, do: get_visual\n-- * if gdk_colormaps are implemented, do: set_colormap, get_colormap\n-- * text drawing functions\n--\nmodule Drawable(\n Drawable,\n DrawableClass,\n castToDrawable,\n drawableGetDepth,\n drawableGetSize,\n drawableGetClipRegion,\n drawableGetVisibleRegion,\n drawPoint,\n drawPoints,\n drawLine,\n drawLines,\n drawSegments,\n drawRectangle,\n drawArc,\n drawPolygon,\n drawDrawable) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport GObject\t(makeNewGObject)\nimport Structs (Point)\n{#import Hierarchy#}\n{#import Region#}\t(Region, makeNewRegion)\n\n{# context lib=\"gtk\" prefix=\"gdk\" #}\n\n-- methods\n\n-- @method drawableGetDepth@ Get the size of pixels.\n--\n-- * Returns the number of bits which are use to store information on each\n-- pixels in this @ref object Drawable@.\n--\ndrawableGetDepth :: DrawableClass d => d -> IO Int\ndrawableGetDepth d = liftM fromIntegral $ \n\t\t {#call unsafe drawable_get_depth#} (toDrawable d)\n\n-- @method drawableGetSize@ Retrieve the size of the @ref type Drawable@.\n--\n-- * The result might not be up-to-date if there are still resizing messages\n-- to be processed.\n--\ndrawableGetSize :: DrawableClass d => d -> IO (Int, Int)\ndrawableGetSize d = alloca $ \\wPtr -> alloca $ \\hPtr -> do\n {#call unsafe drawable_get_size#} (toDrawable d) wPtr hPtr\n (w::{#type gint#}) <- peek wPtr\n (h::{#type gint#}) <- peek hPtr\n return (fromIntegral w, fromIntegral h)\n\n-- @method drawableGetClipRegion@ Determine where not to draw.\n--\n-- * Computes the region of a drawable that potentially can be written\n-- to by drawing primitives. This region will not take into account the\n-- clip region for the GC, and may also not take into account other\n-- factors such as if the window is obscured by other windows, but no\n-- area outside of this region will be affected by drawing primitives.\n--\ndrawableGetClipRegion :: DrawableClass d => d -> IO Region\ndrawableGetClipRegion d = do\n rPtr <- {#call unsafe drawable_get_clip_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawableGetVisibleRegion@ Determine what not to redraw.\n--\n-- * Computes the region of a drawable that is potentially visible.\n-- This does not necessarily take into account if the window is obscured\n-- by other windows, but no area outside of this region is visible.\n--\ndrawableGetVisibleRegion :: DrawableClass d => d -> IO Region\ndrawableGetVisibleRegion d = do\n rPtr <- {#call unsafe drawable_get_visible_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawPoint@ Draw a point into a @ref type Drawable@.\n--\ndrawPoint :: DrawableClass d => d -> GC -> Point -> IO ()\ndrawPoint d gc (x,y) = {#call unsafe draw_point#} (toDrawable d)\n (toGC gc) (fromIntegral x) (fromIntegral y)\n\n\n-- @method drawPoints@ Draw several points into a @ref type Drawable@.\n--\n-- * This function is more efficient than calling @ref method drawPoint@ on\n-- several points.\n--\ndrawPoints :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawPoints d gc points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_points#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawLine@ Draw a line into a @ref type Drawable@.\n--\n-- * The parameters are x1, y1, x2, y2.\n--\n-- * Drawing several separate lines can be done more efficiently by\n-- @ref method drawSegments@.\n--\ndrawLine :: DrawableClass d => d -> GC -> Point -> Point -> IO ()\ndrawLine d gc (x1,y1) (x2,y2) = {#call unsafe draw_line#} (toDrawable d)\n (toGC gc) (fromIntegral x1) (fromIntegral y1) (fromIntegral x2) \n (fromIntegral x2)\n\n-- @method drawLines@ Draw several lines.\n--\n-- * The function uses the current line width, dashing and especially the\n-- joining specification in the graphics context (in contrast to\n-- @ref method drawSegments@.\n--\ndrawLines :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawLines d gc points =\n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_lines#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawSegments@ Draw several unconnected lines.\n--\n-- * This method draws several unrelated lines.\n--\ndrawSegments :: DrawableClass d => d -> GC -> [(Point,Point)] -> IO ()\ndrawSegments d gc pps = withArray (concatMap (\\((x1,y1),(x2,y2)) -> \n [fromIntegral x1, fromIntegral y1, fromIntegral x2, fromIntegral y2])\n pps) $ \\(aPtr :: Ptr {#type gint#}) ->\n {#call unsafe draw_segments#} (toDrawable d) (toGC gc)\n (castPtr aPtr) (fromIntegral (length pps))\n\n-- @method drawRectangle@ Draw a rectangular object.\n--\n-- * Draws a rectangular outline or filled rectangle, using the\n-- foreground color and other attributes of the @ref type GC@.\n--\n-- * A rectangle drawn filled is 1 pixel smaller in both dimensions\n-- than a rectangle outlined. Calling @ref method drawRectangle@ w gc\n-- True 0 0 20 20 results in a filled rectangle 20 pixels wide and 20\n-- pixels high. Calling @ref method drawRectangle@ d gc False 0 0 20 20\n-- results in an outlined rectangle with corners at (0, 0), (0, 20), (20,\n-- 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.\n--\ndrawRectangle :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> IO ()\ndrawRectangle d gc filled x y width height = {#call unsafe draw_rectangle#}\n (toDrawable d) (toGC gc) (fromBool filled) (fromIntegral x)\n (fromIntegral y) (fromIntegral width) (fromIntegral height)\n\n-- @method drawArc@ Draws an arc or a filled 'pie slice'.\n--\n-- * The arc is defined by the bounding rectangle of the entire\n-- ellipse, and the start and end angles of the part of the ellipse to be\n-- drawn.\n--\n-- * The starting angle @ref arg aStart@ is relative to the 3 o'clock\n-- position, counter-clockwise, in 1\/64ths of a degree. @ref arg aEnd@\n-- is measured similarly, but relative to @ref arg aStart@.\n--\ndrawArc :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> Int -> Int -> IO ()\ndrawArc d gc filled x y width height aStart aEnd =\n {#call unsafe draw_arc#} (toDrawable d) (toGC gc) (fromBool filled)\n (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)\n (fromIntegral aStart) (fromIntegral aEnd)\n\n-- @method drawPolygon@ Draws an outlined or filled polygon.\n--\n-- * The polygon is closed automatically, connecting the last point to\n-- the first point if necessary.\n--\ndrawPolygon :: DrawableClass d => d -> GC -> Bool -> [Point] -> IO ()\ndrawPolygon d gc filled points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr::Ptr {#type gint#}) -> {#call unsafe draw_polygon#} (toDrawable d)\n (toGC gc) (fromBool filled) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawDrawable@ Copies another @ref type Drawable@.\n--\n-- * Copies the (width,height) region of the @ref arg src@ at coordinates\n-- (@ref arg xSrc@, @ref arg ySrc@) to coordinates (@ref arg xDest@, @ref\n-- arg yDest@) in the @ref arg dest@. The @ref arg width@ and\/or @ref arg\n-- height@ may be given as -1, in which case the entire source drawable\n-- will be copied.\n--\n-- * Most fields in @ref arg gc@ are not used for this operation, but\n-- notably the clip mask or clip region will be honored. The source and\n-- destination drawables must have the same visual and colormap, or\n-- errors will result. (On X11, failure to match visual\/colormap results\n-- in a BadMatch error from the X server.) A common cause of this\n-- problem is an attempt to draw a bitmap to a color drawable. The way to\n-- draw a bitmap is to set the bitmap as a clip mask on your\n-- @ref type GC@, then use @ref method drawRectangle@ to draw a \n-- rectangle clipped to the bitmap.\n--\ndrawDrawable :: (DrawableClass src, DrawableClass dest) => \n\t\tdest -> GC -> src -> Int -> Int -> Int -> Int -> \n\t\tInt -> Int -> IO ()\ndrawDrawable dest gc src xSrc ySrc xDest yDest width height =\n {#call unsafe draw_drawable#} (toDrawable dest) (toGC gc)\n (toDrawable src)\n (fromIntegral xSrc) (fromIntegral ySrc) (fromIntegral xDest)\n (fromIntegral yDest) (fromIntegral width) (fromIntegral height)\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a671125ddc3e9916a148eae116b9654f26555290","subject":"remove use of image format until needed","message":"remove use of image format until needed\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..),\n -- * Functions\n clSuccess, wrapPError, getCLValue, getDeviceLocalMemType, \n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \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\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n CLBUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n CLCOMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n CLDEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n CLDEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n CLIMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n CLIMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n CLINVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n CLINVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n CLINVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n CLINVALID_BINARY=CL_INVALID_BINARY,\n CLINVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n CLINVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n CLINVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n CLINVALID_CONTEXT=CL_INVALID_CONTEXT,\n CLINVALID_DEVICE=CL_INVALID_DEVICE,\n CLINVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n CLINVALID_EVENT=CL_INVALID_EVENT,\n CLINVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n CLINVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n CLINVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n CLINVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n CLINVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n CLINVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n CLINVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n CLINVALID_KERNEL=CL_INVALID_KERNEL,\n CLINVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n CLINVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n CLINVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n CLINVALID_OPERATION=CL_INVALID_OPERATION,\n CLINVALID_PLATFORM=CL_INVALID_PLATFORM,\n CLINVALID_PROGRAM=CL_INVALID_PROGRAM,\n CLINVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n CLINVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n CLINVALID_SAMPLER=CL_INVALID_SAMPLER,\n CLINVALID_VALUE=CL_INVALID_VALUE,\n CLINVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n CLINVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n CLINVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n CLMAP_FAILURE=CL_MAP_FAILURE,\n CLMEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n CLMEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n CLOUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n CLOUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n CLPROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n CLSUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n* 'CLBUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CLCOMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CLDEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CLDEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CLIMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CLIMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CLINVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CLINVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CLINVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CLINVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CLINVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CLINVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CLINVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CLINVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CLINVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CLINVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CLINVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CLINVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CLINVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CLINVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CLINVALID_HOST_PTR', Returned if host_ptr is NULL and 'CLMEM_USE_HOST_PTR'\nor 'CLMEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CLMEM_COPY_HOST_PTR' or 'CLMEM_USE_HOST_PTR' are not set in flags.\n\n * 'CLINVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CLINVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CLINVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CLINVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CLINVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CLINVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CLINVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CLINVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CLINVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CLINVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CLINVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CLINVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CLINVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CLINVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CLINVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CLINVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CLINVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CLMAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CLMEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CLMEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CLOUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CLPROFILING_INFO_NOT_AVAILABLE', Returned if the 'CLQUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CLSUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CLSUCCESS\n then return $ Right v\n else return $ Left errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} deriving( Show ) #}\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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\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\n#c\nenum CLDeviceLocalMemType {\n CLLOCAL=CL_LOCAL, CLGLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {} deriving( Show ) #}\n\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\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\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\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n CLMEM_READ_WRITE=CL_MEM_READ_WRITE,\n CLMEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n CLMEM_READ_ONLY=CL_MEM_READ_ONLY,\n CLMEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n CLMEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n CLMEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n* 'CLMEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CLMEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CLMEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CLMEM_ALLOC_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CLMEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CLMEM_COPY_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually\nexclusive. 'CLMEM_COPY_HOST_PTR' can be used with 'CLMEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . toEnum . fromIntegral\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . toEnum . fromIntegral\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . toEnum . fromIntegral\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CLEXEC_ERROR\n | otherwise = Just . toEnum . fromIntegral $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\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\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLImageFormat(..), CLPlatformInfo(..), CLMemFlag(..),\n -- * Functions\n clSuccess, wrapPError, getCLValue, getImageFormat, \n getDeviceLocalMemType, getDeviceMemCacheType, \n getCommandType, getCommandExecutionStatus, bitmaskToDeviceTypes, \n bitmaskFromFlags, bitmaskToCommandQueueProperties, bitmaskToFPConfig, \n 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\n{#pointer *cl_image_format as CLImageFormat_p#}\n\ntype CLImageChannelOrder_ = {#type cl_channel_order#}\ntype CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n CLBUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n CLCOMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n CLDEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n CLDEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n CLIMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n CLIMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n CLINVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n CLINVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n CLINVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n CLINVALID_BINARY=CL_INVALID_BINARY,\n CLINVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n CLINVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n CLINVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n CLINVALID_CONTEXT=CL_INVALID_CONTEXT,\n CLINVALID_DEVICE=CL_INVALID_DEVICE,\n CLINVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n CLINVALID_EVENT=CL_INVALID_EVENT,\n CLINVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n CLINVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n CLINVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n CLINVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n CLINVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n CLINVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n CLINVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n CLINVALID_KERNEL=CL_INVALID_KERNEL,\n CLINVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n CLINVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n CLINVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n CLINVALID_OPERATION=CL_INVALID_OPERATION,\n CLINVALID_PLATFORM=CL_INVALID_PLATFORM,\n CLINVALID_PROGRAM=CL_INVALID_PROGRAM,\n CLINVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n CLINVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n CLINVALID_SAMPLER=CL_INVALID_SAMPLER,\n CLINVALID_VALUE=CL_INVALID_VALUE,\n CLINVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n CLINVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n CLINVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n CLMAP_FAILURE=CL_MAP_FAILURE,\n CLMEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n CLMEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n CLOUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n CLOUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n CLPROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n CLSUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n* 'CLBUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CLCOMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CLDEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CLDEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CLIMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CLIMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CLINVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CLINVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CLINVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CLINVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CLINVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CLINVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CLINVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CLINVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CLINVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CLINVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CLINVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CLINVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CLINVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CLINVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CLINVALID_HOST_PTR', Returned if host_ptr is NULL and 'CLMEM_USE_HOST_PTR'\nor 'CLMEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CLMEM_COPY_HOST_PTR' or 'CLMEM_USE_HOST_PTR' are not set in flags.\n\n * 'CLINVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CLINVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CLINVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CLINVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CLINVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CLINVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CLINVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CLINVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CLINVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CLINVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CLINVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CLINVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CLINVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CLINVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CLINVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CLINVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CLINVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CLMAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CLMEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CLMEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CLOUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CLPROFILING_INFO_NOT_AVAILABLE', Returned if the 'CLQUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CLSUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CLSUCCESS\n then return $ Right v\n else return $ Left errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} deriving( Show ) #}\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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\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\n#c\nenum CLDeviceLocalMemType {\n CLLOCAL=CL_LOCAL, CLGLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {} deriving( Show ) #}\n\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\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\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\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n CLMEM_READ_WRITE=CL_MEM_READ_WRITE,\n CLMEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n CLMEM_READ_ONLY=CL_MEM_READ_ONLY,\n CLMEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n CLMEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n CLMEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n* 'CLMEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CLMEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CLMEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CLMEM_ALLOC_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CLMEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CLMEM_COPY_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually\nexclusive. 'CLMEM_COPY_HOST_PTR' can be used with 'CLMEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n--getImageChannelOrder :: CLImageFormat_p -> IO CLImageChannelOrder_\n--getImageChannelOrder = {#get cl_image_format->image_channel_order#}\n\n--getImageChannelDataType :: CLImageFormat_p -> IO CLImageChannelDataType_\n--getImageChannelDataType = {#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 return $ CLImageFormat 0 0\n \ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . toEnum . fromIntegral\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . toEnum . fromIntegral\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . toEnum . fromIntegral\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CLEXEC_ERROR\n | otherwise = Just . toEnum . fromIntegral $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\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\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\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":"1bbeb3aa5431707f280d4d5868f2abc65e8aa327","subject":"lcb_store3 callback","message":"lcb_store3 callback\n","repos":"asvyazin\/libcouchbase.hs","old_file":"src\/Couchbase\/Raw.chs","new_file":"src\/Couchbase\/Raw.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule Couchbase.Raw where\n\n\nimport qualified Data.ByteString as B\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\n\n#define __int128 int\n\n\n#include \n\n\n{# context lib=\"libcouchbase\" #}\n\n\n{# enum lcb_type_t as LcbType {underscoreToCase} deriving (Eq, Show) #}\n\n\n{# pointer *lcb_create_st as LcbCreateSt #}\n\n\n{# pointer lcb_t as Lcb foreign finalizer lcb_destroy newtype #}\n\n\n{# enum lcb_error_t as LcbError {underscoreToCase} deriving (Eq, Show) #}\n\n\n{# fun lcb_get_errtype as ^ {`LcbError'} -> `Int' #}\n\n\n{# fun lcb_strerror as ^ {`Lcb', `LcbError'} -> `String' #}\n\n\n-- lcb_errmap_default\n-- lcb_set_errmap_callback\n\n\nnewLcb :: Ptr Lcb -> IO Lcb\nnewLcb ptr =\n Lcb <$> newForeignPtr lcb_destroy ptr\n\n\npeekLcb :: Ptr (Ptr Lcb) -> IO Lcb\npeekLcb ptr =\n peek ptr >>= newLcb\n\n\n{# fun lcb_create as lcbCreateRaw {alloca- `Lcb' peekLcb*, `LcbCreateSt'} -> `LcbError' #}\n\n\ndata ConnectionParams =\n ConnectionParams\n { connectionString :: String\n , password :: Maybe String\n , lcbType :: LcbType\n } deriving (Show)\n\n\nlcbCreate :: ConnectionParams -> IO (LcbError, Lcb)\nlcbCreate params = do\n allocaBytes {# sizeof lcb_create_st #} $ \\st -> do\n fillBytes st 0 {# sizeof lcb_create_st #}\n {# set lcb_create_st.version #} st 3\n {# set lcb_create_st.v.v3.type #} st $ fromIntegral $ fromEnum $ lcbType params\n withCString (connectionString params) $ \\connstr -> do\n {# set lcb_create_st.v.v3.connstr #} st connstr\n case password params of\n Just pwd ->\n withCString pwd $ \\passwd -> do\n {# set lcb_create_st.v.v3.passwd #} st passwd\n lcbCreateRaw st\n Nothing ->\n lcbCreateRaw st\n\n\n{# fun lcb_connect as ^ {`Lcb'} -> `LcbError' #}\n\n\n-- lcb_set_bootstrap_callback\n\n\n{# fun lcb_get_bootstrap_status as ^ {`Lcb'} -> `LcbError' #}\n\n\n{# enum lcb_CALLBACKTYPE as LcbCallbackType {underscoreToCase} deriving (Eq, Show) #}\n\n\ntype LcbCallbackRaw =\n Ptr Lcb -> CInt -> Ptr () -> IO ()\n\n\nforeign import ccall \"wrapper\"\n mkLcbCallbackFunPtr :: LcbCallbackRaw -> IO (FunPtr LcbCallbackRaw)\n\n\ntype LcbCallback =\n LcbCallbackType -> Ptr () -> IO ()\n\n\nwithLcbCallback :: LcbCallback -> (FunPtr LcbCallbackRaw -> IO a) -> IO a\nwithLcbCallback callback f =\n mkLcbCallbackFunPtr (\\ _ cb p -> callback (toEnum (fromIntegral cb)) p) >>= f\n\n\ntype OldCallbackPtr = FunPtr LcbCallbackRaw\n\n\n{# fun lcb_install_callback3 as ^ {`Lcb', `LcbCallbackType', withLcbCallback* `LcbCallback'} -> `OldCallbackPtr' id #}\n\n\n-- lcb_get_callback3\n-- lcb_strcbtype\n-- lcb_get3\n-- lcb_rget3\n\n\n{# enum lcb_KVBUFTYPE as LcbKvBufType {underscoreToCase} deriving (Eq, Show) #}\n\n\n_lcbKreqSimple :: Ptr () -> B.ByteString -> IO ()\n_lcbKreqSimple p bs =\n B.useAsCStringLen bs $ \\(pv, len) -> do\n {# set lcb_KEYBUF.type #} p $ fromIntegral $ fromEnum LcbKvCopy\n {# set lcb_KEYBUF.contig.bytes #} p $ castPtr pv\n {# set lcb_KEYBUF.contig.nbytes #} p $ fromIntegral len\n\n\n_lcbCmdStoreSetKey :: Ptr () -> B.ByteString -> IO ()\n_lcbCmdStoreSetKey p bs =\n _lcbKreqSimple (plusPtr p {# offsetof lcb_CMDSTORE.key #}) bs\n\n\n_lcbCmdStoreSetValue :: Ptr () -> B.ByteString -> IO ()\n_lcbCmdStoreSetValue p bs =\n B.useAsCStringLen bs $ \\(pv, len) -> do\n {# set lcb_CMDSTORE.value.vtype #} p $ fromIntegral $ fromEnum LcbKvCopy\n {# set lcb_CMDSTORE.value.u_buf.contig.bytes #} p $ castPtr pv\n {# set lcb_CMDSTORE.value.u_buf.contig.nbytes #} p $ fromIntegral len\n\n\n{# enum lcb_storage_t as LcbStorage {underscoreToCase} deriving (Eq, Show) #}\n\n\ndata LcbCmdStore =\n LcbCmdStore\n { operation :: LcbStorage\n , key :: B.ByteString\n , value :: B.ByteString\n } deriving (Show)\n\n\n{# fun lcb_store3 as lcbStore3Raw {`Lcb', `Ptr ()', `Ptr ()'} -> `LcbError' #}\n\n\ntype LcbCookie = Ptr ()\n\n\nlcbStore3 :: Lcb -> LcbCookie -> LcbCmdStore -> IO LcbError\nlcbStore3 lcb cookie cmd =\n allocaBytes {# sizeof lcb_CMDSTORE #} $ \\st -> do\n fillBytes st 0 {# sizeof lcb_CMDSTORE #}\n {# set lcb_CMDSTORE.operation #} st $ fromIntegral $ fromEnum $ operation cmd\n _lcbCmdStoreSetKey st $ key cmd\n _lcbCmdStoreSetValue st $ value cmd\n lcbStore3Raw lcb cookie st\n\n\n{# pointer *lcb_RESPSTORE as LcbRespStorePtr #}\n\n\nlcbRespStoreGetOp :: LcbRespStorePtr -> IO LcbStorage\nlcbRespStoreGetOp p = (toEnum . fromIntegral) <$> {# get lcb_RESPSTORE.op #} p\n\n\n_lcbRespBaseGetCookie :: Ptr () -> IO LcbCookie\n_lcbRespBaseGetCookie p = {# get lcb_RESPBASE.cookie #} p\n\n\nlcbRespStoreGetCookie :: LcbRespStorePtr -> IO LcbCookie\nlcbRespStoreGetCookie = _lcbRespBaseGetCookie . castPtr\n\n\n_lcbRespBaseGetKey :: Ptr () -> IO B.ByteString\n_lcbRespBaseGetKey p = do\n pv <- {# get lcb_RESPBASE.key #} p\n len <- {# get lcb_RESPBASE.nkey #} p\n B.packCStringLen (castPtr pv, fromIntegral len)\n\n\nlcbRespStoreGetKey :: LcbRespStorePtr -> IO B.ByteString\nlcbRespStoreGetKey = _lcbRespBaseGetKey . castPtr\n\n\n_lcbRespBaseGetStatus :: Ptr () -> IO LcbError\n_lcbRespBaseGetStatus p = (toEnum . fromIntegral) <$> {# get lcb_RESPBASE.rc #} p\n\n\nlcbRespStoreGetStatus :: LcbRespStorePtr -> IO LcbError\nlcbRespStoreGetStatus = _lcbRespBaseGetStatus . castPtr\n\n\ntype LcbCas = {# type lcb_CAS #}\n\n\n_lcbRespBaseGetCas :: Ptr () -> IO LcbCas\n_lcbRespBaseGetCas p = {# get lcb_RESPBASE.cas #} p\n\n\nlcbRespStoreGetCas :: LcbRespStorePtr -> IO LcbCas\nlcbRespStoreGetCas = _lcbRespBaseGetCas . castPtr\n\n\ntype LcbRespStoreCallback =\n LcbRespStorePtr -> IO ()\n\n\nlcbInstallRespStoreCallback :: Lcb -> LcbRespStoreCallback -> IO OldCallbackPtr\nlcbInstallRespStoreCallback lcb callback =\n lcbInstallCallback3 lcb LcbCallbackStore $ \\ _ p -> callback (castPtr p)\n\n\n-- lcb_remove3\n-- lcb_endure3_ctxnew\n-- lcb_storedur3\n-- lcb_durability_validate\n-- lcb_observe3_ctxnew\n-- lcb_observe_seqno3\n-- lcb_resp_get_mutation_token\n-- lcb_get_mutation_token\n-- lcb_counter3\n-- lcb_unlock3\n-- lcb_touch3\n-- lcb_stats3\n-- lcb_server_versions3\n-- lcb_server_verbosity3\n-- lcb_cbflush3\n-- lcb_flush3\n-- lcb_http3\n-- lcb_cancel_http_request\n-- lcb_set_cookie\n-- lcb_get_cookie\n\n\n{# fun lcb_wait as ^ {`Lcb'} -> `LcbError' #}\n\n\n-- lcb_tick_nowait\n\n\n{# enum lcb_WAITFLAGS as LcbWaitFlags {underscoreToCase} deriving (Eq, Show) #}\n\n\n{# fun lcb_wait3 as ^ {`Lcb', `LcbWaitFlags'} -> `()' #}\n\n\n-- lcb_breakout\n-- lcb_is_waiting\n-- lcb_refresh_config\n-- lcb_sched_enter\n-- lcb_sched_leave\n-- lcb_sched_fail\n-- lcb_sched_flush\n\n\n{# fun lcb_destroy as ^ {`Lcb'} -> `()' #}\n\n\n-- lcb_set_destroy_callback\n-- lcb_destroy_async\n-- lcb_get_node\n-- lcb_get_keynode\n-- lcb_get_num_replicas\n-- lcb_get_num_nodes\n-- lcb_get_server_list\n-- lcb_dump\n-- lcb_cntl\n-- lcb_cntl_string\n-- lcb_cntl_setu32\n-- lcb_cntl_getu32\n-- lcb_cntl_exists\n-- lcb_enable_timings\n-- lcb_disable_timings\n-- lcb_get_timings\n-- lcb_get_version\n-- lcb_supports_feature\n-- lcb_mem_alloc\n-- lcb_mem_free\n-- lcb_run_loop\n-- lcb_stop_loop\n-- lcb_nstime\n-- lcb_histogram_create\n-- lcb_histogram_destroy\n-- lcb_histogram_record\n-- lcb_histogram_read\n-- lcb_histogram_print\n-- lcb_subdoc3\n-- lcb_sdresult_next\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule Couchbase.Raw where\n\n\nimport qualified Data.ByteString as B\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\n\n#define __int128 int\n\n\n#include \n\n\n{# context lib=\"libcouchbase\" #}\n\n\n{# enum lcb_type_t as LcbType {underscoreToCase} deriving (Eq, Show) #}\n\n\n{# pointer *lcb_create_st as LcbCreateSt #}\n\n\n{# pointer lcb_t as Lcb foreign finalizer lcb_destroy newtype #}\n\n\n{# enum lcb_error_t as LcbError {underscoreToCase} deriving (Eq, Show) #}\n\n\n{# fun lcb_get_errtype as ^ {`LcbError'} -> `Int' #}\n\n\n{# fun lcb_strerror as ^ {`Lcb', `LcbError'} -> `String' #}\n\n\n-- lcb_errmap_default\n-- lcb_set_errmap_callback\n\n\nnewLcb :: Ptr Lcb -> IO Lcb\nnewLcb ptr =\n Lcb <$> newForeignPtr lcb_destroy ptr\n\n\npeekLcb :: Ptr (Ptr Lcb) -> IO Lcb\npeekLcb ptr =\n peek ptr >>= newLcb\n\n\n{# fun lcb_create as lcbCreateRaw {alloca- `Lcb' peekLcb*, `LcbCreateSt'} -> `LcbError' #}\n\n\ndata ConnectionParams =\n ConnectionParams\n { connectionString :: String\n , password :: Maybe String\n , lcbType :: LcbType\n } deriving (Show)\n\n\nlcbCreate :: ConnectionParams -> IO (LcbError, Lcb)\nlcbCreate params = do\n allocaBytes {# sizeof lcb_create_st #} $ \\st -> do\n fillBytes st 0 {# sizeof lcb_create_st #}\n {# set lcb_create_st.version #} st 3\n {# set lcb_create_st.v.v3.type #} st $ fromIntegral $ fromEnum $ lcbType params\n withCString (connectionString params) $ \\connstr -> do\n {# set lcb_create_st.v.v3.connstr #} st connstr\n case password params of\n Just pwd ->\n withCString pwd $ \\passwd -> do\n {# set lcb_create_st.v.v3.passwd #} st passwd\n lcbCreateRaw st\n Nothing ->\n lcbCreateRaw st\n\n\n{# fun lcb_connect as ^ {`Lcb'} -> `LcbError' #}\n\n\n-- lcb_set_bootstrap_callback\n\n\n{# fun lcb_get_bootstrap_status as ^ {`Lcb'} -> `LcbError' #}\n\n\n-- lcb_install_callback3\n-- lcb_get_callback3\n-- lcb_strcbtype\n-- lcb_get3\n-- lcb_rget3\n\n\n{# enum lcb_KVBUFTYPE as LcbKvBufType {underscoreToCase} deriving (Eq, Show) #}\n\n\n_lcbKreqSimple :: Ptr () -> B.ByteString -> IO ()\n_lcbKreqSimple p bs =\n B.useAsCStringLen bs $ \\(pv, len) -> do\n {# set lcb_KEYBUF.type #} p $ fromIntegral $ fromEnum LcbKvCopy\n {# set lcb_KEYBUF.contig.bytes #} p $ castPtr pv\n {# set lcb_KEYBUF.contig.nbytes #} p $ fromIntegral len\n\n\n_lcbCmdStoreSetKey :: Ptr () -> B.ByteString -> IO ()\n_lcbCmdStoreSetKey p bs =\n _lcbKreqSimple (plusPtr p {# offsetof lcb_CMDSTORE.key #}) bs\n\n\n_lcbCmdStoreSetValue :: Ptr () -> B.ByteString -> IO ()\n_lcbCmdStoreSetValue p bs =\n B.useAsCStringLen bs $ \\(pv, len) -> do\n {# set lcb_CMDSTORE.value.vtype #} p $ fromIntegral $ fromEnum LcbKvCopy\n {# set lcb_CMDSTORE.value.u_buf.contig.bytes #} p $ castPtr pv\n {# set lcb_CMDSTORE.value.u_buf.contig.nbytes #} p $ fromIntegral len\n\n\n{# enum lcb_storage_t as LcbStorage {underscoreToCase} deriving (Eq, Show) #}\n\n\ndata LcbCmdStore =\n LcbCmdStore\n { operation :: LcbStorage\n , key :: B.ByteString\n , value :: B.ByteString\n } deriving (Show)\n\n\n{# fun lcb_store3 as lcbStore3Raw {`Lcb', `Ptr ()', `Ptr ()'} -> `LcbError' #}\n\n\ntype LcbCookie = Ptr ()\n\n\nlcbStore3 :: Lcb -> LcbCookie -> LcbCmdStore -> IO LcbError\nlcbStore3 lcb cookie cmd =\n allocaBytes {# sizeof lcb_CMDSTORE #} $ \\st -> do\n fillBytes st 0 {# sizeof lcb_CMDSTORE #}\n {# set lcb_CMDSTORE.operation #} st $ fromIntegral $ fromEnum $ operation cmd\n _lcbCmdStoreSetKey st $ key cmd\n _lcbCmdStoreSetValue st $ value cmd\n lcbStore3Raw lcb cookie st\n\n\n-- lcb_remove3\n-- lcb_endure3_ctxnew\n-- lcb_storedur3\n-- lcb_durability_validate\n-- lcb_observe3_ctxnew\n-- lcb_observe_seqno3\n-- lcb_resp_get_mutation_token\n-- lcb_get_mutation_token\n-- lcb_counter3\n-- lcb_unlock3\n-- lcb_touch3\n-- lcb_stats3\n-- lcb_server_versions3\n-- lcb_server_verbosity3\n-- lcb_cbflush3\n-- lcb_flush3\n-- lcb_http3\n-- lcb_cancel_http_request\n-- lcb_set_cookie\n-- lcb_get_cookie\n\n\n{# fun lcb_wait as ^ {`Lcb'} -> `LcbError' #}\n\n\n-- lcb_tick_nowait\n\n\n{# enum lcb_WAITFLAGS as LcbWaitFlags {underscoreToCase} deriving (Eq, Show) #}\n\n\n{# fun lcb_wait3 as ^ {`Lcb', `LcbWaitFlags'} -> `()' #}\n\n\n-- lcb_breakout\n-- lcb_is_waiting\n-- lcb_refresh_config\n-- lcb_sched_enter\n-- lcb_sched_leave\n-- lcb_sched_fail\n-- lcb_sched_flush\n\n\n{# fun lcb_destroy as ^ {`Lcb'} -> `()' #}\n\n\n-- lcb_set_destroy_callback\n-- lcb_destroy_async\n-- lcb_get_node\n-- lcb_get_keynode\n-- lcb_get_num_replicas\n-- lcb_get_num_nodes\n-- lcb_get_server_list\n-- lcb_dump\n-- lcb_cntl\n-- lcb_cntl_string\n-- lcb_cntl_setu32\n-- lcb_cntl_getu32\n-- lcb_cntl_exists\n-- lcb_enable_timings\n-- lcb_disable_timings\n-- lcb_get_timings\n-- lcb_get_version\n-- lcb_supports_feature\n-- lcb_mem_alloc\n-- lcb_mem_free\n-- lcb_run_loop\n-- lcb_stop_loop\n-- lcb_nstime\n-- lcb_histogram_create\n-- lcb_histogram_destroy\n-- lcb_histogram_record\n-- lcb_histogram_read\n-- lcb_histogram_print\n-- lcb_subdoc3\n-- lcb_sdresult_next\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c676670774401227a57a7b19c4a6b3a10588c985","subject":"whitespace only","message":"whitespace only\n","repos":"GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto,GaloisInc\/hacrypto","old_file":"lib\/Implementation\/Cryptodev.chs","new_file":"lib\/Implementation\/Cryptodev.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1309c054dd1e1a412912327766a69def09b49d22","subject":"Add Eq and Show instances for EngineStatus and XineError","message":"Add Eq and Show instances for EngineStatus and XineError\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(..),\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.\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","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.\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\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\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":"1812afaf6649e2c697d9ea7e5ad30c0f6f28c868","subject":"Remove Gtk.Signals from GtkInternals.chs","message":"Remove Gtk.Signals from GtkInternals.chs\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"d5d4bb6daaafc29380916293335f5c061a8bd60f","subject":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)","message":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0734b4d983b971925ec5ab3d59e645d6f5214d1f","subject":"Index","message":"Index\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\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 if res == 0\n then fmap (Right . Index) $ peek idx\n else return . Left . toEnum . fromIntegral $ res\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\n{-\ndo\n let repo = nullPtr\n pstr <- newCString path\n res <- {#call git_repository_open#} repo pstr\n return $ case res of\n 0 -> Right $ Repository repo\n n -> Left . toEnum . fromIntegral $ n\n-}\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"45942e8285d883e7ea4a9ca4af1881a897412713","subject":"gstreamer: M.S.G.Core.ElementFactory: Control.Monad.>","message":"gstreamer: M.S.G.Core.ElementFactory: Control.Monad.>\n\ndarcs-hash:20080520011633-21862-c1276cd02641d451cec26ccc91fe6759378480ba.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"8cbd5491dcf15cd94cecf95ccb4a1dc6e1e8847f","subject":"Remove unused import.","message":"Remove unused import.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Lib\/Metadata.chs","new_file":"src\/Network\/Grpc\/Lib\/Metadata.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--------------------------------------------------------------------------------\nmodule Network.Grpc.Lib.Metadata (\n Metadata(..)\n , MetadataPtr\n , mallocMetadata\n\n , isKeyValid\n , isNonBinValueValid\n , isBinaryHeader\n\n , MetadataArray\n , mallocMetadataArray\n , readMetadataArray\n , freeMetadataArray\n ) where\n\nimport qualified Foreign.C.Types as C\nimport qualified Foreign.Ptr as C\nimport qualified Foreign.ForeignPtr as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Array as C\nimport qualified Foreign.Storable as C\n\nimport Control.Monad\nimport Data.Word (Word8)\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport Data.ByteString (ByteString)\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\n{#pointer *grpc_metadata as MetadataPtr -> Metadata#}\n\ndata Metadata = Metadata !ByteString !ByteString !{#type uint32_t#} deriving (Show)\n\ninstance C.Storable Metadata where\n sizeOf _ = {#sizeof grpc_metadata#}\n alignment _ = {#alignof grpc_metadata#}\n peek p = do\n keyPtr <- {#get grpc_metadata->key#} p\n valuePtr <- {#get grpc_metadata->value#} p\n valueLength <- {#get grpc_metadata->value_length#} p\n key <- B.packCString keyPtr\n value <- B.packCStringLen (valuePtr, fromIntegral valueLength)\n flags <- {#get grpc_metadata->flags#} p\n return $! Metadata key value flags\n poke _ _ = error \"Storable Metadata: poke not implemented\"\n\ndata CMetadataArray\n{#pointer *metadata_array as MetadataArray -> CMetadataArray#}\n\n{#fun unsafe metadata_array_init as ^\n {`MetadataArray'} -> `()'#}\n\n{#fun unsafe metadata_array_destroy as ^\n {`MetadataArray'} -> `()'#}\n\nmallocMetadata :: [Metadata] -> IO (MetadataPtr, IO ())\nmallocMetadata mds = do\n arr <- C.mallocBytes (length mds * {#sizeof grpc_metadata#})\n ptrs <- forM (zip [0..] mds) $ \\(i, md) ->\n writeMetadata md (arr `C.plusPtr` (i * {#sizeof grpc_metadata#}))\n return (C.castPtr arr, mapM_ C.free (arr : concat ptrs))\n where\n writeMetadata (Metadata key value flags) arr_ptr = do\n key_ptr <- asCString key\n value_ptr <- asCString value\n {#set grpc_metadata->key#} arr_ptr key_ptr\n {#set grpc_metadata->value#} arr_ptr value_ptr\n {#set grpc_metadata->value_length#} arr_ptr (fromIntegral (B.length value))\n {#set grpc_metadata->flags#} arr_ptr flags\n return [key_ptr, value_ptr]\n\n -- | Create null terminated C-string.\n asCString :: ByteString -> IO (C.Ptr C.CChar)\n asCString (B.PS fp o l) = do\n buf <- C.mallocBytes (l+1)\n C.withForeignPtr fp $ \\p -> do\n B.memcpy buf (p `C.plusPtr` o) (fromIntegral l)\n C.pokeByteOff buf l (0::Word8)\n return (C.castPtr buf)\n\nmallocMetadataArray :: IO (C.Ptr CMetadataArray)\nmallocMetadataArray = do \n ptr <- C.mallocBytes {#sizeof grpc_metadata_array#}\n metadataArrayInit ptr\n return ptr\n\nfreeMetadataArray :: MetadataArray -> IO ()\nfreeMetadataArray arr = do\n metadataArrayDestroy arr\n C.free arr\n\nreadMetadataArray :: MetadataArray -> IO [Metadata]\nreadMetadataArray arr = do\n count <- {#get grpc_metadata_array->count#} arr\n metadataPtr <- {#get grpc_metadata_array->metadata#} arr\n C.peekArray (fromIntegral count) metadataPtr\n\n-- | Validate the key of a metadata pair.\n{#fun pure grpc_header_key_is_legal as isKeyValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Validate a non-binary value.\n{#fun pure grpc_header_nonbin_value_is_legal as isNonBinValueValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Is the key a binary key?\n{#fun pure grpc_is_binary_header as isBinaryHeader\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\nuseAsCStringLen :: Num a => B.ByteString -> ((C.Ptr C.CChar, a) -> IO b) -> IO b\nuseAsCStringLen bs act =\n B.useAsCStringLen bs $ \\(ptr, len) -> act (ptr, fromIntegral len)\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--------------------------------------------------------------------------------\nmodule Network.Grpc.Lib.Metadata (\n Metadata(..)\n , MetadataPtr\n , mallocMetadata\n\n , isKeyValid\n , isNonBinValueValid\n , isBinaryHeader\n\n , MetadataArray\n , mallocMetadataArray\n , readMetadataArray\n , freeMetadataArray\n ) where\n\nimport qualified Foreign.C.Types as C\nimport qualified Foreign.Ptr as C\nimport qualified Foreign.ForeignPtr as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Array as C\nimport qualified Foreign.Storable as C\n\nimport Control.Monad\nimport Control.Exception\nimport Data.Word (Word8)\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport Data.ByteString (ByteString)\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\n{#pointer *grpc_metadata as MetadataPtr -> Metadata#}\n\ndata Metadata = Metadata !ByteString !ByteString !{#type uint32_t#} deriving (Show)\n\ninstance C.Storable Metadata where\n sizeOf _ = {#sizeof grpc_metadata#}\n alignment _ = {#alignof grpc_metadata#}\n peek p = do\n keyPtr <- {#get grpc_metadata->key#} p\n valuePtr <- {#get grpc_metadata->value#} p\n valueLength <- {#get grpc_metadata->value_length#} p\n key <- B.packCString keyPtr\n value <- B.packCStringLen (valuePtr, fromIntegral valueLength)\n flags <- {#get grpc_metadata->flags#} p\n return $! Metadata key value flags\n poke _ _ = error \"Storable Metadata: poke not implemented\"\n\ndata CMetadataArray\n{#pointer *metadata_array as MetadataArray -> CMetadataArray#}\n\n{#fun unsafe metadata_array_init as ^\n {`MetadataArray'} -> `()'#}\n\n{#fun unsafe metadata_array_destroy as ^\n {`MetadataArray'} -> `()'#}\n\nmallocMetadata :: [Metadata] -> IO (MetadataPtr, IO ())\nmallocMetadata mds = do\n arr <- C.mallocBytes (length mds * {#sizeof grpc_metadata#})\n ptrs <- forM (zip [0..] mds) $ \\(i, md) ->\n writeMetadata md (arr `C.plusPtr` (i * {#sizeof grpc_metadata#}))\n return (C.castPtr arr, mapM_ C.free (arr : concat ptrs))\n where\n writeMetadata (Metadata key value flags) arr_ptr = do\n key_ptr <- asCString key\n value_ptr <- asCString value\n {#set grpc_metadata->key#} arr_ptr key_ptr\n {#set grpc_metadata->value#} arr_ptr value_ptr\n {#set grpc_metadata->value_length#} arr_ptr (fromIntegral (B.length value))\n {#set grpc_metadata->flags#} arr_ptr flags\n return [key_ptr, value_ptr]\n\n -- | Create null terminated C-string.\n asCString :: ByteString -> IO (C.Ptr C.CChar)\n asCString (B.PS fp o l) = do\n buf <- C.mallocBytes (l+1)\n C.withForeignPtr fp $ \\p -> do\n B.memcpy buf (p `C.plusPtr` o) (fromIntegral l)\n C.pokeByteOff buf l (0::Word8)\n return (C.castPtr buf)\n\nmallocMetadataArray :: IO (C.Ptr CMetadataArray)\nmallocMetadataArray = do \n ptr <- C.mallocBytes {#sizeof grpc_metadata_array#}\n metadataArrayInit ptr\n return ptr\n\nfreeMetadataArray :: MetadataArray -> IO ()\nfreeMetadataArray arr = do\n metadataArrayDestroy arr\n C.free arr\n\nreadMetadataArray :: MetadataArray -> IO [Metadata]\nreadMetadataArray arr = do\n count <- {#get grpc_metadata_array->count#} arr\n metadataPtr <- {#get grpc_metadata_array->metadata#} arr\n C.peekArray (fromIntegral count) metadataPtr\n\n-- | Validate the key of a metadata pair.\n{#fun pure grpc_header_key_is_legal as isKeyValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Validate a non-binary value.\n{#fun pure grpc_header_nonbin_value_is_legal as isNonBinValueValid\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\n-- | Is the key a binary key?\n{#fun pure grpc_is_binary_header as isBinaryHeader\n { 'useAsCStringLen'* `B.ByteString'&} -> `Bool' #}\n\nuseAsCStringLen :: Num a => B.ByteString -> ((C.Ptr C.CChar, a) -> IO b) -> IO b\nuseAsCStringLen bs act =\n B.useAsCStringLen bs $ \\(ptr, len) -> act (ptr, fromIntegral len)\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"9d2393907dcdf7acc2993819742dbf2cfad96285","subject":"On close, wait to receive status on client.","message":"On close, wait to receive status on client.\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\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\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 let m' = do\n x <- m\n _ <- waitForStatus\n throwIfErrorStatus\n return x\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\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\nthrowIfErrorStatus :: Rpc req resp ()\nthrowIfErrorStatus =\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 (readIORef . initialMDRef)\n case status of\n Just md -> return md\n Nothing ->\n branchOnStatus\n (joinClientRWOp clientWaitForInitialMetadata)\n (joinClientRWOp clientWaitForInitialMetadata)\n (\\code msg -> lift (throwE (StatusError code msg)))\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 throwIfErrorStatus\n encoder <- askEncoder\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n throwIfErrorStatus\n joinClientRWOp clientSendHalfClose\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n _ <- waitForStatus\n clientRWOp clientCloseCall\n throwIfErrorStatus\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\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 (readIORef . initialMDRef)\n case status of\n Just md -> return md\n Nothing ->\n branchOnStatus\n (joinClientRWOp clientWaitForInitialMetadata)\n (joinClientRWOp clientWaitForInitialMetadata)\n (\\code msg -> lift (throwE (StatusError code msg)))\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","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"e159dbd69321392fc2178a039ed345a46cbed448","subject":"Adjust webResourceGetMimeType.","message":"Adjust webResourceGetMimeType.","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"33f540416bc90c3a0e2b741e15e74c37bc1eb2c4","subject":"more descriptive error messages","message":"more descriptive error messages\n\nIgnore-this: 3cd2d807debfaf06f11ddb1b06860930\n\ndarcs-hash:20090721232441-115f9-1ad3cfccdfb76cae10c60475eb133e1bcc7f9370.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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\nnewDevicePtr :: Ptr () -> IO (DevicePtr ())\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 ()))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr ptr\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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 (),Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr 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\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 (),Int64))\nmalloc3D = moduleErr \"malloc3D\" \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr () -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr ()' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr () -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr ()' ,\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 () -- ^ 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\nnewDevicePtr :: Ptr () -> IO (DevicePtr ())\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 ()))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr ptr\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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 (),Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr 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\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 (),Int64))\nmalloc3D = error \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr () -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr ()' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr () -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr ()' ,\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 () -- ^ 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 = error \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2f3dc3fa978f4c0e4d94588f43c943f992a8184b","subject":"this utility from the driver side as well","message":"this utility from the driver side as well\n\nIgnore-this: f11aba61078a41269d2ddd7e690a4fa1\n\ndarcs-hash:20091210040032-9241b-498cea3938b2bacaaf62670935020f8e4000a458.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/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 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 (Either String Int)\ndriverVersion = resultIfOk `fmap` 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 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 (Either String Int)\ndriverVersion = resultIfOk `fmap` 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":"89d7918ee248c559d90fd3a23f09af32ecbb5f86","subject":"build fix for CUDA < 5","message":"build fix for CUDA < 5\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Exec.chs","new_file":"Foreign\/CUDA\/Runtime\/Exec.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TemplateHaskell #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Exec\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for C-for-CUDA runtime interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Exec (\n\n -- * Kernel Execution\n Fun, FunAttributes(..), FunParam(..), CacheConfig(..),\n attributes, setConfig, setParams, setCacheConfig, launch, launchKernel,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#c\ntypedef struct cudaFuncAttributes cudaFuncAttributes;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function.\n--\n-- Note that the use of a string naming a function was deprecated in CUDA 4.1\n-- and removed in CUDA 5.0.\n--\n#if CUDART_VERSION >= 5000\ntype Fun = FunPtr ()\n#else\ntype Fun = String\n#endif\n\n\n--\n-- Function Attributes\n--\n{# pointer *cudaFuncAttributes as ^ foreign -> FunAttributes nocode #}\n\ndata FunAttributes = FunAttributes\n {\n constSizeBytes :: !Int64,\n localSizeBytes :: !Int64,\n sharedSizeBytes :: !Int64,\n maxKernelThreadsPerBlock :: !Int, -- ^ maximum block size that can be successively launched (based on register usage)\n numRegs :: !Int -- ^ number of registers required for each thread\n }\n deriving (Show)\n\ninstance Storable FunAttributes where\n sizeOf _ = {# sizeof cudaFuncAttributes #}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"Can not poke Foreign.CUDA.Runtime.FunAttributes\"\n peek p = do\n cs <- cIntConv `fmap` {#get cudaFuncAttributes.constSizeBytes#} p\n ls <- cIntConv `fmap` {#get cudaFuncAttributes.localSizeBytes#} p\n ss <- cIntConv `fmap` {#get cudaFuncAttributes.sharedSizeBytes#} p\n tb <- cIntConv `fmap` {#get cudaFuncAttributes.maxThreadsPerBlock#} p\n nr <- cIntConv `fmap` {#get cudaFuncAttributes.numRegs#} p\n\n return FunAttributes\n {\n constSizeBytes = cs,\n localSizeBytes = ls,\n sharedSizeBytes = ss,\n maxKernelThreadsPerBlock = tb,\n numRegs = nr\n }\n\n#if CUDART_VERSION < 3000\ndata CacheConfig\n#else\n-- |\n-- Cache configuration preference\n--\n{# enum cudaFuncCache as CacheConfig\n { }\n with prefix=\"cudaFuncCachePrefer\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters. Doubles will be converted to an internal float\n-- representation on devices that do not support doubles natively.\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n DArg :: !Double -> FunParam\n VArg :: Storable a => !a -> FunParam\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Obtain the attributes of the named @__global__@ device function. This\n-- itemises the requirements to successfully launch the given kernel.\n--\n{-# INLINEABLE attributes #-}\nattributes :: Fun -> IO FunAttributes\nattributes !fn = resultIfOk =<< cudaFuncGetAttributes fn\n\n{-# INLINE cudaFuncGetAttributes #-}\n{# fun unsafe cudaFuncGetAttributes\n { alloca- `FunAttributes' peek*\n , withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the grid and block dimensions for a device call. Used in conjunction\n-- with 'setParams', this pushes data onto the execution stack that will be\n-- popped when a function is 'launch'ed.\n--\n{-# INLINEABLE setConfig #-}\nsetConfig :: (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ block dimensions\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ associated processing stream\n -> IO ()\nsetConfig (!gx,!gy) (!bx,!by,!bz) !sharedMem !mst =\n nothingIfOk =<<\n cudaConfigureCallSimple gx gy bx by bz sharedMem (maybe defaultStream id mst)\n\n\n--\n-- The FFI does not support passing deferenced structures to C functions, as\n-- this is highly platform\/compiler dependent. Wrap our own function stub\n-- accepting plain integers.\n--\n{-# INLINE cudaConfigureCallSimple #-}\n{# fun unsafe cudaConfigureCallSimple\n { `Int', `Int'\n , `Int', `Int', `Int'\n , cIntConv `Int64'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the argument parameters that will be passed to the next kernel\n-- invocation. This is used in conjunction with 'setConfig' to control kernel\n-- execution.\n--\n{-# INLINEABLE setParams #-}\nsetParams :: [FunParam] -> IO ()\nsetParams = foldM_ k 0\n where\n k !offset !arg = do\n let s = size arg\n set arg s offset >>= nothingIfOk\n return (offset + s)\n\n size (IArg _) = sizeOf (undefined :: Int)\n size (FArg _) = sizeOf (undefined :: Float)\n size (DArg _) = sizeOf (undefined :: Double)\n size (VArg a) = sizeOf a\n\n set (IArg v) s o = cudaSetupArgument v s o\n set (FArg v) s o = cudaSetupArgument v s o\n set (VArg v) s o = cudaSetupArgument v s o\n set (DArg v) s o =\n cudaSetDoubleForDevice v >>= resultIfOk >>= \\d ->\n cudaSetupArgument d s o\n\n\n{-# INLINE cudaSetupArgument #-}\n{# fun unsafe cudaSetupArgument\n `Storable a' =>\n { with'* `a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n\n{-# INLINE cudaSetDoubleForDevice #-}\n{# fun unsafe cudaSetDoubleForDevice\n { with'* `Double' peek'* } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n peek' = peek . castPtr\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 setCacheConfig #-}\nsetCacheConfig :: Fun -> CacheConfig -> IO ()\n#if CUDART_VERSION < 3000\nsetCacheConfig _ _ = requireSDK 'setCacheConfig 3.0\n#else\nsetCacheConfig !fn !pref = nothingIfOk =<< cudaFuncSetCacheConfig fn pref\n\n{-# INLINE cudaFuncSetCacheConfig #-}\n{# fun unsafe cudaFuncSetCacheConfig\n { withFun* `Fun'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Invoke the @__global__@ kernel function on the device. This must be preceded\n-- by a call to 'setConfig' and (if appropriate) 'setParams'.\n--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> IO ()\nlaunch !fn = nothingIfOk =<< cudaLaunch fn\n\n{-# INLINE cudaLaunch #-}\n{# fun unsafe cudaLaunch\n { withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy)@ grid of blocks, where each block contains\n-- @(tx * ty * tz)@ threads and has access to a given number of bytes of shared\n-- memory. The launch may also be associated with a specific 'Stream'.\n--\n{-# INLINEABLE launchKernel #-}\nlaunchKernel\n :: Fun -- ^ Device function symbol\n -> (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ (optional) execution stream\n -> [FunParam]\n -> IO ()\nlaunchKernel !fn !grid !block !sm !mst !args = do\n setConfig grid block sm mst\n setParams args\n launch fn\n\n--------------------------------------------------------------------------------\n-- Internals\n--------------------------------------------------------------------------------\n\n-- CUDA 5.0 changed the type of a kernel function from char* to void*\n--\n#if CUDART_VERSION >= 5000\nwithFun :: Fun -> (Ptr a -> IO b) -> IO b\nwithFun fn action = action (castFunPtrToPtr fn)\n#else\nwithFun :: Fun -> (Ptr CChar -> IO a) -> IO a\nwithFun = withCString\n#endif\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TemplateHaskell #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Exec\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for C-for-CUDA runtime interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Exec (\n\n -- * Kernel Execution\n Fun, FunAttributes(..), FunParam(..), CacheConfig(..),\n attributes, setConfig, setParams, setCacheConfig, launch, launchKernel,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#c\ntypedef struct cudaFuncAttributes cudaFuncAttributes;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function.\n--\n-- Note that the use of a string naming a function was deprecated in CUDA 4.1\n-- and removed in CUDA 5.0.\n--\n#if CUDART_VERSION >= 5000\ntype Fun = FunPtr ()\n#else\ntype Fun = String\n#endif\n\n\n--\n-- Function Attributes\n--\n{# pointer *cudaFuncAttributes as ^ foreign -> FunAttributes nocode #}\n\ndata FunAttributes = FunAttributes\n {\n constSizeBytes :: !Int64,\n localSizeBytes :: !Int64,\n sharedSizeBytes :: !Int64,\n maxKernelThreadsPerBlock :: !Int, -- ^ maximum block size that can be successively launched (based on register usage)\n numRegs :: !Int -- ^ number of registers required for each thread\n }\n deriving (Show)\n\ninstance Storable FunAttributes where\n sizeOf _ = {# sizeof cudaFuncAttributes #}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"Can not poke Foreign.CUDA.Runtime.FunAttributes\"\n peek p = do\n cs <- cIntConv `fmap` {#get cudaFuncAttributes.constSizeBytes#} p\n ls <- cIntConv `fmap` {#get cudaFuncAttributes.localSizeBytes#} p\n ss <- cIntConv `fmap` {#get cudaFuncAttributes.sharedSizeBytes#} p\n tb <- cIntConv `fmap` {#get cudaFuncAttributes.maxThreadsPerBlock#} p\n nr <- cIntConv `fmap` {#get cudaFuncAttributes.numRegs#} p\n\n return FunAttributes\n {\n constSizeBytes = cs,\n localSizeBytes = ls,\n sharedSizeBytes = ss,\n maxKernelThreadsPerBlock = tb,\n numRegs = nr\n }\n\n#if CUDART_VERSION < 3000\ndata CacheConfig\n#else\n-- |\n-- Cache configuration preference\n--\n{# enum cudaFuncCache as CacheConfig\n { }\n with prefix=\"cudaFuncCachePrefer\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters. Doubles will be converted to an internal float\n-- representation on devices that do not support doubles natively.\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n DArg :: !Double -> FunParam\n VArg :: Storable a => !a -> FunParam\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Obtain the attributes of the named @__global__@ device function. This\n-- itemises the requirements to successfully launch the given kernel.\n--\n{-# INLINEABLE attributes #-}\nattributes :: Fun -> IO FunAttributes\nattributes !fn = resultIfOk =<< cudaFuncGetAttributes fn\n\n{-# INLINE cudaFuncGetAttributes #-}\n{# fun unsafe cudaFuncGetAttributes\n { alloca- `FunAttributes' peek*\n , withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the grid and block dimensions for a device call. Used in conjunction\n-- with 'setParams', this pushes data onto the execution stack that will be\n-- popped when a function is 'launch'ed.\n--\n{-# INLINEABLE setConfig #-}\nsetConfig :: (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ block dimensions\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ associated processing stream\n -> IO ()\nsetConfig (!gx,!gy) (!bx,!by,!bz) !sharedMem !mst =\n nothingIfOk =<<\n cudaConfigureCallSimple gx gy bx by bz sharedMem (maybe defaultStream id mst)\n\n\n--\n-- The FFI does not support passing deferenced structures to C functions, as\n-- this is highly platform\/compiler dependent. Wrap our own function stub\n-- accepting plain integers.\n--\n{-# INLINE cudaConfigureCallSimple #-}\n{# fun unsafe cudaConfigureCallSimple\n { `Int', `Int'\n , `Int', `Int', `Int'\n , cIntConv `Int64'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the argument parameters that will be passed to the next kernel\n-- invocation. This is used in conjunction with 'setConfig' to control kernel\n-- execution.\n--\n{-# INLINEABLE setParams #-}\nsetParams :: [FunParam] -> IO ()\nsetParams = foldM_ k 0\n where\n k !offset !arg = do\n let s = size arg\n set arg s offset >>= nothingIfOk\n return (offset + s)\n\n size (IArg _) = sizeOf (undefined :: Int)\n size (FArg _) = sizeOf (undefined :: Float)\n size (DArg _) = sizeOf (undefined :: Double)\n size (VArg a) = sizeOf a\n\n set (IArg v) s o = cudaSetupArgument v s o\n set (FArg v) s o = cudaSetupArgument v s o\n set (VArg v) s o = cudaSetupArgument v s o\n set (DArg v) s o =\n cudaSetDoubleForDevice v >>= resultIfOk >>= \\d ->\n cudaSetupArgument d s o\n\n\n{-# INLINE cudaSetupArgument #-}\n{# fun unsafe cudaSetupArgument\n `Storable a' =>\n { with'* `a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n\n{-# INLINE cudaSetDoubleForDevice #-}\n{# fun unsafe cudaSetDoubleForDevice\n { with'* `Double' peek'* } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n peek' = peek . castPtr\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 setCacheConfig #-}\nsetCacheConfig :: Fun -> CacheConfig -> IO ()\n#if CUDART_VERSION < 3000\nsetCacheConfig _ _ = requireSDK 'setCacheConfig 3.0\n#else\nsetCacheConfig !fn !pref = nothingIfOk =<< cudaFuncSetCacheConfig fn pref\n\n{-# INLINE cudaFuncSetCacheConfig #-}\n{# fun unsafe cudaFuncSetCacheConfig\n { withFun* `Fun'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Invoke the @__global__@ kernel function on the device. This must be preceded\n-- by a call to 'setConfig' and (if appropriate) 'setParams'.\n--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> IO ()\nlaunch !fn = nothingIfOk =<< cudaLaunch fn\n\n{-# INLINE cudaLaunch #-}\n{# fun unsafe cudaLaunch\n { withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy)@ grid of blocks, where each block contains\n-- @(tx * ty * tz)@ threads and has access to a given number of bytes of shared\n-- memory. The launch may also be associated with a specific 'Stream'.\n--\n{-# INLINEABLE launchKernel #-}\nlaunchKernel\n :: Fun -- ^ Device function symbol\n -> (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ (optional) execution stream\n -> [FunParam]\n -> IO ()\nlaunchKernel !fn !grid !block !sm !mst !args = do\n setConfig grid block sm mst\n setParams args\n launch fn\n\n--------------------------------------------------------------------------------\n-- Internals\n--------------------------------------------------------------------------------\n\n-- CUDA 5.0 changed the type of a kernel function from char* to void*\n--\nwithFun :: Fun -> (Ptr a -> IO b) -> IO b\n#if CUDART_VERSION >= 5000\nwithFun fn action = action (castFunPtrToPtr fn)\n#else\nwithFun = withCString\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"23db8c979ece104662e75f72d8ff060fa7ef4ee8","subject":"Fix ref counting bug in sourceBufferCreateMarker (reported by bwwx in #haskell) The docs say that gtk_source_buffer_create_marker returns a new GtkSourceMarker, owned by the buffer. So we need to ref the object, so we should use makeGObject rather than constructNewGObject.","message":"Fix ref counting bug in sourceBufferCreateMarker\n(reported by bwwx in #haskell)\nThe docs say that gtk_source_buffer_create_marker returns a new\nGtkSourceMarker, owned by the buffer. So we need to ref the object, so we\nshould use makeGObject rather than constructNewGObject.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"sourceview\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"sourceview\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 15 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetCheckBrackets,\n sourceBufferGetCheckBrackets,\n sourceBufferSetBracketsMatchStyle,\n sourceBufferSetHighlight,\n sourceBufferGetHighlight,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetEscapeChar,\n sourceBufferGetEscapeChar,\n sourceBufferCanUndo,\n sourceBufferCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateMarker,\n sourceBufferMoveMarker,\n sourceBufferDeleteMarker,\n sourceBufferGetMarker,\n sourceBufferGetMarkersInRegion,\n sourceBufferGetFirstMarker,\n sourceBufferGetLastMarker,\n sourceBufferGetIterAtMarker,\n sourceBufferGetNextMarker,\n sourceBufferGetPrevMarker\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\t\t(fromGSList)\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.SourceView.SourceTagStyle\nimport Graphics.UI.Gtk.SourceView.SourceMarker\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'SourceTagTable'.\n--\nsourceBufferNew :: Maybe SourceTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkSourceTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetCheckBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetCheckBrackets sb newVal =\n {#call unsafe source_buffer_set_check_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetCheckBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetCheckBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_check_brackets#} sb\n\n-- | \n--\nsourceBufferSetBracketsMatchStyle :: SourceBuffer -> SourceTagStyle -> IO () \nsourceBufferSetBracketsMatchStyle sb ts =\n alloca $ \\tsPtr -> do\n poke tsPtr ts\n {#call unsafe source_buffer_set_bracket_match_style#} sb (castPtr tsPtr)\n\n-- | \n--\nsourceBufferSetHighlight :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlight sb newVal =\n {#call unsafe source_buffer_set_highlight#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlight :: SourceBuffer -> IO Bool \nsourceBufferGetHighlight sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetEscapeChar :: SourceBuffer -> Char -> IO ()\nsourceBufferSetEscapeChar sb char =\n {#call unsafe source_buffer_set_escape_char#} sb ((toEnum . fromEnum) char)\n \n-- | \n--\nsourceBufferGetEscapeChar :: SourceBuffer -> IO Char\nsourceBufferGetEscapeChar sb = liftM (toEnum . fromEnum) $\n {#call unsafe source_buffer_get_escape_char#} sb\n\n-- | \n--\nsourceBufferCanUndo :: SourceBuffer -> IO Bool\nsourceBufferCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferCanRedo :: SourceBuffer -> IO Bool\nsourceBufferCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateMarker :: SourceBuffer -- the buffer\n\t\t\t -> Maybe String -- the name of the marker\n\t\t\t -> String -- the type of the marker\n\t\t\t -> TextIter -> IO SourceMarker\nsourceBufferCreateMarker sb name markerType iter =\n makeNewGObject mkSourceMarker $\n maybeWith withCString name $ \\strPtr1 ->\n withCString markerType $ \\strPtr2 ->\n {#call source_buffer_create_marker#} sb strPtr1 strPtr2 iter\n\n-- | \n--\nsourceBufferMoveMarker :: SourceBuffer -> SourceMarker -> TextIter -> IO ()\nsourceBufferMoveMarker sb mark iter =\n {#call source_buffer_move_marker#} sb mark iter\n\n-- | \n--\nsourceBufferDeleteMarker :: SourceBuffer -> SourceMarker -> IO ()\nsourceBufferDeleteMarker sb mark =\n {#call source_buffer_delete_marker#} sb mark\n\n-- | \n--\nsourceBufferGetMarker :: SourceBuffer -> String -> IO (Maybe SourceMarker)\nsourceBufferGetMarker sb name =\n maybeNull (makeNewGObject mkSourceMarker) $\n withCString name $ \\strPtr1 ->\n {#call unsafe source_buffer_get_marker#} sb strPtr1\n\n-- | Returns an \/ordered\/ (by position) list of 'SourceMarker's inside the\n-- region delimited by the two 'TextIter's. The iterators may be in any\n-- order.\n--\nsourceBufferGetMarkersInRegion :: SourceBuffer -> TextIter -> TextIter -> IO [SourceMarker]\nsourceBufferGetMarkersInRegion sb begin end = do\n gList <- {#call unsafe source_buffer_get_markers_in_region#} sb begin end\n wList <- fromGSList gList\n mapM (makeNewGObject mkSourceMarker) (map return wList)\n\n-- | Returns the first (nearest to the top of the buffer) marker.\n--\nsourceBufferGetFirstMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetFirstMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_first_marker#} sb\n\n-- | Returns the last (nearest to the bottom of the buffer) marker.\n--\nsourceBufferGetLastMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetLastMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_last_marker#} sb\n\n-- | \n--\nsourceBufferGetIterAtMarker :: SourceBuffer -> SourceMarker -> IO TextIter\nsourceBufferGetIterAtMarker sb mark = do\n iter <- makeEmptyTextIter\n {#call unsafe source_buffer_get_iter_at_marker#} sb iter mark\n return iter\n\n-- | Returns the nearest marker to the right of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the first one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerNext'.\n--\nsourceBufferGetNextMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetNextMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_next_marker#} sb iter\n\n-- | Returns the nearest marker to the left of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the last one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerPrev'.\n--\nsourceBufferGetPrevMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetPrevMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_prev_marker#} sb iter\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 15 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetCheckBrackets,\n sourceBufferGetCheckBrackets,\n sourceBufferSetBracketsMatchStyle,\n sourceBufferSetHighlight,\n sourceBufferGetHighlight,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetEscapeChar,\n sourceBufferGetEscapeChar,\n sourceBufferCanUndo,\n sourceBufferCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateMarker,\n sourceBufferMoveMarker,\n sourceBufferDeleteMarker,\n sourceBufferGetMarker,\n sourceBufferGetMarkersInRegion,\n sourceBufferGetFirstMarker,\n sourceBufferGetLastMarker,\n sourceBufferGetIterAtMarker,\n sourceBufferGetNextMarker,\n sourceBufferGetPrevMarker\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\t\t(fromGSList)\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.SourceView.SourceTagStyle\nimport Graphics.UI.Gtk.SourceView.SourceMarker\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'SourceTagTable'.\n--\nsourceBufferNew :: Maybe SourceTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkSourceTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetCheckBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetCheckBrackets sb newVal =\n {#call unsafe source_buffer_set_check_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetCheckBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetCheckBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_check_brackets#} sb\n\n-- | \n--\nsourceBufferSetBracketsMatchStyle :: SourceBuffer -> SourceTagStyle -> IO () \nsourceBufferSetBracketsMatchStyle sb ts =\n alloca $ \\tsPtr -> do\n poke tsPtr ts\n {#call unsafe source_buffer_set_bracket_match_style#} sb (castPtr tsPtr)\n\n-- | \n--\nsourceBufferSetHighlight :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlight sb newVal =\n {#call unsafe source_buffer_set_highlight#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlight :: SourceBuffer -> IO Bool \nsourceBufferGetHighlight sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetEscapeChar :: SourceBuffer -> Char -> IO ()\nsourceBufferSetEscapeChar sb char =\n {#call unsafe source_buffer_set_escape_char#} sb ((toEnum . fromEnum) char)\n \n-- | \n--\nsourceBufferGetEscapeChar :: SourceBuffer -> IO Char\nsourceBufferGetEscapeChar sb = liftM (toEnum . fromEnum) $\n {#call unsafe source_buffer_get_escape_char#} sb\n\n-- | \n--\nsourceBufferCanUndo :: SourceBuffer -> IO Bool\nsourceBufferCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferCanRedo :: SourceBuffer -> IO Bool\nsourceBufferCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateMarker :: SourceBuffer -- the buffer\n\t\t\t -> Maybe String -- the name of the marker\n\t\t\t -> String -- the type of the marker\n\t\t\t -> TextIter -> IO SourceMarker\nsourceBufferCreateMarker sb name markerType iter =\n constructNewGObject mkSourceMarker $\n maybeWith withCString name $ \\strPtr1 ->\n withCString markerType $ \\strPtr2 ->\n {#call source_buffer_create_marker#} sb strPtr1 strPtr2 iter\n\n-- | \n--\nsourceBufferMoveMarker :: SourceBuffer -> SourceMarker -> TextIter -> IO ()\nsourceBufferMoveMarker sb mark iter =\n {#call source_buffer_move_marker#} sb mark iter\n\n-- | \n--\nsourceBufferDeleteMarker :: SourceBuffer -> SourceMarker -> IO ()\nsourceBufferDeleteMarker sb mark =\n {#call source_buffer_delete_marker#} sb mark\n\n-- | \n--\nsourceBufferGetMarker :: SourceBuffer -> String -> IO (Maybe SourceMarker)\nsourceBufferGetMarker sb name =\n maybeNull (makeNewGObject mkSourceMarker) $\n withCString name $ \\strPtr1 ->\n {#call unsafe source_buffer_get_marker#} sb strPtr1\n\n-- | Returns an \/ordered\/ (by position) list of 'SourceMarker's inside the\n-- region delimited by the two 'TextIter's. The iterators may be in any\n-- order.\n--\nsourceBufferGetMarkersInRegion :: SourceBuffer -> TextIter -> TextIter -> IO [SourceMarker]\nsourceBufferGetMarkersInRegion sb begin end = do\n gList <- {#call unsafe source_buffer_get_markers_in_region#} sb begin end\n wList <- fromGSList gList\n mapM (makeNewGObject mkSourceMarker) (map return wList)\n\n-- | Returns the first (nearest to the top of the buffer) marker.\n--\nsourceBufferGetFirstMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetFirstMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_first_marker#} sb\n\n-- | Returns the last (nearest to the bottom of the buffer) marker.\n--\nsourceBufferGetLastMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetLastMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_last_marker#} sb\n\n-- | \n--\nsourceBufferGetIterAtMarker :: SourceBuffer -> SourceMarker -> IO TextIter\nsourceBufferGetIterAtMarker sb mark = do\n iter <- makeEmptyTextIter\n {#call unsafe source_buffer_get_iter_at_marker#} sb iter mark\n return iter\n\n-- | Returns the nearest marker to the right of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the first one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerNext'.\n--\nsourceBufferGetNextMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetNextMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_next_marker#} sb iter\n\n-- | Returns the nearest marker to the left of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the last one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerPrev'.\n--\nsourceBufferGetPrevMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetPrevMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_prev_marker#} sb iter\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"282eb7239ffcd3899aded412e32ef70027e4a1d4","subject":"unsafeFromHandle and adoptHandle","message":"unsafeFromHandle and adoptHandle\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 , unsafeFromHandle\n , adoptHandle\n\n , bandDataType\n , bandProjection\n , bandColorInterpretaion\n , bandGeotransform\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasArbitraryOverviews\n , bandOverviewCount\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 , readDatasetRGBA\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\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, (>=>), (<=<))\nimport Control.Monad.Catch (MonadThrow, throwM)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Resource (unprotect)\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 (zipSources)\nimport Data.Maybe (fromMaybe, fromJust, catMaybes)\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, Word32)\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, withArray, 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 GDALColorInterp as ColorInterp { } deriving (Eq, Show) #}\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 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 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 d)\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s 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 d)\nopenReadWriteEx :: [OpenFlag] -> OptionList -> String -> DataType d -> GDAL s (RWDataset s 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\nunsafeFromHandle :: DatasetH -> Dataset s a t\nunsafeFromHandle h = Dataset (Nothing,h)\n\nadoptHandle :: Dataset s a t -> GDAL s (DatasetH, IO ())\nadoptHandle (Dataset (Nothing,h)) = pure (h, pure ())\nadoptHandle (Dataset (Just rk,h)) = do\n closeDs <- fromMaybe (pure ()) <$> liftIO (unprotect rk)\n pure (h, closeDs)\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s 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\nbandHasArbitraryOverviews :: Band s a t -> GDAL s Bool\nbandHasArbitraryOverviews =\n liftIO . fmap toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandOverviewCount :: Band s a t -> GDAL s Int\nbandOverviewCount =\n liftIO . fmap fromIntegral . {#call unsafe GetOverviewCount 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\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'\n -> Envelope Int\n -> Size\n -> St.Vector a'\n -> GDAL s ()\n write band' win size@(bx :+: _) vec = 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 band' <*> 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\n if sizeLen size \/= G.length vec\n then throwBindingException (InvalidRasterSize size)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\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\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 zipSources blocks\n (blocks =$= unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n blocks = allBlocks band =$= CL.filter inRange\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 =\n let blocks = allBlocks band\n in zipSources blocks (blocks =$= unsafeBlockConduit band)\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band =\n let blocks = allBlocks band\n in zipSources blocks (blocks =$= 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\nbandColorInterpretaion\n :: MonadIO m\n => Band s a t\n -> m ColorInterp\nbandColorInterpretaion\n = fmap toEnumC\n . liftIO \n . {#call unsafe GetRasterColorInterpretation as ^#}\n . unBand\n\nreadDatasetRGBA\n :: Dataset s Word8 t\n -> Envelope Int\n -> Size\n -> GDAL s (St.Vector Word32)\nreadDatasetRGBA ds (Envelope (x0:+:y0) (x1:+:y1)) (bufx:+:bufy) = do\n nBands <- datasetBandCount ds\n colorInterps <- mapM (bandColorInterpretaion <=< (`getBand` ds)) [1..nBands] \n let red = (+1) <$> GCI_RedBand `L.elemIndex` colorInterps\n green = (+1) <$> GCI_GreenBand `L.elemIndex` colorInterps\n blue = (+1) <$> GCI_BlueBand `L.elemIndex` colorInterps\n alpha = (+1) <$> GCI_AlphaBand `L.elemIndex` colorInterps\n bandMap = catMaybes [red, green, blue, alpha]\n liftIO $ do\n buf <- Stm.new (bufx*bufy)\n when (length bandMap < 4) (Stm.set buf 0xFF000000)\n withArray (map fromIntegral bandMap) $ \\pBandMap ->\n Stm.unsafeWith buf $ \\ bufPtr ->\n checkCPLError \"DatasetRasterIO\" $\n {#call DatasetRasterIO as ^#}\n (unDataset ds)\n (fromEnumC GA_ReadOnly)\n (fromIntegral x0)\n (fromIntegral y0)\n (fromIntegral (x1-x0))\n (fromIntegral (y1-y0))\n (castPtr bufPtr)\n (fromIntegral bufx)\n (fromIntegral bufy)\n (fromEnumC GByte)\n (fromIntegral (length bandMap))\n pBandMap\n 4\n (fromIntegral (4 * bufx))\n 1\n St.unsafeFreeze buf\n\n \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","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 , bandColorInterpretaion\n , bandGeotransform\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasArbitraryOverviews\n , bandOverviewCount\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 , readDatasetRGBA\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\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, (>=>), (<=<))\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 (zipSources)\nimport Data.Maybe (fromMaybe, fromJust, catMaybes)\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, Word32)\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, withArray, 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 GDALColorInterp as ColorInterp { } deriving (Eq, Show) #}\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 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 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 d)\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s 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 d)\nopenReadWriteEx :: [OpenFlag] -> OptionList -> String -> DataType d -> GDAL s (RWDataset s 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 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\nbandHasArbitraryOverviews :: Band s a t -> GDAL s Bool\nbandHasArbitraryOverviews =\n liftIO . fmap toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandOverviewCount :: Band s a t -> GDAL s Int\nbandOverviewCount =\n liftIO . fmap fromIntegral . {#call unsafe GetOverviewCount 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\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'\n -> Envelope Int\n -> Size\n -> St.Vector a'\n -> GDAL s ()\n write band' win size@(bx :+: _) vec = 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 band' <*> 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\n if sizeLen size \/= G.length vec\n then throwBindingException (InvalidRasterSize size)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\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\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 zipSources blocks\n (blocks =$= unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n blocks = allBlocks band =$= CL.filter inRange\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 =\n let blocks = allBlocks band\n in zipSources blocks (blocks =$= unsafeBlockConduit band)\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band =\n let blocks = allBlocks band\n in zipSources blocks (blocks =$= 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\nbandColorInterpretaion\n :: MonadIO m\n => Band s a t\n -> m ColorInterp\nbandColorInterpretaion\n = fmap toEnumC\n . liftIO \n . {#call unsafe GetRasterColorInterpretation as ^#}\n . unBand\n\nreadDatasetRGBA\n :: Dataset s Word8 t\n -> Envelope Int\n -> Size\n -> GDAL s (St.Vector Word32)\nreadDatasetRGBA ds (Envelope (x0:+:y0) (x1:+:y1)) (bufx:+:bufy) = do\n nBands <- datasetBandCount ds\n colorInterps <- mapM (bandColorInterpretaion <=< (`getBand` ds)) [1..nBands] \n let red = (+1) <$> GCI_RedBand `L.elemIndex` colorInterps\n green = (+1) <$> GCI_GreenBand `L.elemIndex` colorInterps\n blue = (+1) <$> GCI_BlueBand `L.elemIndex` colorInterps\n alpha = (+1) <$> GCI_AlphaBand `L.elemIndex` colorInterps\n bandMap = catMaybes [red, green, blue, alpha]\n liftIO $ do\n buf <- Stm.new (bufx*bufy)\n when (length bandMap < 4) (Stm.set buf 0xFF000000)\n withArray (map fromIntegral bandMap) $ \\pBandMap ->\n Stm.unsafeWith buf $ \\ bufPtr ->\n checkCPLError \"DatasetRasterIO\" $\n {#call DatasetRasterIO as ^#}\n (unDataset ds)\n (fromEnumC GA_ReadOnly)\n (fromIntegral x0)\n (fromIntegral y0)\n (fromIntegral (x1-x0))\n (fromIntegral (y1-y0))\n (castPtr bufPtr)\n (fromIntegral bufx)\n (fromIntegral bufy)\n (fromEnumC GByte)\n (fromIntegral (length bandMap))\n pBandMap\n 4\n (fromIntegral (4 * bufx))\n 1\n St.unsafeFreeze buf\n\n \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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9194e798a41d59675b172c41fb01f68967f61b3d","subject":"refs #8: add clCreateImage3D","message":"refs #8: add clCreateImage3D\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 -- * 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, getEnumCL, bitmaskFromFlags, \n 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} #}\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} #}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\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 CUint\ngetNumSupportedImageFormats ctx xs mtype = alloca $ \\(value_size :: Ptr CUint) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags mtype 0 nullPtr value_size)\n $ peek value_size\n--getProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n-- whenSuccess (raw_clGetProgramInfo prg infoid 0 nullPtr value_size)\n-- $ peek value_size\n \n \nclGetSupportedImageFormats = id\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,\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, getEnumCL, bitmaskFromFlags, \n 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\n--foreign 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} #}\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} #}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\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#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":"f74194fcd1dcdd9b845fc87282861c5c0c82b80c","subject":"Module desc fixed","message":"Module desc fixed\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@ 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, tagVal, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, isendPtr, ibsendPtr, issendPtr, irecv,\n 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\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*- #}\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{- 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 , mpiErrorCode :: CInt\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 code\n\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 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 ( \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, tagVal, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, isendPtr, ibsendPtr, issendPtr, irecv,\n 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\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*- #}\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{- 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 , mpiErrorCode :: CInt\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 code\n\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":"22d9eda647b8cd49565ac246d192ed5c3a95107d","subject":"Proper freeing of memory","message":"Proper freeing of memory\n","repos":"RyanGlScott\/bluetooth,bneijt\/bluetooth","old_file":"src\/Network\/Bluetooth\/Linux\/SDP.chs","new_file":"src\/Network\/Bluetooth\/Linux\/SDP.chs","new_contents":"{-# LANGUAGE NamedFieldPuns #-}\nmodule Network.Bluetooth.Linux.SDP where\n\nimport Control.Monad\n\nimport Data.Ix\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.UUID as U\nimport Data.UUID (UUID)\n\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Protocol\nimport Network.Bluetooth.Utils\nimport Network.Bluetooth.UUID\n\n#include \"wr_bluetooth.h\"\n#include \"wr_sdp.h\"\n#include \"wr_sdp_lib.h\"\n\nregisterSDPService :: UUID -> SDPInfo -> BluetoothProtocol -> BluetoothPort -> IO SDPSessionPtr\nregisterSDPService uuid info btProto port = do\n -- TODO: Check if service is already being advertised\n let uuidSize = {#sizeof uuid_t #}\n sdpUUID16Create uuid' = throwErrnoIfNull_ \"sdp_uuid16_create\" . c_sdp_uuid16_create uuid'\n sdpListAppend list = throwErrnoIfNull \"sdp_list_append\" . c_sdp_list_append list\n sdpListAppend_ list = void . sdpListAppend list\n setFoldM q s f = foldM f q $ S.toList s\n sdpUUID128Create cUuid hUuid = withUUIDArray hUuid $\n throwErrnoIfNull_ \"sdp_uuid128_create\" . c_sdp_uuid128_create cUuid\n \n allocaBytes uuidSize $ \\rootUuid ->\n allocaBytes uuidSize $ \\l2capUuid ->\n allocaBytes uuidSize $ \\rfcommUuid ->\n allocaBytes uuidSize $ \\svcUuid ->\n allocaBytes {#sizeof sdp_record_t #} $ \\record -> do\n -- Convert the UUID to a uuid_t\n sdpUUID128Create svcUuid uuid\n \n {#set sdp_record_t.handle #} record 0xffffffff\n \n -- Make the record publicly browsable\n sdpUUID16Create rootUuid PublicBrowseGroup\n rootList <- sdpListAppend nullPtr rootUuid\n throwErrnoIfNegative_ \"sdp_set_browse_groups\" $\n c_sdp_set_browse_groups record rootList\n \n -- Set L2CAP information (always happens)\n sdpUUID16Create l2capUuid L2CAPProtocol\n l2capList <- sdpListAppend nullPtr l2capUuid\n protoList <- sdpListAppend nullPtr l2capList\n \n portData <- case btProto of\n L2CAP -> do\n -- Register the L2CAP PSM\n psm <- with port $ c_sdp_data_alloc SDP_CUInt16\n sdpListAppend_ l2capList psm\n return $ Left psm\n RFCOMM -> do\n -- Register the RFCOMM channel\n sdpUUID16Create rfcommUuid RFCOMMProtocol\n channel <- with port $ c_sdp_data_alloc SDP_CUInt8\n rfcommList <- sdpListAppend nullPtr rfcommUuid\n sdpListAppend_ rfcommList channel\n sdpListAppend_ protoList rfcommList\n return $ Right (channel, rfcommList)\n \n -- Add additional UUID protocols\n (extraProtosList, protoList') <- setFoldM ([], protoList) (sdpExtraProtocols info)\n $ \\(extraProtosList, protoList') hUUIDProto -> do\n cUUIDProto <- mallocBytes uuidSize\n sdpUUID16Create cUUIDProto hUUIDProto\n newList <- sdpListAppend nullPtr cUUIDProto\n protoList'' <- sdpListAppend protoList' newList\n return (newList : extraProtosList, protoList'')\n \n accessProtoList <- sdpListAppend nullPtr protoList'\n throwErrnoIfNegative_ \"sdp_set_access_protos\" $\n c_sdp_set_access_protos record accessProtoList\n \n -- Add UUID service classes\n svcClassList <- if (sdpRegisterUUIDAsServiceClass info)\n then do\n svcClassUuid <- mallocBytes uuidSize\n sdpUUID128Create svcClassUuid uuid\n sdpListAppend nullPtr svcClassUuid\n else return nullPtr\n \n svcClassList' <- setFoldM svcClassList (sdpServiceClasses info)\n $ \\svcClassList' hUUIDSvcClass -> do\n cUUIDSvcClass <- mallocBytes uuidSize\n sdpUUID16Create cUUIDSvcClass hUUIDSvcClass\n sdpListAppend svcClassList' cUUIDSvcClass\n \n throwErrnoIfNegative_ \"sdp_set_service_classes\" $\n c_sdp_set_service_classes record svcClassList'\n \n -- Add UUID profiles\n profileList <- setFoldM nullPtr (sdpProfiles info)\n $ \\profileList profile -> do\n profileDesc <- mallocBytes {#sizeof sdp_profile_desc_t #}\n sdpUUID16Create (c_sdp_profile_desc_get_uuid profileDesc) profile\n {#set sdp_profile_desc_t.version #} profileDesc 0x0100 -- Magic number\n sdpListAppend profileList profileDesc\n \n throwErrnoIfNegative_ \"sdp_set_profile_descs\" $\n c_sdp_set_profile_descs record profileList\n \n -- Add service name, provider, and description\n case info of SDPInfo {\n sdpServiceName = name\n , sdpProviderName = prov\n , sdpDescription = desc\n } -> c_sdp_set_info_attr record name prov desc\n \n -- Set the general service ID\n c_sdp_set_service_id record svcUuid\n \n -- Connect to the local SDP server, register\n -- the service record, and disconnect\n session <- throwErrnoIfNull \"sdp_connect\" $\n c_sdp_connect anyAddr localAddr SDPRetryIfBusy\n throwErrnoIfMinus1_ \"sdp_record_register\" $\n c_sdp_record_register session record 0\n \n -- Cleanup\n case portData of\n Left psm -> do\n c_sdp_data_free psm\n c_sdp_list_free l2capList nullFunPtr\n Right (channel, rfcommList) -> do\n c_sdp_data_free channel\n c_sdp_list_free l2capList nullFunPtr\n c_sdp_list_free rfcommList nullFunPtr\n \n forM_ (reverse extraProtosList) $ flip c_sdp_list_free finalizerFree\n c_sdp_list_free rootList nullFunPtr\n c_sdp_list_free accessProtoList nullFunPtr\n c_sdp_list_free svcClassList' finalizerFree\n c_sdp_list_free profileList finalizerFree\n return session\n\ncloseSDPService :: SDPSessionPtr -> IO ()\ncloseSDPService = throwErrnoIfMinus1_ \"sdp_close\" . c_sdp_close\n\ndata SDPInfo = SDPInfo {\n sdpServiceName :: Maybe String\n , sdpProviderName :: Maybe String\n , sdpDescription :: Maybe String\n , sdpExtraProtocols :: Set UUIDProtocol\n , sdpServiceClasses :: Set UUIDServiceClass\n , sdpRegisterUUIDAsServiceClass :: Bool\n , sdpProfiles :: Set UUIDProfile\n} deriving (Read, Ord, Show, Eq)\n\ndefaultSDPInfo :: SDPInfo\ndefaultSDPInfo = SDPInfo {\n sdpServiceName = Nothing\n , sdpProviderName = Nothing\n , sdpDescription = Nothing\n , sdpExtraProtocols = S.empty\n , sdpServiceClasses = S.empty\n , sdpRegisterUUIDAsServiceClass = True\n , sdpProfiles = S.empty\n}\n\n-------------------------------------------------------------------------------\n\ntype CUInt32 = {#type uint32_t #}\ntype SDPFreeFunPtr = {#type sdp_free_func_t #}\n\nwithUUIDArray :: UUID -> (Ptr CUInt32 -> IO a) -> IO a\nwithUUIDArray uuid = let (w1,w2,w3,w4) = U.toWords uuid\n in withArray $ map (fromIntegral . byteSwap32) [w1,w2,w3,w4]\n\n{#enum define SDPDataRep {\n SDP_UINT8 as SDP_CUInt8\n , SDP_UINT16 as SDP_CUInt16\n } deriving (Ix, Show, Eq, Read, Ord, Bounded) #}\n\n{#enum define SDPConnectFlag {\n SDP_RETRY_IF_BUSY as SDPRetryIfBusy\n } deriving (Ix, Show, Eq, Read, Ord, Bounded) #}\n\ndata C_UUID\ndata C_SDPProfileDesc\ndata C_SDPRecord\ndata C_SDPList\ndata C_SDPData\ndata C_SDPSession\n\n{#pointer *uuid_t as UUIDPtr -> C_UUID #}\n{#pointer *sdp_profile_desc_t as SDPProfileDescPtr -> C_SDPProfileDesc #}\n{#pointer *sdp_record_t as SDPRecordPtr -> C_SDPRecord #}\n{#pointer *sdp_list_t as SDPListPtr -> C_SDPList #}\n{#pointer *sdp_data_t as SDPDataPtr -> C_SDPData #}\n{#pointer *sdp_session_t as SDPSessionPtr -> C_SDPSession #}\n\n{#fun unsafe sdp_uuid128_create as c_sdp_uuid128_create\n { `UUIDPtr'\n , castPtr `Ptr a'\n } -> `UUIDPtr' #}\n\n{#fun pure wr_sdp_profile_desc_get_uuid as c_sdp_profile_desc_get_uuid\n { `SDPProfileDescPtr'\n } -> `UUIDPtr' #}\n\n{#fun unsafe wr_sdp_set_service_id as c_sdp_set_service_id\n { `SDPRecordPtr'\n , `UUIDPtr'\n } -> `()' #}\n\n{#fun unsafe sdp_uuid2strn as c_sdp_uuid2strn\n { `UUIDPtr'\n , `String'&\n } -> `Int' #}\n\n{#fun unsafe sdp_uuid16_create as c_sdp_uuid16_create\n `Enum e' =>\n { `UUIDPtr'\n , cFromEnum `e'\n } -> `UUIDPtr' #}\n\n{#fun unsafe sdp_list_append as c_sdp_list_append\n { `SDPListPtr'\n , castPtr `Ptr a'\n } -> `SDPListPtr' #}\n\n{#fun unsafe wr_sdp_set_service_classes as c_sdp_set_service_classes\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe sdp_set_profile_descs as c_sdp_set_profile_descs\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe wr_sdp_set_browse_groups as c_sdp_set_browse_groups\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe sdp_data_alloc as c_sdp_data_alloc\n { `SDPDataRep'\n , castPtr `Ptr a'\n } -> `SDPDataPtr' #}\n\n{#fun unsafe sdp_set_access_protos as c_sdp_set_access_protos\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe sdp_set_info_attr as c_sdp_set_info_attr\n { `SDPRecordPtr'\n , maybeWithCString* `Maybe String'\n , maybeWithCString* `Maybe String'\n , maybeWithCString* `Maybe String'\n } -> `()' #}\n where\n maybeWithCString :: Maybe String -> (CString -> IO a) -> IO a\n maybeWithCString = maybeWith withCString\n\n{#fun unsafe wr_sdp_connect as c_sdp_connect\n `Enum e' =>\n { withCast* `BluetoothAddr'\n , withCast* `BluetoothAddr'\n , cFromEnum `e'\n } -> `SDPSessionPtr' #}\n\n{#fun unsafe sdp_record_register as c_sdp_record_register\n { `SDPSessionPtr'\n , `SDPRecordPtr'\n , `Int'\n } -> `Int' #}\n\n{#fun unsafe sdp_data_free as c_sdp_data_free { `SDPDataPtr' } -> `()' #}\n\n{#fun sdp_list_free as c_sdp_list_free\n { `SDPListPtr'\n , id `SDPFreeFunPtr'\n } -> `()' #}\n\n{#fun unsafe sdp_close as c_sdp_close { `SDPSessionPtr' } -> `Int' #}","old_contents":"{-# LANGUAGE NamedFieldPuns #-}\nmodule Network.Bluetooth.Linux.SDP where\n\nimport Control.Monad\n\nimport Data.Ix\nimport qualified Data.Set as S\nimport Data.Set (Set)\nimport qualified Data.UUID as U\nimport Data.UUID (UUID)\n\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Protocol\nimport Network.Bluetooth.Utils\nimport Network.Bluetooth.UUID\n\n#include \"wr_bluetooth.h\"\n#include \"wr_sdp.h\"\n#include \"wr_sdp_lib.h\"\n\nregisterSDPService :: UUID -> SDPInfo -> BluetoothProtocol -> BluetoothPort -> IO SDPSessionPtr\nregisterSDPService uuid info btProto port = do\n -- TODO: Check if service is already being advertised\n let uuidSize = {#sizeof uuid_t #}\n sdpUUID16Create uuid' = throwErrnoIfNull_ \"sdp_uuid16_create\" . c_sdp_uuid16_create uuid'\n sdpListAppend list = throwErrnoIfNull \"sdp_list_append\" . c_sdp_list_append list\n sdpListAppend_ list = void . sdpListAppend list\n setFoldM q s f = foldM f q $ S.toList s\n sdpUUID128Create cUuid hUuid = withUUIDArray hUuid $\n throwErrnoIfNull_ \"sdp_uuid128_create\" . c_sdp_uuid128_create cUuid\n \n allocaBytes uuidSize $ \\rootUuid ->\n allocaBytes uuidSize $ \\l2capUuid ->\n allocaBytes uuidSize $ \\rfcommUuid ->\n allocaBytes uuidSize $ \\svcUuid ->\n allocaBytes uuidSize $ \\svcClassUuid ->\n allocaBytes {#sizeof sdp_record_t #} $ \\record -> do\n -- Convert the UUID to a uuid_t\n sdpUUID128Create svcUuid uuid\n \n {#set sdp_record_t.handle #} record 0xffffffff\n \n -- Make the record publicly browsable\n sdpUUID16Create rootUuid PublicBrowseGroup\n rootList <- sdpListAppend nullPtr rootUuid\n throwErrnoIfNegative_ \"sdp_set_browse_groups\" $\n c_sdp_set_browse_groups record rootList\n \n -- Set L2CAP information (always happens)\n sdpUUID16Create l2capUuid L2CAPProtocol\n l2capList <- sdpListAppend nullPtr l2capUuid\n protoList <- sdpListAppend nullPtr l2capList\n \n portData <- case btProto of\n L2CAP -> do\n -- Register the L2CAP PSM\n psm <- with port $ c_sdp_data_alloc SDPCUInt16\n sdpListAppend_ l2capList psm\n return $ Left psm\n RFCOMM -> do\n -- Register the RFCOMM channel\n sdpUUID16Create rfcommUuid RFCOMMProtocol\n channel <- with port $ c_sdp_data_alloc SDPCUInt8\n rfcommList <- sdpListAppend nullPtr rfcommUuid\n sdpListAppend_ rfcommList channel\n sdpListAppend_ protoList rfcommList\n return $ Right (channel, rfcommList)\n \n -- Add additional UUID protocols\n (extraProtosList, protoList') <- setFoldM ([], protoList) (sdpExtraProtocols info)\n $ \\(extraProtosList, protoList') hUUIDProto -> do\n cUUIDProto <- mallocBytes uuidSize\n sdpUUID16Create cUUIDProto hUUIDProto\n newList <- sdpListAppend nullPtr cUUIDProto\n protoList'' <- sdpListAppend protoList' newList\n return (newList : extraProtosList, protoList'')\n \n accessProtoList <- sdpListAppend nullPtr protoList'\n throwErrnoIfNegative_ \"sdp_set_access_protos\" $\n c_sdp_set_access_protos record accessProtoList\n \n -- Add UUID service classes\n svcClassList <- if (sdpRegisterUUIDAsServiceClass info)\n then do\n sdpUUID128Create svcClassUuid uuid\n sdpListAppend nullPtr svcClassUuid\n else return nullPtr\n \n svcClassList' <- setFoldM svcClassList (sdpServiceClasses info)\n $ \\svcClassList' hUUIDSvcClass -> do\n cUUIDSvcClass <- mallocBytes uuidSize\n sdpUUID16Create cUUIDSvcClass hUUIDSvcClass\n sdpListAppend svcClassList' cUUIDSvcClass\n \n throwErrnoIfNegative_ \"sdp_set_service_classes\" $\n c_sdp_set_service_classes record svcClassList'\n \n -- Add UUID profiles\n profileList <- setFoldM nullPtr (sdpProfiles info)\n $ \\profileList profile -> do\n profileDesc <- mallocBytes {#sizeof sdp_profile_desc_t #}\n sdpUUID16Create (c_sdp_profile_desc_get_uuid profileDesc) profile\n {#set sdp_profile_desc_t.version #} profileDesc 0x0100 -- Magic number\n sdpListAppend profileList profileDesc\n \n throwErrnoIfNegative_ \"sdp_set_profile_descs\" $\n c_sdp_set_profile_descs record profileList\n \n -- Add service name, provider, and description\n case info of SDPInfo {\n sdpServiceName = name\n , sdpProviderName = prov\n , sdpDescription = desc\n } -> c_sdp_set_info_attr record name prov desc\n \n -- Set the general service ID\n c_sdp_set_service_id record svcUuid\n \n -- Connect to the local SDP server, register\n -- the service record, and disconnect\n session <- throwErrnoIfNull \"sdp_connect\" $\n c_sdp_connect anyAddr localAddr SDPRetryIfBusy\n throwErrnoIfMinus1_ \"sdp_record_register\" $\n c_sdp_record_register session record 0\n \n -- Cleanup\n case portData of\n Left psm -> c_sdp_data_free psm\n Right (channel, rfcommList) -> do\n c_sdp_data_free channel\n c_sdp_list_free rfcommList nullFunPtr\n \n withSDPFreeFunPtr free $ \\freeFunPtr -> do\n c_sdp_list_free l2capList nullFunPtr\n forM_ extraProtosList $ flip c_sdp_list_free freeFunPtr\n c_sdp_list_free rootList nullFunPtr\n c_sdp_list_free accessProtoList nullFunPtr\n c_sdp_list_free svcClassList' nullFunPtr\n c_sdp_list_free profileList nullFunPtr\n return session\n\ncloseSDPService :: SDPSessionPtr -> IO ()\ncloseSDPService = throwErrnoIfMinus1_ \"sdp_close\" . c_sdp_close\n\ndata SDPInfo = SDPInfo {\n sdpServiceName :: Maybe String\n , sdpProviderName :: Maybe String\n , sdpDescription :: Maybe String\n , sdpExtraProtocols :: Set UUIDProtocol\n , sdpServiceClasses :: Set UUIDServiceClass\n , sdpRegisterUUIDAsServiceClass :: Bool\n , sdpProfiles :: Set UUIDProfile\n} deriving (Read, Ord, Show, Eq)\n\ndefaultSDPInfo :: SDPInfo\ndefaultSDPInfo = SDPInfo {\n sdpServiceName = Nothing\n , sdpProviderName = Nothing\n , sdpDescription = Nothing\n , sdpExtraProtocols = S.empty\n , sdpServiceClasses = S.empty\n , sdpRegisterUUIDAsServiceClass = True\n , sdpProfiles = S.empty\n}\n\n-------------------------------------------------------------------------------\n\ntype CUInt32 = {#type uint32_t #}\ntype SDPFreeFun = Ptr () -> IO ()\ntype SDPFreeFunPtr = {#type sdp_free_func_t #}\n\nwithUUIDArray :: UUID -> (Ptr CUInt32 -> IO a) -> IO a\nwithUUIDArray uuid = let (w1,w2,w3,w4) = U.toWords uuid\n in withArray $ map (fromIntegral . byteSwap32) [w1,w2,w3,w4]\n\n{#enum define SDPDataRep {\n SDP_UINT8 as SDPCUInt8\n , SDP_UINT16 as SDPCUInt16\n } deriving (Ix, Show, Eq, Read, Ord, Bounded) #}\n\n{#enum define SDPConnectFlag {\n SDP_RETRY_IF_BUSY as SDPRetryIfBusy\n } deriving (Ix, Show, Eq, Read, Ord, Bounded) #}\n\ndata C_UUID\ndata C_SDPProfileDesc\ndata C_SDPRecord\ndata C_SDPList\ndata C_SDPData\ndata C_SDPSession\n\n{#pointer *uuid_t as UUIDPtr -> C_UUID #}\n{#pointer *sdp_profile_desc_t as SDPProfileDescPtr -> C_SDPProfileDesc #}\n{#pointer *sdp_record_t as SDPRecordPtr -> C_SDPRecord #}\n{#pointer *sdp_list_t as SDPListPtr -> C_SDPList #}\n{#pointer *sdp_data_t as SDPDataPtr -> C_SDPData #}\n{#pointer *sdp_session_t as SDPSessionPtr -> C_SDPSession #}\n\nforeign import ccall \"wrapper\"\n wrapSDPFreeFun :: SDPFreeFun -> IO SDPFreeFunPtr\n\nwithSDPFreeFunPtr :: SDPFreeFun -> (SDPFreeFunPtr -> IO a) -> IO a\nwithSDPFreeFunPtr sff f = do\n sffp <- wrapSDPFreeFun sff\n res <- f sffp\n freeHaskellFunPtr sffp\n return res\n\n{#fun unsafe sdp_uuid128_create as c_sdp_uuid128_create\n { `UUIDPtr'\n , castPtr `Ptr a'\n } -> `UUIDPtr' #}\n\n{#fun pure wr_sdp_profile_desc_get_uuid as c_sdp_profile_desc_get_uuid\n { `SDPProfileDescPtr'\n } -> `UUIDPtr' #}\n\n{#fun unsafe wr_sdp_set_service_id as c_sdp_set_service_id\n { `SDPRecordPtr'\n , `UUIDPtr'\n } -> `()' #}\n\n{#fun unsafe sdp_uuid2strn as c_sdp_uuid2strn\n { `UUIDPtr'\n , `String'&\n } -> `Int' #}\n\n{#fun unsafe sdp_uuid16_create as c_sdp_uuid16_create\n `Enum e' =>\n { `UUIDPtr'\n , cFromEnum `e'\n } -> `UUIDPtr' #}\n\n{#fun unsafe sdp_list_append as c_sdp_list_append\n { `SDPListPtr'\n , castPtr `Ptr a'\n } -> `SDPListPtr' #}\n\n{#fun unsafe wr_sdp_set_service_classes as c_sdp_set_service_classes\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe sdp_set_profile_descs as c_sdp_set_profile_descs\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe wr_sdp_set_browse_groups as c_sdp_set_browse_groups\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe sdp_data_alloc as c_sdp_data_alloc\n { `SDPDataRep'\n , castPtr `Ptr a'\n } -> `SDPDataPtr' #}\n\n{#fun unsafe sdp_set_access_protos as c_sdp_set_access_protos\n { `SDPRecordPtr'\n , `SDPListPtr'\n } -> `Int' #}\n\n{#fun unsafe sdp_set_info_attr as c_sdp_set_info_attr\n { `SDPRecordPtr'\n , maybeWithCString* `Maybe String'\n , maybeWithCString* `Maybe String'\n , maybeWithCString* `Maybe String'\n } -> `()' #}\n where\n maybeWithCString :: Maybe String -> (CString -> IO a) -> IO a\n maybeWithCString = maybeWith withCString\n\n{#fun unsafe wr_sdp_connect as c_sdp_connect\n `Enum e' =>\n { withCast* `BluetoothAddr'\n , withCast* `BluetoothAddr'\n , cFromEnum `e'\n } -> `SDPSessionPtr' #}\n\n{#fun unsafe sdp_record_register as c_sdp_record_register\n { `SDPSessionPtr'\n , `SDPRecordPtr'\n , `Int'\n } -> `Int' #}\n\n{#fun unsafe sdp_data_free as c_sdp_data_free { `SDPDataPtr' } -> `()' #}\n\n{#fun unsafe sdp_list_free as c_sdp_list_free\n { `SDPListPtr'\n , id `SDPFreeFunPtr'\n } -> `()' #}\n\n{#fun unsafe sdp_close as c_sdp_close { `SDPSessionPtr' } -> `Int' #}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"34ff0bd77a10d03a9456035ae29e6140951192fa","subject":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM","message":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"bcdcb333a3a03050c08fbfd748bc1bed14c8cfdb","subject":"Added webResourceGetData","message":"Added webResourceGetData\n\nThis requires glib with GString patch applied.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetData,\n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Returns the data of the WebResource.\nwebResourceGetData :: WebResourceClass self => self -> IO (Maybe String)\nwebResourceGetData wr =\n {#call web_resource_get_data#} (toWebResource wr) >>= readGString\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"202d202edb5445894e9401a335eb9c6f45f7b564","subject":"gstreamer: add StaticPadTemplate to M.S.G.Core.Types","message":"gstreamer: add StaticPadTemplate to M.S.G.Core.Types\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate(..),\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet =\n {# call static_pad_template_get #} >=> takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"03a66bfa12c0c4824939cc23c1fa1ffdcd984da9","subject":"[project @ 2002-06-20 14:13:05 by as49] Turn the xoptions and yoptions parameters into lists.","message":"[project @ 2002-06-20 14:13:05 by as49]\nTurn the xoptions and yoptions parameters into lists.\n","repos":"vincenthz\/webkit","old_file":"gtk\/layout\/Table.chs","new_file":"gtk\/layout\/Table.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Table@\n--\n-- Author : Axel Simon\n-- \n-- Created: 15 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/06\/20 14:13:05 $\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-- * The table widget is a container in which widgets can be aligned in cells.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Table(\n Table,\n TableClass,\n castToTable,\n tableNew,\n tableResize,\n AttachOptions(..),\n tableAttach,\n tableAttachDefaults,\n tableSetRowSpacing,\n tableSetColSpacing,\n tableSetRowSpacings,\n tableSetColSpacings,\n tableSetHomogeneous\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(AttachOptions(..), fromFlags)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor tableNew@ Create a new table with the specified dimensions.\n-- Set @ref arg homogeneous@ to True if all cells should be of the same size.\n--\ntableNew :: Int -> Int -> Bool -> IO Table\ntableNew rows columns homogeneous = makeNewObject mkTable $ liftM castPtr $\n {#call unsafe table_new#} (fromIntegral rows) (fromIntegral columns)\n (fromBool homogeneous)\n\n-- @method tableResize@ Change the dimensions of an already existing table.\n--\ntableResize :: TableClass tb => tb -> Int -> Int -> IO ()\ntableResize tb rows columns = {#call table_resize#} (toTable tb)\n (fromIntegral rows) (fromIntegral columns)\n\n-- @method tableAttach@ Put a new widget in the table container. The widget\n-- should span the cells (leftAttach,topAttach) to (rightAttach,bottomAttach).\n-- Further formatting options have to be specified.\n--\ntableAttach :: (TableClass tb, WidgetClass w) => tb -> w -> Int -> Int ->\n Int -> Int -> [AttachOptions] -> [AttachOptions] -> Int ->\n Int -> IO ()\ntableAttach tb child leftAttach rightAttach topAttach bottomAttach xoptions\n yoptions xpadding ypadding = {#call table_attach#} (toTable tb)\n (toWidget child) (fromIntegral leftAttach) (fromIntegral rightAttach) \n (fromIntegral topAttach) (fromIntegral bottomAttach) \n ((fromIntegral.fromFlags) xoptions) ((fromIntegral.fromFlags) yoptions) \n (fromIntegral xpadding) (fromIntegral ypadding)\n\n-- @method tableAttachDefaults@ Put a new widget in the table container. As\n-- opposed to @ref method tableAttach@ this function assumes default values\n-- for the packing options.\n--\ntableAttachDefaults :: (TableClass tb, WidgetClass w) => tb -> w -> Int ->\n Int -> Int -> Int -> IO ()\ntableAttachDefaults tb child leftAttach rightAttach topAttach bottomAttach =\n {#call table_attach_defaults#} (toTable tb) (toWidget child) \n (fromIntegral leftAttach) (fromIntegral rightAttach) \n (fromIntegral topAttach) (fromIntegral bottomAttach)\n\n-- @method tableSetRowSpacing@ Set the amount of space (in pixels) between the\n-- specified @ref arg row@ and its neighbours.\n--\ntableSetRowSpacing :: TableClass tb => tb -> Int -> Int -> IO ()\ntableSetRowSpacing tb row space = {#call table_set_row_spacing#}\n (toTable tb) (fromIntegral row) (fromIntegral space)\n\n-- @method tableSetColSpacing@ Set the amount of space (in pixels) between the\n-- specified column @ref arg col@ and its neighbours.\n--\ntableSetColSpacing :: TableClass tb => tb -> Int -> Int -> IO ()\ntableSetColSpacing tb col space = {#call table_set_col_spacing#}\n (toTable tb) (fromIntegral col) (fromIntegral space)\n\n-- @method tableSetRowSpacings@ Set the amount of space between any two rows.\n--\ntableSetRowSpacings :: TableClass tb => tb -> Int -> IO ()\ntableSetRowSpacings tb space = {#call table_set_row_spacings#}\n (toTable tb) (fromIntegral space)\n\n-- @method tableSetColSpacings@ Set the amount of space between any two\n-- columns.\n--\ntableSetColSpacings :: TableClass tb => tb -> Int -> IO ()\ntableSetColSpacings tb space = {#call table_set_col_spacings#}\n (toTable tb) (fromIntegral space)\n\n-- @method tableSetHomogeneous@ Make all cells the same size.\n--\ntableSetHomogeneous :: TableClass tb => tb -> Bool -> IO ()\ntableSetHomogeneous tb hom = \n {#call table_set_homogeneous#} (toTable tb) (fromBool hom)\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Table@\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-- * The table widget is a container in which widgets can be aligned in cells.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Table(\n Table,\n TableClass,\n castToTable,\n tableNew,\n tableResize,\n AttachOptions(..),\n tableAttach,\n tableAttachDefaults,\n tableSetRowSpacing,\n tableSetColSpacing,\n tableSetRowSpacings,\n tableSetColSpacings,\n tableSetHomogeneous\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(AttachOptions(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor tableNew@ Create a new table with the specified dimensions.\n-- Set @ref arg homogeneous@ to True if all cells should be of the same size.\n--\ntableNew :: Int -> Int -> Bool -> IO Table\ntableNew rows columns homogeneous = makeNewObject mkTable $ liftM castPtr $\n {#call unsafe table_new#} (fromIntegral rows) (fromIntegral columns)\n (fromBool homogeneous)\n\n-- @method tableResize@ Change the dimensions of an already existing table.\n--\ntableResize :: TableClass tb => tb -> Int -> Int -> IO ()\ntableResize tb rows columns = {#call table_resize#} (toTable tb)\n (fromIntegral rows) (fromIntegral columns)\n\n-- @method tableAttach@ Put a new widget in the table container. The widget\n-- should span the cells (leftAttach,topAttach) to (rightAttach,bottomAttach).\n-- Further formatting options have to be specified.\n--\ntableAttach :: (TableClass tb, WidgetClass w) => tb -> w -> Int -> Int ->\n Int -> Int -> AttachOptions -> AttachOptions -> Int -> Int ->\n IO ()\ntableAttach tb child leftAttach rightAttach topAttach bottomAttach xoptions\n yoptions xpadding ypadding = {#call table_attach#} (toTable tb)\n (toWidget child) (fromIntegral leftAttach) (fromIntegral rightAttach) \n (fromIntegral topAttach) (fromIntegral bottomAttach) \n ((fromIntegral.fromEnum) xoptions) ((fromIntegral.fromEnum) yoptions) \n (fromIntegral xpadding) (fromIntegral ypadding)\n\n-- @method tableAttachDefaults@ Put a new widget in the table container. As\n-- opposed to @ref method tableAttach@ this function assumes default values\n-- for the packing options.\n--\ntableAttachDefaults :: (TableClass tb, WidgetClass w) => tb -> w -> Int ->\n Int -> Int -> Int -> IO ()\ntableAttachDefaults tb child leftAttach rightAttach topAttach bottomAttach =\n {#call table_attach_defaults#} (toTable tb) (toWidget child) \n (fromIntegral leftAttach) (fromIntegral rightAttach) \n (fromIntegral topAttach) (fromIntegral bottomAttach)\n\n-- @method tableSetRowSpacing@ Set the amount of space (in pixels) between the\n-- specified @ref arg row@ and its neighbours.\n--\ntableSetRowSpacing :: TableClass tb => tb -> Int -> Int -> IO ()\ntableSetRowSpacing tb row space = {#call table_set_row_spacing#}\n (toTable tb) (fromIntegral row) (fromIntegral space)\n\n-- @method tableSetColSpacing@ Set the amount of space (in pixels) between the\n-- specified column @ref arg col@ and its neighbours.\n--\ntableSetColSpacing :: TableClass tb => tb -> Int -> Int -> IO ()\ntableSetColSpacing tb col space = {#call table_set_col_spacing#}\n (toTable tb) (fromIntegral col) (fromIntegral space)\n\n-- @method tableSetRowSpacings@ Set the amount of space between any two rows.\n--\ntableSetRowSpacings :: TableClass tb => tb -> Int -> IO ()\ntableSetRowSpacings tb space = {#call table_set_row_spacings#}\n (toTable tb) (fromIntegral space)\n\n-- @method tableSetColSpacings@ Set the amount of space between any two\n-- columns.\n--\ntableSetColSpacings :: TableClass tb => tb -> Int -> IO ()\ntableSetColSpacings tb space = {#call table_set_col_spacings#}\n (toTable tb) (fromIntegral space)\n\n-- @method tableSetHomogeneous@ Make all cells the same size.\n--\ntableSetHomogeneous :: TableClass tb => tb -> Bool -> IO ()\ntableSetHomogeneous tb hom = \n {#call table_set_homogeneous#} (toTable tb) (fromBool hom)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9616ce32cbe1bead8c1e4532d2f9205c068e5f2a","subject":"add enqueue kernels","message":"add enqueue kernels\n","repos":"IFCA\/opencl,IFCA\/opencl,Delan90\/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,\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 :: CLCommandQueue -> CLMem -> Bool -> CSize -> CSize \n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueReadBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueReadBuffer cq mem (fromBool check) off 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 :: CLCommandQueue -> CLMem -> Bool -> CSize -> CSize \n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) off size dat)\n\n-- -----------------------------------------------------------------------------\nclEnqueueNDRangeKernel :: CLCommandQueue -> CLKernel -> [CSize] -> [CSize] -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueNDRangeKernel cq krn gws lws events = withArray gws $ \\pgws -> withArray 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","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 -- * 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(..),\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 \"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-- -----------------------------------------------------------------------------\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 :: CLCommandQueue -> CLMem -> Bool -> CSize -> CSize \n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueReadBuffer cq mem check off size dat [] = alloca $ \\event -> do\n errcode <- raw_clEnqueueReadBuffer cq mem (fromBool check) off size dat 0 nullPtr event\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap Right $ peek event\n else return . Left . toEnum . fromIntegral $ errcode\nclEnqueueReadBuffer cq mem check off size dat events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> do\n errcode <- raw_clEnqueueReadBuffer cq mem (fromBool check) off size dat 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{-| 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 :: CLCommandQueue -> CLMem -> Bool -> CSize -> CSize \n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueWriteBuffer cq mem check off size dat [] = alloca $ \\event -> do\n errcode <- raw_clEnqueueWriteBuffer cq mem (fromBool check) off size dat 0 nullPtr event\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap Right $ peek event\n else return . Left . toEnum . fromIntegral $ errcode\nclEnqueueWriteBuffer cq mem check off size dat events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> do\n errcode <- raw_clEnqueueWriteBuffer cq mem (fromBool check) off size dat 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-- | 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":"f918c531259edf8a9586f94685dd206d57a12ce4","subject":"`createVideoWriter` takes `codec:String` of length four and passes it to C `wrapCreateVideoWriter` (fix: previously was hardcoded to send a malformed `int fourcc` value)","message":"`createVideoWriter` takes `codec:String` of length four and passes it to C `wrapCreateVideoWriter` (fix: previously was hardcoded to send a malformed `int fourcc` value)\n","repos":"aleator\/CV,aleator\/CV","old_file":"CV\/Video.chs","new_file":"CV\/Video.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, CPP#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Video where\n{#import CV.Image#}\n\nimport Data.Char (ord)\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\nimport Utils.Stream\n\n-- NOTE: For some reason, this module fails to work with ghci for me\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\ntype VideoStream c d = Stream IO (Image c d)\n\nstreamFromVideo cap = dropS 1 $ streamFromVideo' (undefined) cap \nstreamFromVideo' p cap = Value $ do\n x <- getFrame cap\n case x of\n Just f -> return (p,(streamFromVideo' f cap))\n Nothing -> return (p,Terminated)\n \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 if ptr==nullPtr \n then \n return Nothing\n else do\n fptr <- newForeignPtr releaseCapture ptr\n return . Just . Capture $ fptr\n\ndropFrame cap = withCapture cap $ \\ccap -> {#call cvGrabFrame#} ccap >> return ()\n\ngetFrame :: Capture -> IO (Maybe (Image RGB D32))\ngetFrame cap = withCapture cap $\u00a0\\ccap -> do\n p_frame <- {#call cvQueryFrame#} ccap \n if p_frame==nullPtr then return Nothing\n else creatingImage (ensure32F p_frame) >>= return . Just\n -- NOTE: This works because Image module has generated wrappers for ensure32F\n\n#c\nenum CapProp {\n CAP_PROP_POS_MSEC = CV_CAP_PROP_POS_MSEC \n , CAP_PROP_POS_FRAMES = CV_CAP_PROP_POS_FRAMES \n , CAP_PROP_POS_AVI_RATIO = CV_CAP_PROP_POS_AVI_RATIO\n , CAP_PROP_FRAME_WIDTH = CV_CAP_PROP_FRAME_WIDTH \n , CAP_PROP_FRAME_HEIGHT = CV_CAP_PROP_FRAME_HEIGHT \n , CAP_PROP_FPS = CV_CAP_PROP_FPS \n , CAP_PROP_FOURCC = CV_CAP_PROP_FOURCC \n , CAP_PROP_FRAME_COUNT = CV_CAP_PROP_FRAME_COUNT \n , CAP_PROP_FORMAT = CV_CAP_PROP_FORMAT \n , CAP_PROP_MODE = CV_CAP_PROP_MODE \n , CAP_PROP_BRIGHTNESS = CV_CAP_PROP_BRIGHTNESS \n , CAP_PROP_CONTRAST = CV_CAP_PROP_CONTRAST \n , CAP_PROP_SATURATION = CV_CAP_PROP_SATURATION \n , CAP_PROP_HUE = CV_CAP_PROP_HUE \n , CAP_PROP_GAIN = CV_CAP_PROP_GAIN \n , CAP_PROP_EXPOSURE = CV_CAP_PROP_EXPOSURE \n , CAP_PROP_CONVERT_RGB = CV_CAP_PROP_CONVERT_RGB \n , CAP_PROP_RECTIFICATION = CV_CAP_PROP_RECTIFICATION \n , CAP_PROP_MONOCROME = CV_CAP_PROP_MONOCROME \n};\n#endc\n\n{#enum CapProp {}#}\n\nfromProp = fromIntegral . fromEnum\n\ngetCapProp cap prop = withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp prop) >>= return . realToFrac\n\ngetFrameRate cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp CAP_PROP_FPS) >>= return . realToFrac\n\ngetFrameSize cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap -> do\n w <- {#call cvGetCaptureProperty#} ccap (fromProp CAP_PROP_FRAME_WIDTH) \n >>= return . round\n h <- {#call cvGetCaptureProperty#} ccap (fromProp CAP_PROP_FRAME_HEIGHT)\n >>= return . round\n return (w,h)\n\n\nsetCapProp cap prop val = withCapture cap $\u00a0\\ccap ->\n {#call cvSetCaptureProperty#} \n ccap (fromProp prop) (realToFrac val)\n\nnumberOfFrames cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp CAP_PROP_FRAME_COUNT)\n >>= return . floor\n\nframeNumber cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp CAP_PROP_POS_FRAMES) >>= return . floor\n\n-- Video Writing\n\ncreateVideoWriter filename codec framerate frameSize = \n withCString filename $ \\cfilename -> do\n ptr <- {#call wrapCreateVideoWriter#} cfilename\n cc1 cc2 cc3 cc4\n framerate w h 0\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 (fromIntegral -> w, fromIntegral -> h) = frameSize\n [cc1, cc2, cc3, cc4]\n | 4 == length codec = fmap (fromIntegral . ord) codec\n | otherwise = error \"Video writer codec must be a four-character string, eg. \\\"MPEG\\\"\"\n\nwriteFrame :: VideoWriter -> Image RGB D32 -> IO ()\nwriteFrame writer img = withVideoWriter writer $\u00a0\\cwriter ->\n withImage img $ \\cimg -> \n {#call cvWriteFrame #} cwriter cimg >> return ()\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, CPP#-}\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\nimport Utils.Stream\n\n-- NOTE: For some reason, this module fails to work with ghci for me\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\ntype VideoStream c d = Stream IO (Image c d)\n\nstreamFromVideo cap = dropS 1 $ streamFromVideo' (undefined) cap \nstreamFromVideo' p cap = Value $ do\n x <- getFrame cap\n case x of\n Just f -> return (p,(streamFromVideo' f cap))\n Nothing -> return (p,Terminated)\n \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 if ptr==nullPtr \n then \n return Nothing\n else do\n fptr <- newForeignPtr releaseCapture ptr\n return . Just . Capture $ fptr\n\ndropFrame cap = withCapture cap $ \\ccap -> {#call cvGrabFrame#} ccap >> return ()\n\ngetFrame :: Capture -> IO (Maybe (Image RGB D32))\ngetFrame cap = withCapture cap $\u00a0\\ccap -> do\n p_frame <- {#call cvQueryFrame#} ccap \n if p_frame==nullPtr then return Nothing\n else creatingImage (ensure32F p_frame) >>= return . Just\n -- NOTE: This works because Image module has generated wrappers for ensure32F\n\n#c\nenum CapProp {\n CAP_PROP_POS_MSEC = CV_CAP_PROP_POS_MSEC \n , CAP_PROP_POS_FRAMES = CV_CAP_PROP_POS_FRAMES \n , CAP_PROP_POS_AVI_RATIO = CV_CAP_PROP_POS_AVI_RATIO\n , CAP_PROP_FRAME_WIDTH = CV_CAP_PROP_FRAME_WIDTH \n , CAP_PROP_FRAME_HEIGHT = CV_CAP_PROP_FRAME_HEIGHT \n , CAP_PROP_FPS = CV_CAP_PROP_FPS \n , CAP_PROP_FOURCC = CV_CAP_PROP_FOURCC \n , CAP_PROP_FRAME_COUNT = CV_CAP_PROP_FRAME_COUNT \n , CAP_PROP_FORMAT = CV_CAP_PROP_FORMAT \n , CAP_PROP_MODE = CV_CAP_PROP_MODE \n , CAP_PROP_BRIGHTNESS = CV_CAP_PROP_BRIGHTNESS \n , CAP_PROP_CONTRAST = CV_CAP_PROP_CONTRAST \n , CAP_PROP_SATURATION = CV_CAP_PROP_SATURATION \n , CAP_PROP_HUE = CV_CAP_PROP_HUE \n , CAP_PROP_GAIN = CV_CAP_PROP_GAIN \n , CAP_PROP_EXPOSURE = CV_CAP_PROP_EXPOSURE \n , CAP_PROP_CONVERT_RGB = CV_CAP_PROP_CONVERT_RGB \n , CAP_PROP_RECTIFICATION = CV_CAP_PROP_RECTIFICATION \n , CAP_PROP_MONOCROME = CV_CAP_PROP_MONOCROME \n};\n#endc\n\n{#enum CapProp {}#}\n\nfromProp = fromIntegral . fromEnum\n\ngetCapProp cap prop = withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp prop) >>= return . realToFrac\n\ngetFrameRate cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp CAP_PROP_FPS) >>= return . realToFrac\n\ngetFrameSize cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap -> do\n w <- {#call cvGetCaptureProperty#} ccap (fromProp CAP_PROP_FRAME_WIDTH) \n >>= return . round\n h <- {#call cvGetCaptureProperty#} ccap (fromProp CAP_PROP_FRAME_HEIGHT)\n >>= return . round\n return (w,h)\n\n\nsetCapProp cap prop val = withCapture cap $\u00a0\\ccap ->\n {#call cvSetCaptureProperty#} \n ccap (fromProp prop) (realToFrac val)\n\nnumberOfFrames cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp CAP_PROP_FRAME_COUNT)\n >>= return . floor\n\nframeNumber cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap (fromProp CAP_PROP_POS_FRAMES) >>= return . floor\n\n-- Video Writing\n\ndata Codec = MPG4 deriving (Eq,Show)\n\ncreateVideoWriter filename codec framerate frameSize = \n withCString filename $ \\cfilename -> do\n ptr <- {#call wrapCreateVideoWriter#} cfilename fourcc \n framerate w h 0\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 (fromIntegral -> w, fromIntegral -> h) = frameSize\n fourcc | codec == MPG4 = 0x4d504734 -- This is so wrong..\n\nwriteFrame :: VideoWriter -> Image RGB D32 -> IO ()\nwriteFrame writer img = withVideoWriter writer $\u00a0\\cwriter ->\n withImage img $ \\cimg -> \n {#call cvWriteFrame #} cwriter cimg >> return ()\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2bbf2c25ca6715bd06313394d9c174e84bdf63b0","subject":"regexdispatcher: small simplification","message":"regexdispatcher: small simplification\n","repos":"BernhardDenner\/libelektra,petermax2\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,e1528532\/libelektra,petermax2\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,mpranj\/libelektra,e1528532\/libelektra,mpranj\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,ElektraInitiative\/libelektra,mpranj\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,petermax2\/libelektra,mpranj\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,mpranj\/libelektra,petermax2\/libelektra,e1528532\/libelektra,mpranj\/libelektra,petermax2\/libelektra,petermax2\/libelektra,BernhardDenner\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,mpranj\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,ElektraInitiative\/libelektra,mpranj\/libelektra,e1528532\/libelektra,BernhardDenner\/libelektra,petermax2\/libelektra","old_file":"src\/bindings\/haskell\/src\/Elektra\/Key.chs","new_file":"src\/bindings\/haskell\/src\/Elektra\/Key.chs","new_contents":"--\n-- @file\n--\n-- @brief Key Haskell bindings\n--\n-- @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n-- \nmodule Elektra.Key (\n Key (..), Namespace (..), ElektraKeyVarargs (KeyMetaName, KeyBinary, KeyComment, KeyOwner),\n keyNew, keyNewWithValue, keyNewWithFlagsAndValue,\n keyDup, keyCopy, keyClear,\n keyIncRef, keyDecRef, keyGetRef,\n keyName, keyGetNameSize, keySetName, keyAddName, \n keyUnescapedName, keyGetUnescapedNameSize,\n keyGetFullNameSize, keyGetFullName,\n keyBaseName, keyGetBaseName, keyGetBaseNameSize, keyAddBaseName, keySetBaseName, keyDeleteBaseName,\n keyGetNamespace,\n keyString, keyGetValueSize, keySetString, keySet,\n keyRewindMeta, keyNextMeta, keyCurrentMeta,\n keyCopyMeta, keyCopyAllMeta, keyGetMeta, keySetMeta, keyListMeta,\n keyCmp, keyNeedSync, \n keyIsBelow, keyIsDirectBelow, \n keyRel, keyIsInactive, keyIsBinary, keyIsString, keyPtrNull, \n ifKey, withKey, whenKey,\n tmpRef\n) where\n\n#include \nimport Foreign.Marshal.Alloc (allocaBytes)\nimport Foreign.Ptr (castPtr, nullPtr)\nimport Foreign.ForeignPtr (FinalizerPtr (..), withForeignPtr, addForeignPtrFinalizer)\nimport System.IO.Unsafe (unsafePerformIO)\nimport Data.Maybe (isJust, fromJust)\nimport Control.Monad (liftM)\nimport Data.Bool (bool)\n\n{#context lib=\"libelektra\" #}\n\n-- ***\n-- TYPE DEFINITIONS\n-- ***\n\n{#pointer *Key foreign 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\ndata KeyNew = KeyNew { knKeyName :: Maybe String\n , knKeyValue :: Maybe String\n , knMeta :: [(String, String)]\n , knKeySize :: Maybe Int\n , knFlags :: [ElektraKeyVarargs]\n } deriving (Show)\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 = keyNewRaw name KeyEnd >>= addFinalizer\nkeyNewWithValue :: String -> String -> IO Key\nkeyNewWithValue name value = keyNewRawWithValue name KeyValue value KeyEnd >>= addFinalizer\nkeyNewWithFlagsAndValue :: String -> ElektraKeyVarargs -> String -> IO Key\nkeyNewWithFlagsAndValue name flags value = keyNewRawWithFlagsAndValue name KeyFlags flags KeyValue value KeyEnd >>= addFinalizer\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' #}\n{#fun unsafe variadic keyNew[keyswitch_t, keyswitch_t, keyswitch_t, const char *, keyswitch_t]\n as keyNewRawWithFlagsAndValue \n {`String', `ElektraKeyVarargs', `ElektraKeyVarargs', `ElektraKeyVarargs', `String', `ElektraKeyVarargs'} \n -> `Key' #}\nkeyDup :: Key -> IO Key\nkeyDup k = keyDupRaw k >>= addFinalizer\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' #}\nkeySetBaseName :: Key -> String -> IO Int\nkeySetBaseName key baseName = keySetBaseNameRaw key (Just baseName)\nkeyDeleteBaseName :: Key -> IO Int\nkeyDeleteBaseName key = keySetBaseNameRaw key Nothing\nkeySetBaseNameRaw :: Key -> Maybe String -> IO Int\nkeySetBaseNameRaw key baseName = do\n withKey key $ \\cKey -> if (isJust baseName)\n then C2HSImp.withCString (fromJust baseName) $ \\cValue -> call cKey cValue\n else call cKey nullPtr\n where call cKey cValue = {#call unsafe keySetBaseName as keySetBaseNameRaw' #} cKey cValue\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 as keyNextMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCurrentMeta as keyCurrentMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCopyMeta {`Key', `Key', `String'} -> `Int' #}\n{#fun unsafe keyCopyAllMeta {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyGetMeta as 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\naddFinalizer :: Key -> IO Key\naddFinalizer (Key a) = addForeignPtrFinalizer keyDel a >> return (Key a)\n\nifKey :: IO a -> (Key -> IO a) -> Key -> IO a\nifKey f t k = keyPtrNull k >>= bool (t k) f \n\nwhenKey :: (Key -> IO ()) -> Key -> IO ()\nwhenKey w k = ifKey (return ()) w k\n\n-- Temporarily increases the reference counter so e.g. a keyset will not take ownership so\n-- Haskell's finalizer can run successfully afterwards\ntmpRef :: Key -> IO Key\ntmpRef k@(Key a) = keyIncRef k >> addForeignPtrFinalizer keyDecRefPtr a >> return (Key a)\n\nforeign import ccall unsafe \"Elektra\/Key.chs.h &keyDel\"\n keyDel :: C2HSImp.FunPtr ((C2HSImp.Ptr (Key)) -> (IO ()))\n\n\nforeign import ccall unsafe \"Elektra\/Key.chs.h &keyDecRef\"\n keyDecRefPtr :: C2HSImp.FunPtr ((C2HSImp.Ptr (Key)) -> (IO ()))\n","old_contents":"--\n-- @file\n--\n-- @brief Key Haskell bindings\n--\n-- @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n-- \nmodule Elektra.Key (\n Key (..), Namespace (..), ElektraKeyVarargs (KeyMetaName, KeyBinary, KeyComment, KeyOwner),\n keyNew, keyNewWithValue, keyNewWithFlagsAndValue,\n keyDup, keyCopy, keyClear,\n keyIncRef, keyDecRef, keyGetRef,\n keyName, keyGetNameSize, keySetName, keyAddName, \n keyUnescapedName, keyGetUnescapedNameSize,\n keyGetFullNameSize, keyGetFullName,\n keyBaseName, keyGetBaseName, keyGetBaseNameSize, keyAddBaseName, keySetBaseName, keyDeleteBaseName,\n keyGetNamespace,\n keyString, keyGetValueSize, keySetString, keySet,\n keyRewindMeta, keyNextMeta, keyCurrentMeta,\n keyCopyMeta, keyCopyAllMeta, keyGetMeta, keySetMeta, keyListMeta,\n keyCmp, keyNeedSync, \n keyIsBelow, keyIsDirectBelow, \n keyRel, keyIsInactive, keyIsBinary, keyIsString, keyPtrNull, \n ifKey, withKey, whenKey,\n tmpRef\n) where\n\n#include \nimport Foreign.Marshal.Alloc (allocaBytes)\nimport Foreign.Ptr (castPtr, nullPtr)\nimport Foreign.ForeignPtr (FinalizerPtr (..), withForeignPtr, addForeignPtrFinalizer)\nimport System.IO.Unsafe (unsafePerformIO)\nimport Data.Maybe (isJust, fromJust)\nimport Control.Monad (liftM, join)\nimport Data.Bool (bool)\n\n{#context lib=\"libelektra\" #}\n\n-- ***\n-- TYPE DEFINITIONS\n-- ***\n\n{#pointer *Key foreign 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\ndata KeyNew = KeyNew { knKeyName :: Maybe String\n , knKeyValue :: Maybe String\n , knMeta :: [(String, String)]\n , knKeySize :: Maybe Int\n , knFlags :: [ElektraKeyVarargs]\n } deriving (Show)\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 = keyNewRaw name KeyEnd >>= addFinalizer\nkeyNewWithValue :: String -> String -> IO Key\nkeyNewWithValue name value = keyNewRawWithValue name KeyValue value KeyEnd >>= addFinalizer\nkeyNewWithFlagsAndValue :: String -> ElektraKeyVarargs -> String -> IO Key\nkeyNewWithFlagsAndValue name flags value = keyNewRawWithFlagsAndValue name KeyFlags flags KeyValue value KeyEnd >>= addFinalizer\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' #}\n{#fun unsafe variadic keyNew[keyswitch_t, keyswitch_t, keyswitch_t, const char *, keyswitch_t]\n as keyNewRawWithFlagsAndValue \n {`String', `ElektraKeyVarargs', `ElektraKeyVarargs', `ElektraKeyVarargs', `String', `ElektraKeyVarargs'} \n -> `Key' #}\nkeyDup :: Key -> IO Key\nkeyDup k = keyDupRaw k >>= addFinalizer\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' #}\nkeySetBaseName :: Key -> String -> IO Int\nkeySetBaseName key baseName = keySetBaseNameRaw key (Just baseName)\nkeyDeleteBaseName :: Key -> IO Int\nkeyDeleteBaseName key = keySetBaseNameRaw key Nothing\nkeySetBaseNameRaw :: Key -> Maybe String -> IO Int\nkeySetBaseNameRaw key baseName = do\n withKey key $ \\cKey -> if (isJust baseName)\n then C2HSImp.withCString (fromJust baseName) $ \\cValue -> call cKey cValue\n else call cKey nullPtr\n where call cKey cValue = {#call unsafe keySetBaseName as keySetBaseNameRaw' #} cKey cValue\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 as keyNextMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCurrentMeta as keyCurrentMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCopyMeta {`Key', `Key', `String'} -> `Int' #}\n{#fun unsafe keyCopyAllMeta {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyGetMeta as 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\naddFinalizer :: Key -> IO Key\naddFinalizer (Key a) = addForeignPtrFinalizer keyDel a >> return (Key a)\n\nifKey :: IO a -> (Key -> IO a) -> Key -> IO a\nifKey f t k = join $ bool (t k) f <$> keyPtrNull k\n\nwhenKey :: (Key -> IO ()) -> Key -> IO ()\nwhenKey w k = ifKey (return ()) w k\n\n-- Temporarily increases the reference counter so e.g. a keyset will not take ownership so\n-- Haskell's finalizer can run successfully afterwards\ntmpRef :: Key -> IO Key\ntmpRef k@(Key a) = keyIncRef k >> addForeignPtrFinalizer keyDecRefPtr a >> return (Key a)\n\nforeign import ccall unsafe \"Elektra\/Key.chs.h &keyDel\"\n keyDel :: C2HSImp.FunPtr ((C2HSImp.Ptr (Key)) -> (IO ()))\n\n\nforeign import ccall unsafe \"Elektra\/Key.chs.h &keyDecRef\"\n keyDecRefPtr :: C2HSImp.FunPtr ((C2HSImp.Ptr (Key)) -> (IO ()))\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"59323f75a8a53bc03022b92f890ea6d18f23f454","subject":"export the record constructors, useful for `choose'","message":"export the record constructors, useful for `choose'\n\nIgnore-this: bc06b33f525749eeb33ab6d5cf2fb1a\n\ndarcs-hash:20090911024325-115f9-4ce6986a8febf209a345c936bb8863460cd62e84.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Device.chs","new_file":"Foreign\/CUDA\/Device.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Device\n (\n ComputeMode(..),\n DeviceFlags(..),\n DeviceProperties(..),\n\n -- ** Device management\n choose,\n get,\n count,\n props,\n set,\n setFlags,\n setOrder\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum cudaComputeMode as ComputeMode { }\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlags { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Double, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\nchoose :: DeviceProperties -> IO (Either String Int)\nchoose dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n-- |\n-- Returns which device is currently being used\n--\nget :: IO (Either String Int)\nget = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Return information about the selected compute device\n--\nprops :: Int -> IO (Either String DeviceProperties)\nprops n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek* ,\n `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set device to be used for GPU execution\n--\nset :: Int -> IO (Maybe String)\nset n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set flags to be used for device executions\n--\nsetFlags :: [DeviceFlags] -> IO (Maybe String)\nsetFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\nsetOrder :: [Int] -> IO (Maybe String)\nsetOrder l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\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-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Device\n (\n ComputeMode,\n DeviceFlags,\n DeviceProperties(..),\n\n -- ** Device management\n choose,\n get,\n count,\n props,\n set,\n setFlags,\n setOrder\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum cudaComputeMode as ComputeMode { }\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlags { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Double, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\nchoose :: DeviceProperties -> IO (Either String Int)\nchoose dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n-- |\n-- Returns which device is currently being used\n--\nget :: IO (Either String Int)\nget = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Return information about the selected compute device\n--\nprops :: Int -> IO (Either String DeviceProperties)\nprops n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek* ,\n `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set device to be used for GPU execution\n--\nset :: Int -> IO (Maybe String)\nset n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set flags to be used for device executions\n--\nsetFlags :: [DeviceFlags] -> IO (Maybe String)\nsetFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\nsetOrder :: [Int] -> IO (Maybe String)\nsetOrder l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"cf6780df46e6f11d26513b5db043308364013b08","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.","repos":"vincenthz\/webkit","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":"3b977b1ca1bca34385d3746fd7d3da13e01c2b08","subject":"Lots of haddock in Internal. I'm marking completed sections as DONE, will remove this once I'm done.","message":"Lots of haddock in Internal. I'm marking completed sections as DONE,\nwill remove this once I'm done.\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. DONE\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. DONE\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- * Ranks. DONE\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. DONE\n -- ** Tags. DONE\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations. DONE\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations. DONE\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations. DONE\n -- ** One-to-all. DONE\n bcast, scatter, scatterv,\n -- ** All-to-one. DONE\n gather, gatherv, reduce,\n -- ** All-to-all. DONE\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations. DONE\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing. DONE\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\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 -- ^ Major part\n , subversion :: Int -- ^ Minor part\n }\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-- | 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, 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{-| 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 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\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 #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A 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{-\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\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\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-- | 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, 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 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 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 '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#if 0\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{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\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 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\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, errorsThrowExceptions :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n-- This is a more meaningful name than errorsReturn\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 #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A 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{-\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 :: 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{-\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\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":"3c4ed2e920690677c006588fb00086ffb5b9c144","subject":"export Event constructor","message":"export Event constructor\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Event.chs","new_file":"Foreign\/CUDA\/Driver\/Event.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Event\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Event management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Event (\n\n -- * Event Management\n Event(..), EventFlag(..), WaitFlag,\n create, destroy, elapsedTime, query, record, wait, block\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.Stream (Stream(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- Events\n--\nnewtype Event = Event { useEvent :: {# type CUevent #}}\n deriving (Eq, Show)\n\n-- |\n-- Event creation flags\n--\n{# enum CUevent_flags as EventFlag\n { underscoreToCase }\n with prefix=\"CU_EVENT\" deriving (Eq, Show) #}\n\n-- |\n-- Possible option flags for waiting for events\n--\ndata WaitFlag\ninstance Enum WaitFlag where\n\n\n--------------------------------------------------------------------------------\n-- Event management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new event\n--\n{-# INLINEABLE create #-}\ncreate :: [EventFlag] -> IO Event\ncreate !flags = resultIfOk =<< cuEventCreate flags\n\n{-# INLINE cuEventCreate #-}\n{# fun unsafe cuEventCreate\n { alloca- `Event' peekEvt*\n , combineBitMasks `[EventFlag]' } -> `Status' cToEnum #}\n where peekEvt = liftM Event . peek\n\n\n-- |\n-- Destroy an event\n--\n{-# INLINEABLE destroy #-}\ndestroy :: Event -> IO ()\ndestroy !ev = nothingIfOk =<< cuEventDestroy ev\n\n{-# INLINE cuEventDestroy #-}\n{# fun unsafe cuEventDestroy\n { useEvent `Event' } -> `Status' cToEnum #}\n\n\n-- |\n-- Determine the elapsed time (in milliseconds) between two events\n--\n{-# INLINEABLE elapsedTime #-}\nelapsedTime :: Event -> Event -> IO Float\nelapsedTime !ev1 !ev2 = resultIfOk =<< cuEventElapsedTime ev1 ev2\n\n{-# INLINE cuEventElapsedTime #-}\n{# fun unsafe cuEventElapsedTime\n { alloca- `Float' peekFloatConv*\n , useEvent `Event'\n , useEvent `Event' } -> `Status' cToEnum #}\n\n\n-- |\n-- Determines if a event has actually been recorded\n--\n{-# INLINEABLE query #-}\nquery :: Event -> IO Bool\nquery !ev =\n cuEventQuery ev >>= \\rv ->\n case rv of\n Success -> return True\n NotReady -> return False\n _ -> resultIfOk (rv,undefined)\n\n{-# INLINE cuEventQuery #-}\n{# fun unsafe cuEventQuery\n { useEvent `Event' } -> `Status' cToEnum #}\n\n\n-- |\n-- Record an event once all operations in the current context (or optionally\n-- specified stream) have completed. This operation is asynchronous.\n--\n{-# INLINEABLE record #-}\nrecord :: Event -> Maybe Stream -> IO ()\nrecord !ev !mst =\n nothingIfOk =<< case mst of\n Just st -> cuEventRecord ev st\n Nothing -> cuEventRecord ev (Stream nullPtr)\n\n{-# INLINE cuEventRecord #-}\n{# fun unsafe cuEventRecord\n { useEvent `Event'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Makes all future work submitted to the (optional) stream wait until the given\n-- event reports completion before beginning execution. Requires cuda-3.2.\n--\n{-# INLINEABLE wait #-}\nwait :: Event -> Maybe Stream -> [WaitFlag] -> IO ()\n#if CUDA_VERSION < 3020\nwait _ _ _ = requireSDK 3.2 \"wait\"\n#else\nwait !ev !mst !flags =\n nothingIfOk =<< case mst of\n Just st -> cuStreamWaitEvent st ev flags\n Nothing -> cuStreamWaitEvent (Stream nullPtr) ev flags\n\n{-# INLINE cuStreamWaitEvent #-}\n{# fun unsafe cuStreamWaitEvent\n { useStream `Stream'\n , useEvent `Event'\n , combineBitMasks `[WaitFlag]' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Wait until the event has been recorded\n--\n{-# INLINEABLE block #-}\nblock :: Event -> IO ()\nblock !ev = nothingIfOk =<< cuEventSynchronize ev\n\n{-# INLINE cuEventSynchronize #-}\n{# fun unsafe cuEventSynchronize\n { useEvent `Event' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Event\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Event management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Event (\n\n -- * Event Management\n Event, EventFlag(..), WaitFlag,\n create, destroy, elapsedTime, query, record, wait, block\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.Stream (Stream(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- Events\n--\nnewtype Event = Event { useEvent :: {# type CUevent #}}\n deriving (Eq, Show)\n\n-- |\n-- Event creation flags\n--\n{# enum CUevent_flags as EventFlag\n { underscoreToCase }\n with prefix=\"CU_EVENT\" deriving (Eq, Show) #}\n\n-- |\n-- Possible option flags for waiting for events\n--\ndata WaitFlag\ninstance Enum WaitFlag where\n\n\n--------------------------------------------------------------------------------\n-- Event management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new event\n--\n{-# INLINEABLE create #-}\ncreate :: [EventFlag] -> IO Event\ncreate !flags = resultIfOk =<< cuEventCreate flags\n\n{-# INLINE cuEventCreate #-}\n{# fun unsafe cuEventCreate\n { alloca- `Event' peekEvt*\n , combineBitMasks `[EventFlag]' } -> `Status' cToEnum #}\n where peekEvt = liftM Event . peek\n\n\n-- |\n-- Destroy an event\n--\n{-# INLINEABLE destroy #-}\ndestroy :: Event -> IO ()\ndestroy !ev = nothingIfOk =<< cuEventDestroy ev\n\n{-# INLINE cuEventDestroy #-}\n{# fun unsafe cuEventDestroy\n { useEvent `Event' } -> `Status' cToEnum #}\n\n\n-- |\n-- Determine the elapsed time (in milliseconds) between two events\n--\n{-# INLINEABLE elapsedTime #-}\nelapsedTime :: Event -> Event -> IO Float\nelapsedTime !ev1 !ev2 = resultIfOk =<< cuEventElapsedTime ev1 ev2\n\n{-# INLINE cuEventElapsedTime #-}\n{# fun unsafe cuEventElapsedTime\n { alloca- `Float' peekFloatConv*\n , useEvent `Event'\n , useEvent `Event' } -> `Status' cToEnum #}\n\n\n-- |\n-- Determines if a event has actually been recorded\n--\n{-# INLINEABLE query #-}\nquery :: Event -> IO Bool\nquery !ev =\n cuEventQuery ev >>= \\rv ->\n case rv of\n Success -> return True\n NotReady -> return False\n _ -> resultIfOk (rv,undefined)\n\n{-# INLINE cuEventQuery #-}\n{# fun unsafe cuEventQuery\n { useEvent `Event' } -> `Status' cToEnum #}\n\n\n-- |\n-- Record an event once all operations in the current context (or optionally\n-- specified stream) have completed. This operation is asynchronous.\n--\n{-# INLINEABLE record #-}\nrecord :: Event -> Maybe Stream -> IO ()\nrecord !ev !mst =\n nothingIfOk =<< case mst of\n Just st -> cuEventRecord ev st\n Nothing -> cuEventRecord ev (Stream nullPtr)\n\n{-# INLINE cuEventRecord #-}\n{# fun unsafe cuEventRecord\n { useEvent `Event'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Makes all future work submitted to the (optional) stream wait until the given\n-- event reports completion before beginning execution. Requires cuda-3.2.\n--\n{-# INLINEABLE wait #-}\nwait :: Event -> Maybe Stream -> [WaitFlag] -> IO ()\n#if CUDA_VERSION < 3020\nwait _ _ _ = requireSDK 3.2 \"wait\"\n#else\nwait !ev !mst !flags =\n nothingIfOk =<< case mst of\n Just st -> cuStreamWaitEvent st ev flags\n Nothing -> cuStreamWaitEvent (Stream nullPtr) ev flags\n\n{-# INLINE cuStreamWaitEvent #-}\n{# fun unsafe cuStreamWaitEvent\n { useStream `Stream'\n , useEvent `Event'\n , combineBitMasks `[WaitFlag]' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Wait until the event has been recorded\n--\n{-# INLINEABLE block #-}\nblock :: Event -> IO ()\nblock !ev = nothingIfOk =<< cuEventSynchronize ev\n\n{-# INLINE cuEventSynchronize #-}\n{# fun unsafe cuEventSynchronize\n { useEvent `Event' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"dcd11e399f0e460b4d0cb82406c22745d3d48076","subject":"Add some functions in SourceCompletionProvider module","message":"Add some functions in SourceCompletionProvider module\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9babb093afd98273d9cb8a5656abd4b10f343df2","subject":"SVG: provide implementation for GObjectClass","message":"SVG: provide implementation for GObjectClass\n","repos":"gtk2hs\/gtksourceview,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 (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":"2acc1bb99e30b02896729fd7cf7f908c4396c2f1","subject":"Add function `widgetGetAllocation` and fix version tag.","message":"Add function `widgetGetAllocation` and fix version tag.\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fb94f83ec9e2edf376d96add432f157fb66c8561","subject":"Cleanups and fixes in CV.Filters","message":"Cleanups and fixes in CV.Filters\n\nAdded documentation, cleaned up code\nand fixed the bilateral filter.\n","repos":"aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV","old_file":"CV\/Filters.chs","new_file":"CV\/Filters.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, TypeFamilies, FlexibleInstances#-}\n#include \"cvWrapLEO.h\"\n{-#OPTIONS_GHC -fwarn-unused-imports#-}\n\n-- | This module is a collection of various image filters\nmodule CV.Filters(\n gaussian,gaussianOp\n ,blurOp,blur,blurNS\n ,bilateral\n ,HasMedianFiltering,median\n ,susan,getCentralMoment,getAbsCentralMoment\n ,getMoment,secondMomentBinarize,secondMomentBinarizeOp\n ,secondMomentAdaptiveBinarize,secondMomentAdaptiveBinarizeOp\n ,selectiveAvg,convolve2D,convolve2DI,haar,haarAt\n ,IntegralImage(),integralImage,verticalAverage) where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.Marshal.Utils\nimport CV.Bindings.ImgProc\n\nimport Utils.GeometryClass\nimport CV.Matrix (Matrix,withMatPtr)\nimport CV.ImageOp\n\nimport System.IO.Unsafe\n\n--import C2HSTools\n{#import CV.Image#}\n\n-- Low level wrapper for Susan filtering:\n-- IplImage* susanSmooth(IplImage *src, int w, int h\n-- ,double t, double sigma); \n\n-- | SUSAN adaptive smoothing filter, see \nsusan :: (Int, Int) -> Double -> Double\n -> Image GrayScale D32 -> Image GrayScale D32\nsusan (w,h) t sigma image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call susanSmooth#} img (fromIntegral w) (fromIntegral h) \n (realToFrac t) (realToFrac sigma))\n-- TODO: ADD checks above!\n\n-- | A selective average filter is an edge preserving noise reduction filter.\n-- It is a standard gaussian filter which ignores pixel values\n-- that are more than a given threshold away from the filtered pixel value.\nselectiveAvg :: (Int, Int) -> Double \n -> Image GrayScale D32 -> Image GrayScale D32\nselectiveAvg (w,h) t image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call selectiveAvgFilter#} \n img (realToFrac t) (fromIntegral w) (fromIntegral h))\n-- TODO: ADD checks above!\n\ngetCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthCentralMoment#} img n w h)\n\ngetAbsCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthAbsCentralMoment#} img n w h)\n\ngetMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthMoment#} img n w h)\n-- TODO: ADD checks above!\n\nsecondMomentBinarizeOp t = ImgOp $ \\image -> \n withGenImage image (flip {#call smb#} $ t)\nsecondMomentBinarize t i = unsafeOperate (secondMomentBinarizeOp t) i\n\nsecondMomentAdaptiveBinarizeOp w h t = ImgOp $ \\image -> \n withGenImage image \n (\\i-> {#call smab#} i w h t)\nsecondMomentAdaptiveBinarize w h t i = unsafeOperate (secondMomentAdaptiveBinarizeOp w h t) i\n\n#c\nenum SmoothType {\n BlurNoScale = CV_BLUR_NO_SCALE,\n Blur = CV_BLUR,\n Gaussian = CV_GAUSSIAN,\n Median = CV_MEDIAN ,\n Bilateral = CV_BILATERAL \n};\n#endc\n{#enum SmoothType {}#}\n\n{#fun cvSmooth as smooth' \n {withGenImage* `Image GrayScale D32'\n ,withGenImage* `Image GrayScale D32'\n ,`Int',`Int',`Int',`Float',`Float'}\n -> `()'#}\n\n\n-- | Image operation which applies gaussian or unifarm smoothing with a given window size to the image.\ngaussianOp,blurOp,blurNSOp :: (Int, Int) -> ImageOperation GrayScale D32\ngaussianOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum Gaussian) w h 0 0\nblurOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum Blur) w h 0 0\nblurNSOp m = withMask m $ \\(w,h) img -> smooth' img img (fromEnum BlurNoScale) w h 0 0\n\n-- | Create a new image by applying gaussian, or uniform smoothing.\ngaussian,blur,blurNS :: (Int, Int) -> Image GrayScale D32 -> Image GrayScale D32\ngaussian = unsafeOperate . gaussianOp\nblur = unsafeOperate . blurOp\nblurNS = unsafeOperate . blurNSOp\n\nwithMask (w,h) op \n | maskIsOk (w,h) = ImgOp $ op (w,h)\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\n\n\n-- | Apply bilateral filtering \nbilateral :: (Int,Int) -> (Int,Int) -> Image a D8 -> Image a D8\nbilateral (w,h) (s1,s2) img = unsafePerformIO $ \n withClone img $ \\clone ->\n withGenImage img $ \\cimg ->\n withGenImage clone $ \\ccln -> do\n {#call cvSmooth#} cimg ccln (fromIntegral $ fromEnum Bilateral)\n (fromIntegral w) (fromIntegral h) \n (realToFrac s1) (realToFrac s2) \n\n\nclass HasMedianFiltering a where\n median :: (Int,Int) -> a -> a\n\ninstance HasMedianFiltering (Image GrayScale D8) where\n median = median'\n\ninstance HasMedianFiltering (Image RGB D8) where\n median = median'\n\n-- |\u00a0Perform median filtering on an eight bit image.\nmedian' :: (Int,Int) -> Image c D8 -> Image c D8\nmedian' (w,h) img \n | maskIsOk (w,h) = unsafePerformIO $ do\n clone2 <- cloneImage img\n withGenImage img $ \\c1 -> \n withGenImage clone2 $ \\c2 -> \n {#call cvSmooth#} c1 c2 (fromIntegral $ fromEnum Median) \n (fromIntegral w) (fromIntegral h) 0 0\n return clone2\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\nmaskIsOk (w,h) = odd w && odd h && w >0 && h>0\n\n\n-- General 2D comvolutions\n-- Convolve image with specified kernel stored in flat list.\n-- Kernel must have dimensions (w,h) and specified anchor point\n-- (x,y) within (0,0) and (w,h)\nconvolve2D :: (Point2D anchor, ELP anchor ~ Int) => \n Matrix D32 -> anchor -> Image GrayScale D32 -> Image GrayScale D32\nconvolve2D kernel anchor image = unsafePerformIO $ \n let result = emptyCopy image\n in withGenImage image $ \\c_img->\n withGenImage result $ \\c_res->\n withMatPtr kernel $ \\c_mat ->\n with (convertPt anchor) $ \\c_pt ->\n c'wrapFilter2 c_img c_res c_mat c_pt\n >> return result\n \nconvolve2DI (x,y) kernel image = unsafePerformIO $ \n withImage image $ \\img->\n withImage kernel $ \\k ->\n creatingImage $\n {#call wrapFilter2DImg#} \n img k x y\n\n-- | Replace pixel values by the average of the row. \nverticalAverage :: Image GrayScale D32 -> Image GrayScale D32\nverticalAverage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w,h) \n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call vertical_average#} i sum \n return s\n\n-- |\u00a0A type for storing integral images. Integral image stores for every pixel the sum of pixels\n-- above and left of it. Such images are used for significantly accelerating the calculation of\n-- area averages. \nnewtype IntegralImage = IntegralImage (Image GrayScale D64)\ninstance Sized IntegralImage where\n type Size IntegralImage = (Int,Int)\n getSize (IntegralImage i) = getSize i\n\ninstance GetPixel IntegralImage where\n type P IntegralImage = Double\n getPixel = getPixel\n\n-- |\u00a0Calculate the integral image from the given image.\nintegralImage :: Image GrayScale D32 -> IntegralImage\nintegralImage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w+1,h+1)\n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call cvIntegral#} i sum nullPtr nullPtr\n return $ IntegralImage s\n\n\n-- |Filter the image with box shaped averaging mask.\nhaar :: IntegralImage -> (Int,Int,Int,Int) -> Image GrayScale D32\nhaar (IntegralImage image) (a',b',c',d') = unsafePerformIO $ do\n let (w,h) = getSize image\n let [a,b,c,d] = map fromIntegral [a',b',c',d']\n r <- create (w,h)\n withImage image $ \\sum ->\n withImage r $ \\res -> do\n {#call haarFilter#} sum \n (min a c) \n (max b d)\n (max a c)\n (min b d) \n res\n return r\n\n-- | Get an average of a given region.\nhaarAt :: IntegralImage -> (Int,Int,Int,Int) -> Double\n\nhaarAt (IntegralImage ii) (a,b,w,h) = realToFrac $ unsafePerformIO $ withImage ii $ \\i -> \n {#call haar_at#} i (f a) (f b) (f w) (f h)\n where f = fromIntegral \n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, TypeFamilies, FlexibleInstances#-}\n#include \"cvWrapLEO.h\"\n{-#OPTIONS_GHC -fwarn-unused-imports#-}\n\n-- | This module is a collection of various image filters\nmodule CV.Filters(gaussian,gaussianOp\n ,blurOp,blur,blurNS\n ,HasMedianFiltering,median\n ,susan,getCentralMoment,getAbsCentralMoment\n ,getMoment,secondMomentBinarize,secondMomentBinarizeOp\n ,secondMomentAdaptiveBinarize,secondMomentAdaptiveBinarizeOp\n ,selectiveAvg,convolve2D,convolve2DI,haar,haarAt\n ,IntegralImage(),integralImage,verticalAverage) where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.Marshal.Utils\nimport CV.Bindings.ImgProc\n\nimport Utils.GeometryClass\nimport CV.Matrix (Matrix,withMatPtr)\nimport CV.ImageOp\n\nimport System.IO.Unsafe\n\n--import C2HSTools\n{#import CV.Image#}\n\n-- Low level wrapper for Susan filtering:\n-- IplImage* susanSmooth(IplImage *src, int w, int h\n-- ,double t, double sigma); \n\n-- | SUSAN adaptive smoothing filter, see \nsusan :: (Int, Int) -> Double -> Double\n -> Image GrayScale D32 -> Image GrayScale D32\nsusan (w,h) t sigma image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call susanSmooth#} img (fromIntegral w) (fromIntegral h) \n (realToFrac t) (realToFrac sigma))\n-- TODO: ADD checks above!\n\n-- | A selective average filter is an edge preserving noise reduction filter.\n-- It is a standard gaussian filter which ignores pixel values\n-- that are more than a given threshold away from the filtered pixel value.\nselectiveAvg :: (Int, Int) -> Double \n -> Image GrayScale D32 -> Image GrayScale D32\nselectiveAvg (w,h) t image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call selectiveAvgFilter#} \n img (realToFrac t) (fromIntegral w) (fromIntegral h))\n-- TODO: ADD checks above!\n\ngetCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthCentralMoment#} img n w h)\n\ngetAbsCentralMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthAbsCentralMoment#} img n w h)\n\ngetMoment n (w,h) image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage \n ({#call getNthMoment#} img n w h)\n-- TODO: ADD checks above!\n\nsecondMomentBinarizeOp t = ImgOp $ \\image -> \n withGenImage image (flip {#call smb#} $ t)\nsecondMomentBinarize t i = unsafeOperate (secondMomentBinarizeOp t) i\n\nsecondMomentAdaptiveBinarizeOp w h t = ImgOp $ \\image -> \n withGenImage image \n (\\i-> {#call smab#} i w h t)\nsecondMomentAdaptiveBinarize w h t i = unsafeOperate (secondMomentAdaptiveBinarizeOp w h t) i\n\ndata SmoothType = BlurNoScale | Blur \n | Gaussian | Median \n | Bilateral\n deriving(Enum)\n\n{#fun cvSmooth as smooth' \n {withGenImage* `Image GrayScale D32'\n ,withGenImage* `Image GrayScale D32'\n ,`Int',`Int',`Int',`Float',`Float'}\n -> `()'#}\n\ngaussianOp (w,h) \n | maskIsOk (w,h) = ImgOp $ \\img -> \n smooth' img img (fromEnum Gaussian) w h 0 0\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\ngaussian = unsafeOperate.gaussianOp\n\nblurOp (w,h) \n | maskIsOk (w,h) = ImgOp $ \\img -> \n smooth' img img (fromEnum Blur) w h 0 0\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\nblurNSOp (w,h) \n | maskIsOk (w,h) = ImgOp $ \\img -> \n smooth' img img (fromEnum BlurNoScale) w h 0 0\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\nblur size image = let r = unsafeOperate (blurOp size) image\n in r\nblurNS size image = let r = unsafeOperate (blurNSOp size) image\n in r\n\n-- | TODO: This doesn't give a reasonable result. Investigate\nbilateral :: Int -> Int -> Image GrayScale D8 -> Image GrayScale D8\nbilateral colorS spaceS img = unsafePerformIO $ \n withClone img $ \\clone ->\n withGenImage img $ \\cimg ->\n withGenImage clone $ \\ccln -> do\n {#call cvSmooth#} cimg ccln (fromIntegral $ fromEnum Bilateral)\n (fromIntegral colorS) (fromIntegral spaceS) 0 0\n\n\n-- TODO: The type is not exactly correct\n\nclass HasMedianFiltering a where\n median :: (Int,Int) -> a -> a\n\ninstance HasMedianFiltering (Image GrayScale D8) where\n median = median'\n\ninstance HasMedianFiltering (Image RGB D8) where\n median = median'\n\n-- |\u00a0Perform median filtering on an eight bit image.\nmedian' :: (Int,Int) -> Image c D8 -> Image c D8\nmedian' (w,h) img \n | maskIsOk (w,h) = unsafePerformIO $ do\n clone2 <- cloneImage img\n withGenImage img $ \\c1 -> \n withGenImage clone2 $ \\c2 -> \n {#call cvSmooth#} c1 c2 (fromIntegral $ fromEnum Median) \n (fromIntegral w) (fromIntegral h) 0 0\n return clone2\n | otherwise = error \"One of aperture dimensions is incorrect (should be >=1 and odd))\"\n\nmaskIsOk (w,h) = odd w && odd h && w >0 && h>0\n\n\n-- General 2D comvolutions\n-- Convolve image with specified kernel stored in flat list.\n-- Kernel must have dimensions (w,h) and specified anchor point\n-- (x,y) within (0,0) and (w,h)\nconvolve2D :: (Point2D anchor, ELP anchor ~ Int) => \n Matrix D32 -> anchor -> Image GrayScale D32 -> Image GrayScale D32\nconvolve2D kernel anchor image = unsafePerformIO $ \n let result = emptyCopy image\n in withGenImage image $ \\c_img->\n withGenImage result $ \\c_res->\n withMatPtr kernel $ \\c_mat ->\n with (convertPt anchor) $ \\c_pt ->\n c'wrapFilter2 c_img c_res c_mat c_pt\n >> return result\n \nconvolve2DI (x,y) kernel image = unsafePerformIO $ \n withImage image $ \\img->\n withImage kernel $ \\k ->\n creatingImage $\n {#call wrapFilter2DImg#} \n img k x y\n\n-- | Replace pixel values by the average of the row. \nverticalAverage :: Image GrayScale D32 -> Image GrayScale D32\nverticalAverage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w,h) \n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call vertical_average#} i sum \n return s\n\n-- |\u00a0A type for storing integral images. Integral image stores for every pixel the sum of pixels\n-- above and left of it. Such images are used for significantly accelerating the calculation of\n-- area averages. \nnewtype IntegralImage = IntegralImage (Image GrayScale D64)\ninstance Sized IntegralImage where\n type Size IntegralImage = (Int,Int)\n getSize (IntegralImage i) = getSize i\n\ninstance GetPixel IntegralImage where\n type P IntegralImage = Double\n getPixel = getPixel\n\n-- |\u00a0Calculate the integral image from the given image.\nintegralImage :: Image GrayScale D32 -> IntegralImage\nintegralImage image = unsafePerformIO $ do \n let (w,h) = getSize image\n s <- create (w+1,h+1)\n withGenImage image $ \\i -> do\n withGenImage s $ \\sum -> do\n {#call cvIntegral#} i sum nullPtr nullPtr\n return $ IntegralImage s\n\n\n-- |Filter the image with box shaped averaging mask.\nhaar :: IntegralImage -> (Int,Int,Int,Int) -> Image GrayScale D32\nhaar (IntegralImage image) (a',b',c',d') = unsafePerformIO $ do\n let (w,h) = getSize image\n let [a,b,c,d] = map fromIntegral [a',b',c',d']\n r <- create (w,h)\n withImage image $ \\sum ->\n withImage r $ \\res -> do\n {#call haarFilter#} sum \n (min a c) \n (max b d)\n (max a c)\n (min b d) \n res\n return r\n\n-- | Get an average of a given region.\nhaarAt :: IntegralImage -> (Int,Int,Int,Int) -> Double\n\nhaarAt (IntegralImage ii) (a,b,w,h) = realToFrac $ unsafePerformIO $ withImage ii $ \\i -> \n {#call haar_at#} i (f a) (f b) (f w) (f h)\n where f = fromIntegral \n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c3dd070ab29baee78886730241513c826e2730bc","subject":"Make more networky","message":"Make more networky\n","repos":"bneijt\/bluetooth,RyanGlScott\/bluetooth","old_file":"src\/Network\/Bluetooth\/Linux\/Socket.chs","new_file":"src\/Network\/Bluetooth\/Linux\/Socket.chs","new_contents":"{-# LANGUAGE ScopedTypeVariables #-}\nmodule Network.Bluetooth.Linux.Socket where\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport Data.Either\n\nimport Foreign.C.Error\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Exception\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Protocol\nimport Network.Bluetooth.Utils\nimport Network.Socket\nimport Network.Socket.Internal\n\nimport System.Posix.Internals (setNonBlockingFD)\n\n#include \n#include \n#include \"wr_l2cap.h\"\n#include \"wr_rfcomm.h\"\n\nbluetoothSocket :: BluetoothProtocol -> IO Socket\nbluetoothSocket proto = socket AF_BLUETOOTH sockType protoNum\n where\n sockType = case proto of\n L2CAP -> SeqPacket\n RFCOMM -> Stream\n protoNum = cFromEnum proto\n\nbluetoothBind :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothBind (MkSocket fd _ _ proto sockStatus) bdaddr portNum =\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n \"bind: can't peform bind on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n case protoEnum of\n L2CAP -> callBind $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> callBind . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n return Bound\n where\n callBind :: SockAddrBluetooth a => a -> IO ()\n callBind sockaddr = throwSocketErrorIfMinus1Retry_ \"bind\" $ c_bind fd sockaddr\n\nbluetoothBindAnyPort :: Socket -> BluetoothAddr -> IO BluetoothPort\nbluetoothBindAnyPort sock@(MkSocket _ _ _ proto _) bdaddr = do\n port <- bindAnyPort (cToEnum proto) bdaddr\n bluetoothBind sock bdaddr $ fromIntegral port\n return port\n\nbluetoothListen :: Socket -> Int -> IO ()\nbluetoothListen = listen\n\nbluetoothAccept :: Socket -> IO (Socket, BluetoothAddr)\nbluetoothAccept sock@(MkSocket _ family sockType proto sockStatus) = do\n currentStatus <- readMVar sockStatus\n when (currentStatus \/= Connected && currentStatus \/= Listening) . ioError . userError $\n \"accept: can't perform accept on socket (\" ++ show (family,sockType,proto) ++ \") in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callAccept :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO (Socket, BluetoothAddr)\n callAccept sock'@(MkSocket fd _ _ _ _) sockaddrPtr size = do\n newFd <- throwSocketErrorWaitRead sock' \"accept\" . fmap fst $ c_accept fd sockaddrPtr size\n setNonBlockIfNeeded newFd\n bdaddr <- fmap sockAddrBluetoothAddr $ peek sockaddrPtr\n newStatus <- newMVar Connected\n return (MkSocket newFd family sockType proto newStatus, bdaddr)\n\nbluetoothConnect :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothConnect sock@(MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n status <- takeMVar sockStatus\n when (status \/= NotConnected && status \/= Bound) . ioError . userError $\n \"connect: can't peform connect on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n \n let connectLoop :: IO ()\n connectLoop = do\n r <- case protoEnum of\n L2CAP -> c_connect fd $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> c_connect fd . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n putMVar sockStatus Connected\n when (r == -1) $ do\n err <- getErrno\n case () of\n _ | err == eINTR -> connectLoop\n _ | err == eINPROGRESS -> connectBlocked\n _otherwise -> throwSocketError \"connect\"\n \n connectBlocked :: IO ()\n connectBlocked = do\n threadWaitWrite $ fromIntegral fd\n err <- getSocketOption sock SoError\n unless (err == 0) . throwSocketErrorCode \"connect\" $ fromIntegral err\n \n connectLoop `onException` close sock\n\nbluetoothSocketPort :: Socket -> IO BluetoothPort\nbluetoothSocketPort sock@(MkSocket _ _ _ proto status) = do\n currentStatus <- readMVar status\n when (currentStatus == NotConnected || currentStatus == Closed) . ioError . userError $\n \"getsockname: can't get name of socket in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callGetSockName :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO BluetoothPort\n callGetSockName (MkSocket fd _ _ _ _) sockaddrPtr size = do\n throwSocketErrorIfMinus1Retry_ \"getsockname\" . fmap fst $ c_getsockname fd sockaddrPtr size\n fmap sockAddrPort $ peek sockaddrPtr\n\n-------------------------------------------------------------------------------\n\nbindAnyPort :: BluetoothProtocol -> BluetoothAddr -> IO BluetoothPort\nbindAnyPort proto addr = do\n avails <- flip filterM (portRange proto) $ \\portNum -> do\n sock <- bluetoothSocket proto\n res <- try $ bluetoothBind sock addr portNum\n close sock\n return $ isRight (res :: Either IOError ())\n case avails of\n portNum:_ -> return portNum\n _ -> ioError $ userError \"Unable to find any available port\"\n where\n portRange L2CAP = [4097, 4099 .. 32767]\n portRange RFCOMM = [1 .. 30]\n\nsetNonBlockIfNeeded :: CInt -> IO ()\nsetNonBlockIfNeeded = flip setNonBlockingFD True\n\n{#fun unsafe bind as c_bind\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe accept as c_accept\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun unsafe connect as c_connect\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe getsockname as c_getsockname\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun pure wr_htobs as c_htobs\n `Integral i' =>\n { fromIntegral `i'\n } -> `i' fromIntegral #}","old_contents":"{-# LANGUAGE ScopedTypeVariables #-}\nmodule Network.Bluetooth.Linux.Socket where\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport Data.Either\n\nimport Foreign.C.Error\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Exception\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Protocol\nimport Network.Bluetooth.Utils\nimport Network.Socket\nimport Network.Socket.Internal\n\n#include \n#include \n#include \"wr_l2cap.h\"\n#include \"wr_rfcomm.h\"\n\nbluetoothSocket :: BluetoothProtocol -> IO Socket\nbluetoothSocket proto = socket AF_BLUETOOTH sockType protoNum\n where\n sockType = case proto of\n L2CAP -> SeqPacket\n RFCOMM -> Stream\n protoNum = cFromEnum proto\n\nbluetoothBind :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothBind (MkSocket fd _ _ proto sockStatus) bdaddr portNum =\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n \"bind: can't peform bind on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n case protoEnum of\n L2CAP -> callBind $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> callBind . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n return Bound\n where\n callBind :: SockAddrBluetooth a => a -> IO ()\n callBind sockaddr = throwSocketErrorIfMinus1Retry_ \"bind\" $ c_bind fd sockaddr\n\nbluetoothBindAnyPort :: Socket -> BluetoothAddr -> IO BluetoothPort\nbluetoothBindAnyPort sock@(MkSocket _ _ _ proto _) bdaddr = do\n port <- bindAnyPort (cToEnum proto) bdaddr\n bluetoothBind sock bdaddr $ fromIntegral port\n return port\n\nbluetoothListen :: Socket -> Int -> IO ()\nbluetoothListen = listen\n\nbluetoothAccept :: Socket -> IO (Socket, BluetoothAddr)\nbluetoothAccept sock@(MkSocket _ family sockType proto sockStatus) = do\n currentStatus <- readMVar sockStatus\n when (currentStatus \/= Connected && currentStatus \/= Listening) . ioError . userError $\n \"accept: can't perform accept on socket (\" ++ show (family,sockType,proto) ++ \") in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callAccept sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callAccept :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO (Socket, BluetoothAddr)\n callAccept sock'@(MkSocket fd _ _ _ _) sockaddrPtr size = do\n newFd <- throwSocketErrorWaitRead sock' \"accept\" . fmap fst $ c_accept fd sockaddrPtr size\n bdaddr <- fmap sockAddrBluetoothAddr $ peek sockaddrPtr\n newStatus <- newMVar Connected\n return (MkSocket newFd family sockType proto newStatus, bdaddr)\n\nbluetoothConnect :: Socket -> BluetoothAddr -> BluetoothPort -> IO ()\nbluetoothConnect sock@(MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n status <- takeMVar sockStatus\n when (status \/= NotConnected && status \/= Bound) . ioError . userError $\n \"connect: can't peform connect on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n unless (isBluetoothPortValid protoEnum portNum) . throwIO $ BluetoothPortException protoEnum portNum\n \n let connectLoop :: IO ()\n connectLoop = do\n r <- case protoEnum of\n L2CAP -> c_connect fd $ SockAddrL2CAP AF_BLUETOOTH (c_htobs portNum) bdaddr\n RFCOMM -> c_connect fd . SockAddrRFCOMM AF_BLUETOOTH bdaddr $ fromIntegral portNum\n putMVar sockStatus Connected\n when (r == -1) $ do\n err <- getErrno\n case () of\n _ | err == eINTR -> connectLoop\n _ | err == eINPROGRESS -> connectBlocked\n _otherwise -> throwSocketError \"connect\"\n \n connectBlocked :: IO ()\n connectBlocked = do\n threadWaitWrite $ fromIntegral fd\n err <- getSocketOption sock SoError\n unless (err == 0) . throwSocketErrorCode \"connect\" $ fromIntegral err\n \n connectLoop `onException` close sock\n\nbluetoothSocketPort :: Socket -> IO BluetoothPort\nbluetoothSocketPort sock@(MkSocket _ _ _ proto status) = do\n currentStatus <- readMVar status\n when (currentStatus == NotConnected || currentStatus == Closed) . ioError . userError $\n \"getsockname: can't get name of socket in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> alloca $ \\(sockaddrPtr :: Ptr SockAddrL2CAP) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrL2CAP)\n RFCOMM -> alloca $ \\(sockaddrPtr :: Ptr SockAddrRFCOMM) ->\n callGetSockName sock sockaddrPtr $ sizeOf (undefined :: SockAddrRFCOMM)\n where\n callGetSockName :: SockAddrBluetooth a => Socket -> Ptr a -> Int -> IO BluetoothPort\n callGetSockName (MkSocket fd _ _ _ _) sockaddrPtr size = do\n throwSocketErrorIfMinus1Retry_ \"getsockname\" . fmap fst $ c_getsockname fd sockaddrPtr size\n fmap sockAddrPort $ peek sockaddrPtr\n\n-------------------------------------------------------------------------------\n\nbindAnyPort :: BluetoothProtocol -> BluetoothAddr -> IO BluetoothPort\nbindAnyPort proto addr = do\n avails <- flip filterM (portRange proto) $ \\portNum -> do\n sock <- bluetoothSocket proto\n res <- try $ bluetoothBind sock addr portNum\n close sock\n return $ isRight (res :: Either IOError ())\n case avails of\n portNum:_ -> return portNum\n _ -> ioError $ userError \"Unable to find any available port\"\n where\n portRange L2CAP = [4097, 4099 .. 32767]\n portRange RFCOMM = [1 .. 30]\n\n{#fun unsafe bind as c_bind\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe accept as c_accept\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun unsafe connect as c_connect\n `SockAddrBluetooth a' =>\n { id `CInt'\n , withCastLenConv* `a'&\n } -> `Int' #}\n\n{#fun unsafe getsockname as c_getsockname\n `SockAddrBluetooth a' =>\n { id `CInt'\n , castPtr `Ptr a'\n , `Int' peekFromIntegral*\n } -> `CInt' id #}\n\n{#fun pure wr_htobs as c_htobs\n `Integral i' =>\n { fromIntegral `i'\n } -> `i' fromIntegral #}","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"32b9afbe86157a431ce20500e57d290a9abc7ae0","subject":"For compatibility reasons re-ordered Image.montage output","message":"For compatibility reasons re-ordered Image.montage\noutput","repos":"BeautifulDestinations\/CV,TomMD\/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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 = 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..u-1] , x <- [0..v-1] \n | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 = 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 | x <- [0..u-1] , y <- [0..v-1] \n | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ab04d2889fd0ea72496dc3e2e7004b13d30952a5","subject":"Xine.Foreign: bindings for XINE_VIDEO_AFD_*","message":"Xine.Foreign: bindings for XINE_VIDEO_AFD_*\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{-# OPTIONS_GHC -Wwarn #-}\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(..), DemuxStrategy(..), Verbosity(..), MRL, EngineParam(..),\n 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-- | 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-- | Stream format detection strategies\n{#enum define DemuxStrategy\n {XINE_DEMUX_DEFAULT_STRATEGY as DemuxDefault,\n XINE_DEMUX_REVERT_STRATEGY as DemuxRevert,\n XINE_DEMUX_CONTENT_STRATEGY as DemuxContent,\n XINE_DEMUX_EXTENSION_STRATEGY as DemuxExtension}#}\n\n-- | Verbosity setting\n{#enum define Verbosity\n {XINE_VERBOSITY_NONE as VerbosityNone,\n XINE_VERBOSITY_LOG as VerbosityLog,\n XINE_VERBOSITY_DEBUG as VerbosityDebug}#}\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-- This is a trick to read the #define'd constant XINE_LANG_MAX\n{#enum define Wrapping\n {XINE_LANG_MAX as LangMax}#}\n\ncXINE_LANG_MAX :: Int\ncXINE_LANG_MAX = fromEnum LangMax\n\n-- Helper to allocate a language buffer\nallocLangBuf = allocaArray0 cXINE_LANG_MAX\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-- | Possible values for InfoVideoAFD\n{#enum define AFDValue\n {XINE_VIDEO_AFD_NOT_PRESENT as AFDNotPresent,\n XINE_VIDEO_AFD_RESERVED_0 as AFDReserved0,\n XINE_VIDEO_AFD_RESERVED_1 as AFDReserved1,\n XINE_VIDEO_AFD_BOX_16_9_TOP as AFDBox169Top,\n XINE_VIDEO_AFD_BOX_14_9_TOP as AFDBox149Top,\n XINE_VIDEO_AFD_BOX_GT_16_9_CENTRE as AFDGt169Centre,\n XINE_VIDEO_AFD_RESERVED_5 as AFDReserved5,\n XINE_VIDEO_AFD_RESERVED_6 as AFDReserved6,\n XINE_VIDEO_AFD_RESERVED_7 as AFDReserved7,\n XINE_VIDEO_AFD_SAME_AS_FRAME as AFDSameAsFrame,\n XINE_VIDEO_AFD_4_3_CENTRE as AFD43Centre,\n XINE_VIDEO_AFD_16_9_CENTRE as AFD169Centre,\n XINE_VIDEO_AFD_14_9_CENTRE as AFD149Centre,\n XINE_VIDEO_AFD_RESERVED_12 as AFDReserved12,\n XINE_VIDEO_AFD_4_3_PROTECT_14_9 as AFD43Protect149,\n XINE_VIDEO_AFD_16_9_PROTECT_14_9 as AFD169Protect149,\n XINE_VIDEO_AFD_16_9_PROTECT_4_3 as AFD169Protect43}#}\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{-# OPTIONS_GHC -Wwarn #-}\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(..), DemuxStrategy(..), Verbosity(..), MRL, EngineParam(..),\n 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-- | 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-- | Stream format detection strategies\n{#enum define DemuxStrategy\n {XINE_DEMUX_DEFAULT_STRATEGY as DemuxDefault,\n XINE_DEMUX_REVERT_STRATEGY as DemuxRevert,\n XINE_DEMUX_CONTENT_STRATEGY as DemuxContent,\n XINE_DEMUX_EXTENSION_STRATEGY as DemuxExtension}#}\n\n-- | Verbosity setting\n{#enum define Verbosity\n {XINE_VERBOSITY_NONE as VerbosityNone,\n XINE_VERBOSITY_LOG as VerbosityLog,\n XINE_VERBOSITY_DEBUG as VerbosityDebug}#}\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-- This is a trick to read the #define'd constant XINE_LANG_MAX\n{#enum define Wrapping\n {XINE_LANG_MAX as LangMax}#}\n\ncXINE_LANG_MAX :: Int\ncXINE_LANG_MAX = fromEnum LangMax\n\n-- Helper to allocate a language buffer\nallocLangBuf = allocaArray0 cXINE_LANG_MAX\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":"1de9c0a9f9f96c99f9f57ce1579b7c6c74540349","subject":"Docu tweaks","message":"Docu tweaks\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(..), 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\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {int2cint `Int',\n int2cint `Int',\n int2cint `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 (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","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(..), 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\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {int2cint `Int',\n int2cint `Int',\n int2cint `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' 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.\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.\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.\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":"d724a6a29e3ce41705e7e2a23b1eaab9bb978cde","subject":"Haddock tweaks in IO module.","message":"Haddock tweaks in IO module.\n\nIgnore-this: b196f8eb273decb2b48ef0744f4ff21\n\ndarcs-hash:20090309003406-ed7c9-59b52172dff531ed82dd48c8ac6696c830dadaab.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-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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, parseChunk, Encoding(..), XMLParseError(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level interface\n unsafeParseChunk,\n withHandlers,\n unsafeSetHandlers,\n unsafeReleaseHandlers,\n ExpatHandlers,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = withHandlers parser $ unsafeParseChunk parser xml final\n\n-- | This variant of parseChunk must either be called inside 'withHandlers' (safest), or\n-- between 'unsafeSetHandlers' and 'unsafeReleaseHandlers', and this\n-- will give you better performance than 'parseChunk' if you process multiple chunks inside.\nunsafeParseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nunsafeParseChunk parser xml final = do\n ok <- doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\n\ndata ExpatHandlers = ExpatHandlers\n (FunPtr CStartElementHandler)\n (FunPtr CEndElementHandler)\n (FunPtr CCharacterDataHandler)\n\nunsafeSetHandlers :: Parser -> IO ExpatHandlers\nunsafeSetHandlers parser@(Parser fp startRef endRef charRef) = 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 $ ExpatHandlers cStartH cEndH cCharH\n\nunsafeReleaseHandlers :: ExpatHandlers -> IO ()\nunsafeReleaseHandlers (ExpatHandlers cStartH cEndH cCharH) = do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH\n\n-- | 'unsafeParseChunk' is required to be called inside @withHandlers@.\n-- Safer than using 'unsafeSetHandlers' \/ 'unsafeReleaseHandlers'.\nwithHandlers :: Parser\n -> IO a -- ^ Computation where unsafeParseChunk may be used\n -> IO a\nwithHandlers parser code = do\n bracket\n (unsafeSetHandlers parser)\n unsafeReleaseHandlers\n (\\_ -> code)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- | Parse error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return True\n-- to continue parsing as normal, or False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return True to continue parsing as normal, or False to\n-- terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return True to continue\n-- parsing as normal, or False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","old_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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, parseChunk, Encoding(..), XMLParseError(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level interface\n withHandlers,\n unsafeSetHandlers,\n unsafeReleaseHandlers,\n ExpatHandlers,\n unsafeParseChunk,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = withHandlers parser $ unsafeParseChunk parser xml final\n\n-- | This version of parseChunk must either be called inside withHandlers (safest), or\n-- between 'unsafeSetHandlers' and 'unsafeReleaseHandlers', and this\n-- will give you better performance if you process multiple chunks inside.\nunsafeParseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nunsafeParseChunk parser xml final = do\n ok <- doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\n\ndata ExpatHandlers = ExpatHandlers\n (FunPtr CStartElementHandler)\n (FunPtr CEndElementHandler)\n (FunPtr CCharacterDataHandler)\n\nunsafeSetHandlers :: Parser -> IO ExpatHandlers\nunsafeSetHandlers parser@(Parser fp startRef endRef charRef) = 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 $ ExpatHandlers cStartH cEndH cCharH\n\nunsafeReleaseHandlers :: ExpatHandlers -> IO ()\nunsafeReleaseHandlers (ExpatHandlers cStartH cEndH cCharH) = do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH\n\n-- | 'unsafeParseChunk' is required to be called inside the argument to this.\n-- Safer than using unsafeSetHandlers \/ unsafeReleaseHandlers.\nwithHandlers :: Parser -> IO a -> IO a\nwithHandlers parser code = do\n bracket\n (unsafeSetHandlers parser)\n unsafeReleaseHandlers\n (\\_ -> code)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- | Parse error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return True\n-- to continue parsing as normal, or False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return True to continue parsing as normal, or False to\n-- terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return True to continue\n-- parsing as normal, or False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"08d8501ab077dace11bca4d8d006486bb31b2343","subject":"Make MessageID a newtype.","message":"Make MessageID a newtype.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Statusbar.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Statusbar.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Statusbar\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/11\/06 20:46:10 $\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-- Report messages of minor importance to the user\n--\nmodule Graphics.UI.Gtk.Display.Statusbar (\n-- * Detail\n-- \n-- | A 'Statusbar' is usually placed along the bottom of an application's main\n-- 'Window'. It may provide a regular commentary of the application's status\n-- (as is usually the case in a web browser, for example), or may be used to\n-- simply output a message when the status changes, (when an upload is complete\n-- in an FTP client, for example). It may also have a resize grip (a triangular\n-- area in the lower right corner) which can be clicked on to resize the window\n-- containing the statusbar.\n--\n-- Status bars in Gtk+ maintain a stack of messages. The message at the top\n-- of the each bar's stack is the one that will currently be displayed.\n--\n-- Any messages added to a statusbar's stack must specify a \/context_id\/\n-- that is used to uniquely identify the source of a message. This context_id\n-- can be generated by 'statusbarGetContextId', given a message and the\n-- statusbar that it will be added to. Note that messages are stored in a\n-- stack, and when choosing which message to display, the stack structure is\n-- adhered to, regardless of the context identifier of a message.\n--\n-- Status bars are created using 'statusbarNew'.\n--\n-- Messages are added to the bar's stack with 'statusbarPush'.\n--\n-- The message at the top of the stack can be removed using 'statusbarPop'.\n-- A message can be removed from anywhere in the stack if its message_id was\n-- recorded at the time it was added. This is done using 'statusbarRemove'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Box'\n-- | +----'HBox'\n-- | +----Statusbar\n-- @\n\n-- * Types\n Statusbar,\n StatusbarClass,\n castToStatusbar,\n toStatusbar,\n ContextId,\n MessageId,\n\n-- * Constructors\n statusbarNew,\n\n-- * Methods\n statusbarGetContextId,\n statusbarPush,\n statusbarPop,\n statusbarRemove,\n statusbarSetHasResizeGrip,\n statusbarGetHasResizeGrip,\n\n-- * Attributes\n statusbarHasResizeGrip,\n\n-- * Signals\n onTextPopped,\n afterTextPopped,\n onTextPushed,\n afterTextPushed,\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\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-- Constructors\n\n-- | Creates a new 'Statusbar' ready for messages.\n--\nstatusbarNew :: IO Statusbar\nstatusbarNew =\n makeNewObject mkStatusbar $\n liftM (castPtr :: Ptr Widget -> Ptr Statusbar) $\n {# call unsafe statusbar_new #}\n\n--------------------\n-- Methods\n\ntype ContextId = {#type guint#}\n\n-- | Returns a new context identifier, given a description of the actual\n-- context. This id can be used to later remove entries form the Statusbar.\n--\nstatusbarGetContextId :: StatusbarClass self => self\n -> String -- ^ @contextDescription@ - textual description of what context the\n -- new message is being used in.\n -> IO ContextId -- ^ returns an id that can be used to later remove entries\n -- ^ from the Statusbar.\nstatusbarGetContextId self contextDescription =\n withUTFString contextDescription $ \\contextDescriptionPtr ->\n {# call unsafe statusbar_get_context_id #}\n (toStatusbar self)\n contextDescriptionPtr\n\nnewtype MessageId = MessageId {#type guint#}\n\n-- | Pushes a new message onto the Statusbar's stack. It will\n-- be displayed as long as it is on top of the stack.\n--\nstatusbarPush :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the message's context id, as returned by\n -- 'statusbarGetContextId'.\n -> String -- ^ @text@ - the message to add to the statusbar.\n -> IO MessageId -- ^ returns the message's new message id for use with\n -- 'statusbarRemove'.\nstatusbarPush self contextId text =\n liftM MessageId $\n withUTFString text $ \\textPtr ->\n {# call statusbar_push #}\n (toStatusbar self)\n contextId\n textPtr\n\n-- | Removes the topmost message that has the correct context.\n--\nstatusbarPop :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the context identifier used when the\n -- message was added.\n -> IO ()\nstatusbarPop self contextId =\n {# call statusbar_pop #}\n (toStatusbar self)\n contextId\n\n-- | Forces the removal of a message from a statusbar's stack. The exact\n-- @contextId@ and @messageId@ must be specified.\n--\nstatusbarRemove :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - a context identifier.\n -> MessageId -- ^ @messageId@ - a message identifier, as returned by\n -- 'statusbarPush'.\n -> IO ()\nstatusbarRemove self contextId (MessageId messageId) =\n {# call statusbar_remove #}\n (toStatusbar self)\n contextId\n messageId\n\n-- | Sets whether the statusbar has a resize grip. @True@ by default.\n--\nstatusbarSetHasResizeGrip :: StatusbarClass self => self -> Bool -> IO ()\nstatusbarSetHasResizeGrip self setting =\n {# call statusbar_set_has_resize_grip #}\n (toStatusbar self)\n (fromBool setting)\n\n-- | Returns whether the statusbar has a resize grip.\n--\nstatusbarGetHasResizeGrip :: StatusbarClass self => self -> IO Bool\nstatusbarGetHasResizeGrip self =\n liftM toBool $\n {# call unsafe statusbar_get_has_resize_grip #}\n (toStatusbar self)\n\n--------------------\n-- Attributes\n\n-- | Whether the statusbar has a grip for resizing the toplevel window.\n--\n-- Default value: @True@\n--\nstatusbarHasResizeGrip :: StatusbarClass self => Attr self Bool\nstatusbarHasResizeGrip = newAttr\n statusbarGetHasResizeGrip\n statusbarSetHasResizeGrip\n\n--------------------\n-- Signals\n\n-- | Called if a message is removed.\n--\nonTextPopped, afterTextPopped :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" False self (user . fromIntegral)\nafterTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" True self (user . fromIntegral)\n\n-- | Called if a message is pushed on top of the\n-- stack.\n--\nonTextPushed, afterTextPushed :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" False self (user . fromIntegral)\nafterTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" True self (user . fromIntegral)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Statusbar\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/11\/06 20:46:10 $\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-- Report messages of minor importance to the user\n--\nmodule Graphics.UI.Gtk.Display.Statusbar (\n-- * Detail\n-- \n-- | A 'Statusbar' is usually placed along the bottom of an application's main\n-- 'Window'. It may provide a regular commentary of the application's status\n-- (as is usually the case in a web browser, for example), or may be used to\n-- simply output a message when the status changes, (when an upload is complete\n-- in an FTP client, for example). It may also have a resize grip (a triangular\n-- area in the lower right corner) which can be clicked on to resize the window\n-- containing the statusbar.\n--\n-- Status bars in Gtk+ maintain a stack of messages. The message at the top\n-- of the each bar's stack is the one that will currently be displayed.\n--\n-- Any messages added to a statusbar's stack must specify a \/context_id\/\n-- that is used to uniquely identify the source of a message. This context_id\n-- can be generated by 'statusbarGetContextId', given a message and the\n-- statusbar that it will be added to. Note that messages are stored in a\n-- stack, and when choosing which message to display, the stack structure is\n-- adhered to, regardless of the context identifier of a message.\n--\n-- Status bars are created using 'statusbarNew'.\n--\n-- Messages are added to the bar's stack with 'statusbarPush'.\n--\n-- The message at the top of the stack can be removed using 'statusbarPop'.\n-- A message can be removed from anywhere in the stack if its message_id was\n-- recorded at the time it was added. This is done using 'statusbarRemove'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Box'\n-- | +----'HBox'\n-- | +----Statusbar\n-- @\n\n-- * Types\n Statusbar,\n StatusbarClass,\n castToStatusbar,\n toStatusbar,\n ContextId,\n MessageId,\n\n-- * Constructors\n statusbarNew,\n\n-- * Methods\n statusbarGetContextId,\n statusbarPush,\n statusbarPop,\n statusbarRemove,\n statusbarSetHasResizeGrip,\n statusbarGetHasResizeGrip,\n\n-- * Attributes\n statusbarHasResizeGrip,\n\n-- * Signals\n onTextPopped,\n afterTextPopped,\n onTextPushed,\n afterTextPushed,\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\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-- Constructors\n\n-- | Creates a new 'Statusbar' ready for messages.\n--\nstatusbarNew :: IO Statusbar\nstatusbarNew =\n makeNewObject mkStatusbar $\n liftM (castPtr :: Ptr Widget -> Ptr Statusbar) $\n {# call unsafe statusbar_new #}\n\n--------------------\n-- Methods\n\ntype ContextId = {#type guint#}\n\n-- | Returns a new context identifier, given a description of the actual\n-- context. This id can be used to later remove entries form the Statusbar.\n--\nstatusbarGetContextId :: StatusbarClass self => self\n -> String -- ^ @contextDescription@ - textual description of what context the\n -- new message is being used in.\n -> IO ContextId -- ^ returns an id that can be used to later remove entries\n -- ^ from the Statusbar.\nstatusbarGetContextId self contextDescription =\n withUTFString contextDescription $ \\contextDescriptionPtr ->\n {# call unsafe statusbar_get_context_id #}\n (toStatusbar self)\n contextDescriptionPtr\n\ntype MessageId = {#type guint#}\n\n-- | Pushes a new message onto the Statusbar's stack. It will\n-- be displayed as long as it is on top of the stack.\n--\nstatusbarPush :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the message's context id, as returned by\n -- 'statusbarGetContextId'.\n -> String -- ^ @text@ - the message to add to the statusbar.\n -> IO MessageId -- ^ returns the message's new message id for use with\n -- 'statusbarRemove'.\nstatusbarPush self contextId text =\n withUTFString text $ \\textPtr ->\n {# call statusbar_push #}\n (toStatusbar self)\n contextId\n textPtr\n\n-- | Removes the topmost message that has the correct context.\n--\nstatusbarPop :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - the context identifier used when the\n -- message was added.\n -> IO ()\nstatusbarPop self contextId =\n {# call statusbar_pop #}\n (toStatusbar self)\n contextId\n\n-- | Forces the removal of a message from a statusbar's stack. The exact\n-- @contextId@ and @messageId@ must be specified.\n--\nstatusbarRemove :: StatusbarClass self => self\n -> ContextId -- ^ @contextId@ - a context identifier.\n -> MessageId -- ^ @messageId@ - a message identifier, as returned by\n -- 'statusbarPush'.\n -> IO ()\nstatusbarRemove self contextId messageId =\n {# call statusbar_remove #}\n (toStatusbar self)\n contextId\n messageId\n\n-- | Sets whether the statusbar has a resize grip. @True@ by default.\n--\nstatusbarSetHasResizeGrip :: StatusbarClass self => self -> Bool -> IO ()\nstatusbarSetHasResizeGrip self setting =\n {# call statusbar_set_has_resize_grip #}\n (toStatusbar self)\n (fromBool setting)\n\n-- | Returns whether the statusbar has a resize grip.\n--\nstatusbarGetHasResizeGrip :: StatusbarClass self => self -> IO Bool\nstatusbarGetHasResizeGrip self =\n liftM toBool $\n {# call unsafe statusbar_get_has_resize_grip #}\n (toStatusbar self)\n\n--------------------\n-- Attributes\n\n-- | Whether the statusbar has a grip for resizing the toplevel window.\n--\n-- Default value: @True@\n--\nstatusbarHasResizeGrip :: StatusbarClass self => Attr self Bool\nstatusbarHasResizeGrip = newAttr\n statusbarGetHasResizeGrip\n statusbarSetHasResizeGrip\n\n--------------------\n-- Signals\n\n-- | Called if a message is removed.\n--\nonTextPopped, afterTextPopped :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" False self (user . fromIntegral)\nafterTextPopped self user = connect_WORD_STRING__NONE \"text-popped\" True self (user . fromIntegral)\n\n-- | Called if a message is pushed on top of the\n-- stack.\n--\nonTextPushed, afterTextPushed :: StatusbarClass self => self\n -> (ContextId -> String -> IO ())\n -> IO (ConnectId self)\nonTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" False self (user . fromIntegral)\nafterTextPushed self user = connect_WORD_STRING__NONE \"text-pushed\" True self (user . fromIntegral)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"50d60c96b4f8ad8b883bb7f17f29f8c68b3a0322","subject":"Added bcast","message":"Added bcast\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Bindings\/MPI\/Internal.chs","new_file":"src\/Bindings\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n ( init, finalize, send, recv, commRank, probe, commSize,\n iSend, iRecv, bcast\n ) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Applicative ((<$>))\nimport Bindings.MPI.Comm (Comm)\nimport Bindings.MPI.Request (Request)\nimport Bindings.MPI.Status (Status, StatusPtr)\nimport Bindings.MPI.MarshalUtils (enumToCInt)\nimport Bindings.MPI.ErrorClasses (ErrorClass)\nimport Bindings.MPI.MarshalUtils (enumFromCInt)\nimport Bindings.MPI.Utils (checkError)\n\n{# context prefix = \"MPI\" #}\n\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #}\ncommRank = {# call unsafe Comm_rank as commRank_ #}\nprobe = {# call Probe as probe_ #}\nsend = {# call unsafe Send as send_ #}\nrecv = {# call unsafe Recv as recv_ #}\niSend = {# call unsafe Isend as iSend_ #}\niRecv = {# call Irecv as iRecv_ #}\nbcast = {# call Bcast as bcast_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n ( init, finalize, send, recv, commRank, probe, commSize,\n iSend, iRecv \n ) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Applicative ((<$>))\nimport Bindings.MPI.Comm (Comm)\nimport Bindings.MPI.Request (Request)\nimport Bindings.MPI.Status (Status, StatusPtr)\nimport Bindings.MPI.MarshalUtils (enumToCInt)\nimport Bindings.MPI.ErrorClasses (ErrorClass)\nimport Bindings.MPI.MarshalUtils (enumFromCInt)\nimport Bindings.MPI.Utils (checkError)\n\n{# context prefix = \"MPI\" #}\n\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #}\ncommRank = {# call unsafe Comm_rank as commRank_ #}\nprobe = {# call Probe as probe_ #}\nsend = {# call unsafe Send as send_ #}\nrecv = {# call unsafe Recv as recv_ #}\niSend = {# call unsafe Isend as iSend_ #}\niRecv = {# call Irecv as iRecv_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f738590c97a6d339339ca12abcc819758e7b562b","subject":"Implement annotTextGetIsOpen and annotTextSetIsOpen","message":"Implement annotTextGetIsOpen and annotTextSetIsOpen\n","repos":"YoEight\/poppler_bak","old_file":"Graphics\/UI\/Gtk\/Poppler\/Annotation.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Annotation.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\nmodule Graphics.UI.Gtk.Poppler.Annotation (\n Annot,\n AnnotClass,\n AnnotType (..),\n AnnotFlag (..),\n AnnotMarkup,\n AnnotMarkupClass,\n annotGetAnnotType,\n annotGetAnnotFlags,\n annotSetAnnotFlags,\n annotGetName,\n annotGetPageIndex,\n annotGetColor,\n annotSetColor,\n annotGetContents,\n annotSetContents,\n annotGetModified,\n annotMarkupGetLabel,\n annotMarkupSetLabel,\n annotMarkupGetSubject,\n annotMarkupGetOpacity,\n annotMarkupSetOpacity,\n annotMarkupHasPopup,\n annotMarkupSetPopup,\n annotMarkupGetPopupIsOpen,\n annotMarkupSetPopupIsOpen,\n annotTextNew,\n annotTextGetIsOpen,\n annotTextSetIsOpen\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\nannotGetAnnotType :: AnnotClass annot => annot -> IO AnnotType\nannotGetAnnotType annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_annot_type #} (toAnnot annot)\n\nannotGetAnnotFlags :: AnnotClass annot => annot -> IO AnnotFlag\nannotGetAnnotFlags annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_flags #} (toAnnot annot)\n\nannotSetAnnotFlags :: AnnotClass annot => annot -> AnnotFlag -> IO ()\nannotSetAnnotFlags annot flag =\n {# call poppler_annot_set_flags #}\n (toAnnot annot)\n (fromIntegral $ fromEnum flag)\n\nannotGetName :: AnnotClass annot => annot -> IO String\nannotGetName annot =\n {# call poppler_annot_get_name #} (toAnnot annot) >>= peekUTFString\n\nannotGetPageIndex :: AnnotClass annot => annot -> IO Int\nannotGetPageIndex annot =\n liftM fromIntegral $\n {# call poppler_annot_get_page_index #} (toAnnot annot)\n\nannotGetColor :: AnnotClass annot => annot -> IO PopplerColor\nannotGetColor annot =\n (peekPopplerColor . castPtr) =<<\n {# call poppler_annot_get_color #} (toAnnot annot)\n\nannotSetColor :: AnnotClass annot => annot -> PopplerColor -> IO ()\nannotSetColor annot color =\n with color $ \\colorPtr ->\n {# call poppler_annot_set_color #} (toAnnot annot) (castPtr colorPtr)\n\nannotGetContents :: AnnotClass annot => annot -> IO String\nannotGetContents annot =\n {# call poppler_annot_get_contents #} (toAnnot annot) >>= peekUTFString\n\nannotSetContents :: AnnotClass annot => annot -> String -> IO ()\nannotSetContents annot content =\n withUTFString content $ \\contentPtr ->\n {# call poppler_annot_set_contents #} (toAnnot annot) contentPtr\n\nannotGetModified :: AnnotClass annot => annot -> IO String\nannotGetModified annot =\n {# call poppler_annot_get_modified #} (toAnnot annot) >>= peekUTFString\n\nannotMarkupGetLabel :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetLabel mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_label #} (toAnnotMarkup mark)\n\nannotMarkupSetLabel :: AnnotMarkupClass mark => mark -> String -> IO ()\nannotMarkupSetLabel mark label =\n withUTFString label $ \\labelPtr ->\n {# call poppler_annot_markup_set_label #}\n (toAnnotMarkup mark)\n (castPtr labelPtr)\n\nannotMarkupGetSubject :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetSubject mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_subject #} (toAnnotMarkup mark)\n\nannotMarkupGetOpacity :: AnnotMarkupClass mark => mark -> IO Double\nannotMarkupGetOpacity mark =\n liftM realToFrac $\n {# call poppler_annot_markup_get_opacity #} (toAnnotMarkup mark)\n\nannotMarkupSetOpacity :: AnnotMarkupClass mark => mark -> Double -> IO ()\nannotMarkupSetOpacity mark opacity =\n {# call poppler_annot_markup_set_opacity #}\n (toAnnotMarkup mark)\n (realToFrac opacity)\n\nannotMarkupHasPopup :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupHasPopup mark =\n liftM toBool $\n {# call poppler_annot_markup_has_popup #} (toAnnotMarkup mark)\n\nannotMarkupSetPopup :: AnnotMarkupClass mark\n => mark\n -> PopplerRectangle\n -> IO ()\nannotMarkupSetPopup mark rect =\n with rect $ \\rectPtr ->\n {# call poppler_annot_markup_set_popup #} (toAnnotMarkup mark) (castPtr rectPtr)\n\nannotMarkupGetPopupIsOpen :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupGetPopupIsOpen mark =\n liftM toBool $\n {# call poppler_annot_markup_get_popup_is_open #} (toAnnotMarkup mark)\n\nannotMarkupSetPopupIsOpen :: AnnotMarkupClass mark => mark -> Bool -> IO ()\nannotMarkupSetPopupIsOpen mark bool =\n {# call poppler_annot_markup_set_popup_is_open #}\n (toAnnotMarkup mark)\n (fromBool bool)\n\nannotTextNew :: DocumentClass doc => doc -> PopplerRectangle -> IO Annot\nannotTextNew doc selection =\n wrapNewGObject mkAnnot $\n with selection $ \\selectionPtr ->\n {# call poppler_annot_text_new #} (toDocument doc) (castPtr selectionPtr)\n\nannotTextGetIsOpen :: AnnotClass annot => annot -> IO Bool\nannotTextGetIsOpen annot =\n liftM toBool $\n withForeignPtr (unAnnot (toAnnot annot)) $ \\annotPtr ->\n {# call poppler_annot_text_get_is_open #} (castPtr annotPtr)\n\nannotTextSetIsOpen :: AnnotClass annot => annot -> Bool -> IO ()\nannotTextSetIsOpen annot bool =\n withForeignPtr (unAnnot (toAnnot annot)) $ \\annotPtr ->\n {# call poppler_annot_text_set_is_open #}\n (castPtr annotPtr)\n (fromBool bool)\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\nmodule Graphics.UI.Gtk.Poppler.Annotation (\n Annot,\n AnnotClass,\n AnnotType (..),\n AnnotFlag (..),\n AnnotMarkup,\n AnnotMarkupClass,\n annotGetAnnotType,\n annotGetAnnotFlags,\n annotSetAnnotFlags,\n annotGetName,\n annotGetPageIndex,\n annotGetColor,\n annotSetColor,\n annotGetContents,\n annotSetContents,\n annotGetModified,\n annotMarkupGetLabel,\n annotMarkupSetLabel,\n annotMarkupGetSubject,\n annotMarkupGetOpacity,\n annotMarkupSetOpacity,\n annotMarkupHasPopup,\n annotMarkupSetPopup,\n annotMarkupGetPopupIsOpen,\n annotMarkupSetPopupIsOpen,\n annotTextNew\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\nannotGetAnnotType :: AnnotClass annot => annot -> IO AnnotType\nannotGetAnnotType annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_annot_type #} (toAnnot annot)\n\nannotGetAnnotFlags :: AnnotClass annot => annot -> IO AnnotFlag\nannotGetAnnotFlags annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_flags #} (toAnnot annot)\n\nannotSetAnnotFlags :: AnnotClass annot => annot -> AnnotFlag -> IO ()\nannotSetAnnotFlags annot flag =\n {# call poppler_annot_set_flags #}\n (toAnnot annot)\n (fromIntegral $ fromEnum flag)\n\nannotGetName :: AnnotClass annot => annot -> IO String\nannotGetName annot =\n {# call poppler_annot_get_name #} (toAnnot annot) >>= peekUTFString\n\nannotGetPageIndex :: AnnotClass annot => annot -> IO Int\nannotGetPageIndex annot =\n liftM fromIntegral $\n {# call poppler_annot_get_page_index #} (toAnnot annot)\n\nannotGetColor :: AnnotClass annot => annot -> IO PopplerColor\nannotGetColor annot =\n (peekPopplerColor . castPtr) =<<\n {# call poppler_annot_get_color #} (toAnnot annot)\n\nannotSetColor :: AnnotClass annot => annot -> PopplerColor -> IO ()\nannotSetColor annot color =\n with color $ \\colorPtr ->\n {# call poppler_annot_set_color #} (toAnnot annot) (castPtr colorPtr)\n\nannotGetContents :: AnnotClass annot => annot -> IO String\nannotGetContents annot =\n {# call poppler_annot_get_contents #} (toAnnot annot) >>= peekUTFString\n\nannotSetContents :: AnnotClass annot => annot -> String -> IO ()\nannotSetContents annot content =\n withUTFString content $ \\contentPtr ->\n {# call poppler_annot_set_contents #} (toAnnot annot) contentPtr\n\nannotGetModified :: AnnotClass annot => annot -> IO String\nannotGetModified annot =\n {# call poppler_annot_get_modified #} (toAnnot annot) >>= peekUTFString\n\nannotMarkupGetLabel :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetLabel mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_label #} (toAnnotMarkup mark)\n\nannotMarkupSetLabel :: AnnotMarkupClass mark => mark -> String -> IO ()\nannotMarkupSetLabel mark label =\n withUTFString label $ \\labelPtr ->\n {# call poppler_annot_markup_set_label #}\n (toAnnotMarkup mark)\n (castPtr labelPtr)\n\nannotMarkupGetSubject :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetSubject mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_subject #} (toAnnotMarkup mark)\n\nannotMarkupGetOpacity :: AnnotMarkupClass mark => mark -> IO Double\nannotMarkupGetOpacity mark =\n liftM realToFrac $\n {# call poppler_annot_markup_get_opacity #} (toAnnotMarkup mark)\n\nannotMarkupSetOpacity :: AnnotMarkupClass mark => mark -> Double -> IO ()\nannotMarkupSetOpacity mark opacity =\n {# call poppler_annot_markup_set_opacity #}\n (toAnnotMarkup mark)\n (realToFrac opacity)\n\nannotMarkupHasPopup :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupHasPopup mark =\n liftM toBool $\n {# call poppler_annot_markup_has_popup #} (toAnnotMarkup mark)\n\nannotMarkupSetPopup :: AnnotMarkupClass mark\n => mark\n -> PopplerRectangle\n -> IO ()\nannotMarkupSetPopup mark rect =\n with rect $ \\rectPtr ->\n {# call poppler_annot_markup_set_popup #} (toAnnotMarkup mark) (castPtr rectPtr)\n\nannotMarkupGetPopupIsOpen :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupGetPopupIsOpen mark =\n liftM toBool $\n {# call poppler_annot_markup_get_popup_is_open #} (toAnnotMarkup mark)\n\nannotMarkupSetPopupIsOpen :: AnnotMarkupClass mark => mark -> Bool -> IO ()\nannotMarkupSetPopupIsOpen mark bool =\n {# call poppler_annot_markup_set_popup_is_open #}\n (toAnnotMarkup mark)\n (fromBool bool)\n\nannotTextNew :: DocumentClass doc => doc -> PopplerRectangle -> IO Annot\nannotTextNew doc selection =\n wrapNewGObject mkAnnot $\n with selection $ \\selectionPtr ->\n {# call poppler_annot_text_new #} (toDocument doc) (castPtr selectionPtr)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0caec1a27646dea72de62ca08d3145edbc477275","subject":"GHC 7.6 compatibility","message":"GHC 7.6 compatibility\n","repos":"gtk2hs\/gstreamer","old_file":"Media\/Streaming\/GStreamer\/Core\/Iterator.chs","new_file":"Media\/Streaming\/GStreamer\/Core\/Iterator.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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult(..),\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> Ptr GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult(..),\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"30b160f3102039f74a67d913e6e3210a57e16db6","subject":"Fix getKeyList exception on empty list","message":"Fix getKeyList exception on empty list\n","repos":"reinerp\/CoreFoundation","old_file":"CoreFoundation\/Preferences.chs","new_file":"CoreFoundation\/Preferences.chs","new_contents":"{- |\nCore Foundation provides a simple, standard way to manage user (and application) preferences. Core Foundation stores preferences as key-value pairs that are assigned a scope using a combination of user name, application ID, and host (computer) names. This makes it possible to save and retrieve preferences that apply to different classes of users. Core Foundation preferences is useful to all applications that support user preferences. Note that modification of some preferences domains (those not belonging to the \\\"Current User\\\") requires root privileges (or Admin privileges prior to Mac OS X v10.6)-see Authorization Services Programming Guide ()\nfor information on how to gain suitable privileges.\n-}\nmodule CoreFoundation.Preferences(\n -- * Types\n Key,\n SuiteID,\n AppID,\n anyApp,\n currentApp,\n HostID,\n anyHost,\n currentHost,\n UserID,\n anyUser,\n currentUser,\n -- * Getting\n getAppValue,\n getKeyList,\n getMultiple,\n getValue,\n -- * Setting\n setAppValue,\n setMultiple,\n setValue,\n -- * Synchronizing\n SyncFailed(..),\n appSync,\n sync,\n -- * Suite preferences\n addSuiteToApp,\n removeSuiteFromApp,\n -- * Misc\n appValueIsForced,\n getAppList,\n ) where\n\nimport Prelude hiding(String)\n\nimport CoreFoundation.Base\nimport CoreFoundation.String\nimport CoreFoundation.Array\nimport CoreFoundation.Dictionary\nimport CoreFoundation.PropertyList\n#include \n#include \"cbits.h\"\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Data.Typeable\nimport qualified Data.Vector as V\nimport Data.Maybe(fromMaybe)\nimport Foreign\nimport Foreign.C.Types\n\n{#pointer CFStringRef -> CFString#}\n{#pointer CFArrayRef -> CFArray#}\n{#pointer CFDictionaryRef -> CFDictionary#}\n{#pointer CFPropertyListRef -> CFPropertyList#}\n\n-- | Keys. These can be constructed using the OverloadedStrings\n-- language extension.\ntype Key = String\n\n-- | ID of a suite, for example @com.apple.iApps@.\ntype SuiteID = String\n\n-- | Application ID. Takes the form of a java package name, @com.foosoft@, or one of the constants 'anyApp', 'currentApp'.\ntype AppID = String\n\n-- | Matches any application. This may be passed to functions which \\\"search\\\", such as 'getAppValue', 'getValue', 'getKeyList', etc. However, this may not be passed to functions which put a value in a specific location, such as 'setAppValue', 'syncApp'.\nanyApp :: AppID\nanyApp = constant {#call pure unsafe hsAnyApp#}\n\n-- | Specifies the current application\ncurrentApp :: AppID\ncurrentApp = constant {#call pure unsafe hsCurrentApp#}\n\n-- | Host ID. User-provided, or see the constants 'anyHost', 'currentHost'\ntype HostID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any host. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all hosts.\nanyHost :: HostID\nanyHost = constant {#call pure unsafe hsAnyHost#}\n\n-- | Current host\ncurrentHost :: HostID\ncurrentHost = constant {#call pure unsafe hsCurrentHost#}\n\n-- | User ID. User-provided, or see the constants 'anyUser',\n -- 'currentUser'\ntype UserID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any user. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all users.\nanyUser :: UserID\nanyUser = constant {#call pure unsafe hsAnyUser#}\n\n-- | Current user\ncurrentUser :: UserID\ncurrentUser = constant {#call pure unsafe hsCurrentUser#}\n\n------------------------- Getting ----------------------------\n{- |\nObtains a preference value for the specified key and application. Wraps CFPreferencesCopyAppValue.\n-}\ngetAppValue :: Key -> AppID -> IO (Maybe Plist)\ngetAppValue = call2 createNullable {#call unsafe CFPreferencesCopyAppValue as ^#}\n\n{- |\nConstructs and returns the list of all keys set in the specified domain. Wraps CFPreferencesCopyKeyList\n-}\ngetKeyList :: AppID -> UserID -> HostID -> IO (Array Key)\ngetKeyList = \n call3 \n (fmap (fromMaybe (fromHs V.empty)) . createNullable)\n {#call unsafe CFPreferencesCopyKeyList as ^ #}\n\n{- |\nReturns a dictionary containing preference values for multiple keys. If no values were located, returns an empty dictionary. \n-}\ngetMultiple :: Array Key -> AppID -> UserID -> HostID -> IO (Dictionary Key Plist)\ngetMultiple = call4 create {#call unsafe CFPreferencesCopyMultiple as ^ #}\n\n{- |\nReturns a preference value for a given domain.\n\nThis function is the primitive get mechanism for the higher level preference function 'getAppValue'. Unlike the high-level function, 'getValue' searches only the exact domain specified. Do not use this function directly unless you have a need. Do not use arbitrary user and host names, instead pass the pre-defined domain qualifier constants (i.e. 'currentUser', 'anyUser', 'currentHost', 'anyHost').\n-}\ngetValue :: Key -> AppID -> UserID -> HostID -> IO (Maybe Plist)\ngetValue = call4 createNullable {#call unsafe CFPreferencesCopyValue as ^ #}\n\n-------------------------- Setting ---------------------------\n{- |\nAdds, modifies, or removes a preference.\n\nNew preference values are stored in the standard application preference location, <~\/Library\/Preferences\/>. When called with 'currentApp', modifications are performed in the preference domain \\\"Current User, Current Application, Any Host.\\\" If you need to create preferences in some other domain, use the low-level function 'setValue'.\n\nYou must call the 'appSync' function in order for your changes to be saved to permanent storage.\n\nWraps @CFPreferencesSetAppValue@.\n-}\nsetAppValue :: Key -> Maybe Plist -> AppID -> IO ()\nsetAppValue key val app =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n {#call unsafe CFPreferencesSetAppValue as ^ #} k v a\n\n{- |\nConvenience function that allows you to set and remove multiple preference values.\n\nBehavior is undefined if a key is in both keysToSet and keysToRemove.\n\nWraps @CFPreferencesSetMultiple@.\n-}\nsetMultiple :: \n Dictionary Key Plist -- ^ values to set\n -> Array Key -- ^ keys to remove \n -> AppID \n -> UserID \n -> HostID \n -> IO ()\nsetMultiple = call5 idScheme {#call unsafe CFPreferencesSetMultiple as ^ #}\n\n{- |\nAdds, modifies, or removes a preference value for the specified domain.\n\nThis function is the primitive set mechanism for the higher level preference function 'setAppValue'. Only the exact domain specified is modified. Do not use this function directly unless you have a specific need. Do not use arbitrary user and host names, instead pass the pre-defined constants.\n\nYou must call the 'sync' function in order for your changes to be saved to permanent storage. Note that you can only save preferences for \\\"Any User\\\" if you have root privileges (or Admin privileges prior to Mac OS X v10.6).\n-}\nsetValue :: Key -> Maybe Plist -> AppID -> UserID -> HostID -> IO ()\nsetValue key val app user host =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n withObject user $ \\u ->\n withObject host $ \\h ->\n {#call unsafe CFPreferencesSetValue as ^ #} k v a u h\n\n------------------------- Synchronizing ---------------\n-- | Exception thrown when 'appSync' or 'sync' fail.\ndata SyncFailed = SyncFailed\n deriving(Typeable)\ninstance Show SyncFailed where\n show _ = \"Syncing Apple preferences failed\"\ninstance Exception SyncFailed\n\n{- |\nWrites to permanent storage all pending changes to the preference data for the application, and reads the latest preference data from permanent storage.\n\nCalling the function 'setAppValue' is not in itself sufficient for storing preferences. The 'appSync' function writes to permanent storage all pending preference changes for the application. Typically you would call this function after multiple calls to 'setAppValue'. Conversely, preference data is cached after it is first read. Changes made externally are not automatically incorporated. The 'appSync' function reads the latest preferences from permanent storage.\n\nThrows 'SyncFailed' if synchronization failed.\n-}\nappSync :: AppID -> IO ()\nappSync = call1 (checkError SyncFailed) {#call unsafe CFPreferencesAppSynchronize as ^ #}\n\n{- |\nFor the specified domain, writes all pending changes to preference data to permanent storage, and reads latest preference data from permanent storage.\n\nThis function is the primitive synchronize mechanism for the higher level preference function 'appSync'; it writes updated preferences to permanent storage, and reads the latest preferences from permanent storage. Only the exact domain specified is modified. Note that to modify \\\"Any User\\\" preferences requires root privileges (or Admin privileges prior to Mac OS X v10.6) - see \n-}\nsync :: AppID -> UserID -> HostID -> IO ()\nsync = call3 (checkError SyncFailed) {#call unsafe CFPreferencesSynchronize as ^ #}\n\n---------------------- Suite preferences -----------\n{- |\nAdds suite preferences to an application\u2019s preference search chain.\n\nSuite preferences allow you to maintain a set of preferences that are common to all applications in the suite. When a suite is added to an application\u2019s search chain, all of the domains pertaining to that suite are inserted into the chain. Suite preferences are added between the \\\"Current Application\\\" domains and the \\\"Any Application\\\" domains. If you add multiple suite preferences to one application, the order of the suites in the search chain is non-deterministic. You can override a suite preference for a given application by defining the same preference key in the application specific preferences.\n\nWraps @CFPreferencesAddSuitePreferencesToApp@.\n-}\naddSuiteToApp :: AppID -> SuiteID -> IO ()\naddSuiteToApp = call2 idScheme {#call unsafe CFPreferencesAddSuitePreferencesToApp as ^ #}\n\n{- |\nRemoves suite preferences from an application\u2019s search chain.\n-}\nremoveSuiteFromApp :: AppID -> SuiteID -> IO ()\nremoveSuiteFromApp = call2 idScheme {#call unsafe CFPreferencesRemoveSuitePreferencesFromApp as ^ #}\n\n----------------------- Misc ------------------\n{- |\nDetermines whether or not a given key has been imposed on the user.\n\nIn cases where machines and\/or users are under some kind of management, you should use this function to determine whether or not to disable UI elements corresponding to those preference keys.\n-}\nappValueIsForced :: Key -> AppID -> IO Bool\nappValueIsForced = call2 (Foreign.toBool <$>) {#call unsafe CFPreferencesAppValueIsForced as ^ #}\n\n{- |\nConstructs and returns the list of all applications that have preferences in the scope of the specified user and host.\n-}\ngetAppList :: UserID -> HostID -> IO (Array AppID)\ngetAppList = call2 create {#call unsafe CFPreferencesCopyApplicationList as ^ #}\n\n\n-- marshalling utils\ncheckError exception gen = do\n res <- gen\n when (res == 0) $ throw exception\n\nwithMaybe Nothing f = f nullPtr\nwithMaybe (Just o) f = withObject o f\n\ncall1 scheme f = \\arg1 ->\n withObject arg1 $ \\parg1 ->\n scheme $\n f parg1\n\ncall2 scheme f = \\arg1 arg2 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n scheme $\n f parg1 parg2\n\ncall3 scheme f = \\arg1 arg2 arg3 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n scheme $\n f parg1 parg2 parg3\n\ncall4 scheme f = \\arg1 arg2 arg3 arg4 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n scheme $\n f parg1 parg2 parg3 parg4\n\ncall5 scheme f = \\arg1 arg2 arg3 arg4 arg5 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n withObject arg5 $ \\parg5 ->\n scheme $\n f parg1 parg2 parg3 parg4 parg5\n\n","old_contents":"{- |\nCore Foundation provides a simple, standard way to manage user (and application) preferences. Core Foundation stores preferences as key-value pairs that are assigned a scope using a combination of user name, application ID, and host (computer) names. This makes it possible to save and retrieve preferences that apply to different classes of users. Core Foundation preferences is useful to all applications that support user preferences. Note that modification of some preferences domains (those not belonging to the \\\"Current User\\\") requires root privileges (or Admin privileges prior to Mac OS X v10.6)-see Authorization Services Programming Guide ()\nfor information on how to gain suitable privileges.\n-}\nmodule CoreFoundation.Preferences(\n -- * Types\n Key,\n SuiteID,\n AppID,\n anyApp,\n currentApp,\n HostID,\n anyHost,\n currentHost,\n UserID,\n anyUser,\n currentUser,\n -- * Getting\n getAppValue,\n getKeyList,\n getMultiple,\n getValue,\n -- * Setting\n setAppValue,\n setMultiple,\n setValue,\n -- * Synchronizing\n SyncFailed(..),\n appSync,\n sync,\n -- * Suite preferences\n addSuiteToApp,\n removeSuiteFromApp,\n -- * Misc\n appValueIsForced,\n getAppList,\n ) where\n\nimport Prelude hiding(String)\n\nimport CoreFoundation.Base\nimport CoreFoundation.String\nimport CoreFoundation.Array\nimport CoreFoundation.Dictionary\nimport CoreFoundation.PropertyList\n#include \n#include \"cbits.h\"\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Data.Typeable\nimport Foreign\nimport Foreign.C.Types\n\n{#pointer CFStringRef -> CFString#}\n{#pointer CFArrayRef -> CFArray#}\n{#pointer CFDictionaryRef -> CFDictionary#}\n{#pointer CFPropertyListRef -> CFPropertyList#}\n\n-- | Keys. These can be constructed using the OverloadedStrings\n-- language extension.\ntype Key = String\n\n-- | ID of a suite, for example @com.apple.iApps@.\ntype SuiteID = String\n\n-- | Application ID. Takes the form of a java package name, @com.foosoft@, or one of the constants 'anyApp', 'currentApp'.\ntype AppID = String\n\n-- | Matches any application. This may be passed to functions which \\\"search\\\", such as 'getAppValue', 'getValue', 'getKeyList', etc. However, this may not be passed to functions which put a value in a specific location, such as 'setAppValue', 'syncApp'.\nanyApp :: AppID\nanyApp = constant {#call pure unsafe hsAnyApp#}\n\n-- | Specifies the current application\ncurrentApp :: AppID\ncurrentApp = constant {#call pure unsafe hsCurrentApp#}\n\n-- | Host ID. User-provided, or see the constants 'anyHost', 'currentHost'\ntype HostID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any host. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all hosts.\nanyHost :: HostID\nanyHost = constant {#call pure unsafe hsAnyHost#}\n\n-- | Current host\ncurrentHost :: HostID\ncurrentHost = constant {#call pure unsafe hsCurrentHost#}\n\n-- | User ID. User-provided, or see the constants 'anyUser',\n -- 'currentUser'\ntype UserID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any user. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all users.\nanyUser :: UserID\nanyUser = constant {#call pure unsafe hsAnyUser#}\n\n-- | Current user\ncurrentUser :: UserID\ncurrentUser = constant {#call pure unsafe hsCurrentUser#}\n\n------------------------- Getting ----------------------------\n{- |\nObtains a preference value for the specified key and application. Wraps CFPreferencesCopyAppValue.\n-}\ngetAppValue :: Key -> AppID -> IO (Maybe Plist)\ngetAppValue = call2 createNullable {#call unsafe CFPreferencesCopyAppValue as ^#}\n\n{- |\nConstructs and returns the list of all keys set in the specified domain. Wraps CFPreferencesCopyKeyList\n-}\ngetKeyList :: AppID -> UserID -> HostID -> IO (Array Key)\ngetKeyList = call3 create {#call unsafe CFPreferencesCopyKeyList as ^ #}\n\n{- |\nReturns a dictionary containing preference values for multiple keys. If no values were located, returns an empty dictionary. \n-}\ngetMultiple :: Array Key -> AppID -> UserID -> HostID -> IO (Dictionary Key Plist)\ngetMultiple = call4 create {#call unsafe CFPreferencesCopyMultiple as ^ #}\n\n{- |\nReturns a preference value for a given domain.\n\nThis function is the primitive get mechanism for the higher level preference function 'getAppValue'. Unlike the high-level function, 'getValue' searches only the exact domain specified. Do not use this function directly unless you have a need. Do not use arbitrary user and host names, instead pass the pre-defined domain qualifier constants (i.e. 'currentUser', 'anyUser', 'currentHost', 'anyHost').\n-}\ngetValue :: Key -> AppID -> UserID -> HostID -> IO (Maybe Plist)\ngetValue = call4 createNullable {#call unsafe CFPreferencesCopyValue as ^ #}\n\n-------------------------- Setting ---------------------------\n{- |\nAdds, modifies, or removes a preference.\n\nNew preference values are stored in the standard application preference location, <~\/Library\/Preferences\/>. When called with 'currentApp', modifications are performed in the preference domain \\\"Current User, Current Application, Any Host.\\\" If you need to create preferences in some other domain, use the low-level function 'setValue'.\n\nYou must call the 'appSync' function in order for your changes to be saved to permanent storage.\n\nWraps @CFPreferencesSetAppValue@.\n-}\nsetAppValue :: Key -> Maybe Plist -> AppID -> IO ()\nsetAppValue key val app =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n {#call unsafe CFPreferencesSetAppValue as ^ #} k v a\n\n{- |\nConvenience function that allows you to set and remove multiple preference values.\n\nBehavior is undefined if a key is in both keysToSet and keysToRemove.\n\nWraps @CFPreferencesSetMultiple@.\n-}\nsetMultiple :: \n Dictionary Key Plist -- ^ values to set\n -> Array Key -- ^ keys to remove \n -> AppID \n -> UserID \n -> HostID \n -> IO ()\nsetMultiple = call5 idScheme {#call unsafe CFPreferencesSetMultiple as ^ #}\n\n{- |\nAdds, modifies, or removes a preference value for the specified domain.\n\nThis function is the primitive set mechanism for the higher level preference function 'setAppValue'. Only the exact domain specified is modified. Do not use this function directly unless you have a specific need. Do not use arbitrary user and host names, instead pass the pre-defined constants.\n\nYou must call the 'sync' function in order for your changes to be saved to permanent storage. Note that you can only save preferences for \\\"Any User\\\" if you have root privileges (or Admin privileges prior to Mac OS X v10.6).\n-}\nsetValue :: Key -> Maybe Plist -> AppID -> UserID -> HostID -> IO ()\nsetValue key val app user host =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n withObject user $ \\u ->\n withObject host $ \\h ->\n {#call unsafe CFPreferencesSetValue as ^ #} k v a u h\n\n------------------------- Synchronizing ---------------\n-- | Exception thrown when 'appSync' or 'sync' fail.\ndata SyncFailed = SyncFailed\n deriving(Typeable)\ninstance Show SyncFailed where\n show _ = \"Syncing Apple preferences failed\"\ninstance Exception SyncFailed\n\n{- |\nWrites to permanent storage all pending changes to the preference data for the application, and reads the latest preference data from permanent storage.\n\nCalling the function 'setAppValue' is not in itself sufficient for storing preferences. The 'appSync' function writes to permanent storage all pending preference changes for the application. Typically you would call this function after multiple calls to 'setAppValue'. Conversely, preference data is cached after it is first read. Changes made externally are not automatically incorporated. The 'appSync' function reads the latest preferences from permanent storage.\n\nThrows 'SyncFailed' if synchronization failed.\n-}\nappSync :: AppID -> IO ()\nappSync = call1 (checkError SyncFailed) {#call unsafe CFPreferencesAppSynchronize as ^ #}\n\n{- |\nFor the specified domain, writes all pending changes to preference data to permanent storage, and reads latest preference data from permanent storage.\n\nThis function is the primitive synchronize mechanism for the higher level preference function 'appSync'; it writes updated preferences to permanent storage, and reads the latest preferences from permanent storage. Only the exact domain specified is modified. Note that to modify \\\"Any User\\\" preferences requires root privileges (or Admin privileges prior to Mac OS X v10.6) - see \n-}\nsync :: AppID -> UserID -> HostID -> IO ()\nsync = call3 (checkError SyncFailed) {#call unsafe CFPreferencesSynchronize as ^ #}\n\n---------------------- Suite preferences -----------\n{- |\nAdds suite preferences to an application\u2019s preference search chain.\n\nSuite preferences allow you to maintain a set of preferences that are common to all applications in the suite. When a suite is added to an application\u2019s search chain, all of the domains pertaining to that suite are inserted into the chain. Suite preferences are added between the \\\"Current Application\\\" domains and the \\\"Any Application\\\" domains. If you add multiple suite preferences to one application, the order of the suites in the search chain is non-deterministic. You can override a suite preference for a given application by defining the same preference key in the application specific preferences.\n\nWraps @CFPreferencesAddSuitePreferencesToApp@.\n-}\naddSuiteToApp :: AppID -> SuiteID -> IO ()\naddSuiteToApp = call2 idScheme {#call unsafe CFPreferencesAddSuitePreferencesToApp as ^ #}\n\n{- |\nRemoves suite preferences from an application\u2019s search chain.\n-}\nremoveSuiteFromApp :: AppID -> SuiteID -> IO ()\nremoveSuiteFromApp = call2 idScheme {#call unsafe CFPreferencesRemoveSuitePreferencesFromApp as ^ #}\n\n----------------------- Misc ------------------\n{- |\nDetermines whether or not a given key has been imposed on the user.\n\nIn cases where machines and\/or users are under some kind of management, you should use this function to determine whether or not to disable UI elements corresponding to those preference keys.\n-}\nappValueIsForced :: Key -> AppID -> IO Bool\nappValueIsForced = call2 (Foreign.toBool <$>) {#call unsafe CFPreferencesAppValueIsForced as ^ #}\n\n{- |\nConstructs and returns the list of all applications that have preferences in the scope of the specified user and host.\n-}\ngetAppList :: UserID -> HostID -> IO (Array AppID)\ngetAppList = call2 create {#call unsafe CFPreferencesCopyApplicationList as ^ #}\n\n\n-- marshalling utils\ncheckError exception gen = do\n res <- gen\n when (res == 0) $ throw exception\n\nwithMaybe Nothing f = f nullPtr\nwithMaybe (Just o) f = withObject o f\n\ncall1 scheme f = \\arg1 ->\n withObject arg1 $ \\parg1 ->\n scheme $\n f parg1\n\ncall2 scheme f = \\arg1 arg2 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n scheme $\n f parg1 parg2\n\ncall3 scheme f = \\arg1 arg2 arg3 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n scheme $\n f parg1 parg2 parg3\n\ncall4 scheme f = \\arg1 arg2 arg3 arg4 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n scheme $\n f parg1 parg2 parg3 parg4\n\ncall5 scheme f = \\arg1 arg2 arg3 arg4 arg5 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n withObject arg5 $ \\parg5 ->\n scheme $\n f parg1 parg2 parg3 parg4 parg5\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7797387c9151e7daea2ab18e6251309e99945c00","subject":"Move binding to within #if block","message":"Move binding to within #if block\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Device.chs","new_file":"Foreign\/CUDA\/Driver\/Device.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n#ifdef USE_EMPTY_CASE\n{-# LANGUAGE EmptyCase #-}\n#endif\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device (\n\n -- * Device Management\n Device(..),\n DeviceProperties(..), DeviceAttribute(..), Compute(..), ComputeMode(..), InitFlag,\n initialise, capability, device, attribute, count, name, props, totalMem\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\nimport Control.Applicative\nimport Prelude\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Eq, Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as DeviceAttribute\n { underscoreToCase\n , MAX as CU_DEVICE_ATTRIBUTE_MAX } -- ignore\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n\n#if CUDA_VERSION < 5000\n{# pointer *CUdevprop as ^ foreign -> CUDevProp nocode #}\n\n--\n-- Properties of the compute device (internal helper).\n-- Replaced by cuDeviceGetAttribute in CUDA-5.0 and later.\n--\ndata CUDevProp = CUDevProp\n {\n cuMaxThreadsPerBlock :: !Int, -- Maximum number of threads per block\n cuMaxBlockSize :: !(Int,Int,Int), -- Maximum size of each dimension of a block\n cuMaxGridSize :: !(Int,Int,Int), -- Maximum size of each dimension of a grid\n cuSharedMemPerBlock :: !Int64, -- Shared memory available per block in bytes\n cuTotalConstMem :: !Int64, -- Constant memory available on device in bytes\n cuWarpSize :: !Int, -- Warp size in threads (SIMD width)\n cuMemPitch :: !Int64, -- Maximum pitch in bytes allowed by memory copies\n cuRegsPerBlock :: !Int, -- 32-bit registers available per block\n cuClockRate :: !Int, -- Clock frequency in kilohertz\n cuTextureAlignment :: !Int64 -- Alignment requirement for textures\n }\n deriving (Show)\n\n\ninstance Storable CUDevProp where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"no instance for Foreign.Storable.poke DeviceProperties\"\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n [t1,t2,t3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxThreadsDim#} p\n [g1,g2,g3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxGridSize#} p\n\n return CUDevProp\n {\n cuMaxThreadsPerBlock = tb,\n cuMaxBlockSize = (t1,t2,t3),\n cuMaxGridSize = (g1,g2,g3),\n cuSharedMemPerBlock = sm,\n cuTotalConstMem = cm,\n cuWarpSize = ws,\n cuMemPitch = mp,\n cuRegsPerBlock = rb,\n cuClockRate = cl,\n cuTextureAlignment = ta\n }\n#endif\n\n\n-- |\n-- Possible option flags for CUDA initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata InitFlag\ninstance Enum InitFlag where\n#ifdef USE_EMPTY_CASE\n toEnum x = case x of {}\n fromEnum x = case x of {}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. This must be called before any other\n-- driver function.\n--\n-- \n--\n{-# INLINEABLE initialise #-}\ninitialise :: [InitFlag] -> IO ()\ninitialise !flags = nothingIfOk =<< cuInit flags\n\n{-# INLINE cuInit #-}\n{# fun unsafe cuInit\n { combineBitMasks `[InitFlag]' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\n{-# INLINEABLE capability #-}\ncapability :: Device -> IO Compute\n#if CUDA_VERSION >= 5000\ncapability !dev =\n Compute <$> attribute dev ComputeCapabilityMajor\n <*> attribute dev ComputeCapabilityMinor\n#else\n-- Deprecated as of CUDA-5.0\n--\ncapability !dev =\n (\\(!s,!a,!b) -> resultIfOk (s,Compute a b)) =<< cuDeviceComputeCapability dev\n\n{-# INLINE cuDeviceComputeCapability #-}\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return a handle to the compute device at the given ordinal.\n--\n-- \n--\n{-# INLINEABLE device #-}\ndevice :: Int -> IO Device\ndevice !d = resultIfOk =<< cuDeviceGet d\n\n{-# INLINE cuDeviceGet #-}\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peek\n\n\n-- |\n-- Return the selected attribute for the given device.\n--\n-- \n--\n{-# INLINEABLE attribute #-}\nattribute :: Device -> DeviceAttribute -> IO Int\nattribute !d !a = resultIfOk =<< cuDeviceGetAttribute a d\n\n{-# INLINE cuDeviceGetAttribute #-}\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `DeviceAttribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0.\n--\n-- \n--\n{-# INLINEABLE count #-}\ncount :: IO Int\ncount = resultIfOk =<< cuDeviceGetCount\n\n{-# INLINE cuDeviceGetCount #-}\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- The identifying name of the device.\n--\n-- \n--\n{-# INLINEABLE name #-}\nname :: Device -> IO String\nname !d = resultIfOk =<< cuDeviceGetName d\n\n{-# INLINE cuDeviceGetName #-}\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\n{-# INLINEABLE props #-}\nprops :: Device -> IO DeviceProperties\nprops !d = do\n\n#if CUDA_VERSION < 5000\n -- Old versions of the CUDA API used the separate cuDeviceGetProperties\n -- function to probe some properties, and cuDeviceGetAttribute for\n -- others. As of CUDA-5.0, the former was deprecated and its\n -- functionality subsumed by the latter, which we use below.\n --\n p <- resultIfOk =<< cuDeviceGetProperties d\n let cm = cuTotalConstMem p\n sm = cuSharedMemPerBlock p\n rb = cuRegsPerBlock p\n ws = cuWarpSize p\n tb = cuMaxThreadsPerBlock p\n bs = cuMaxBlockSize p\n gs = cuMaxGridSize p\n cl = cuClockRate p\n mp = cuMemPitch p\n ta = cuTextureAlignment p\n#else\n cm <- fromIntegral <$> attribute d TotalConstantMemory\n sm <- fromIntegral <$> attribute d SharedMemoryPerBlock\n mp <- fromIntegral <$> attribute d MaxPitch\n ta <- fromIntegral <$> attribute d TextureAlignment\n cl <- attribute d ClockRate\n ws <- attribute d WarpSize\n rb <- attribute d RegistersPerBlock\n tb <- attribute d MaxThreadsPerBlock\n bs <- (,,) <$> attribute d MaxBlockDimX\n <*> attribute d MaxBlockDimY\n <*> attribute d MaxBlockDimZ\n gs <- (,,) <$> attribute d MaxGridDimX\n <*> attribute d MaxGridDimY\n <*> attribute d MaxGridDimZ\n#endif\n\n -- The rest of the properties.\n --\n n <- name d\n cc <- capability d\n gm <- totalMem d\n pc <- attribute d MultiprocessorCount\n md <- toEnum `fmap` attribute d ComputeMode\n ov <- toBool `fmap` attribute d GpuOverlap\n ke <- toBool `fmap` attribute d KernelExecTimeout\n tg <- toBool `fmap` attribute d Integrated\n hm <- toBool `fmap` attribute d CanMapHostMemory\n#if CUDA_VERSION >= 3000\n ck <- toBool `fmap` attribute d ConcurrentKernels\n ee <- toBool `fmap` attribute d EccEnabled\n u1 <- attribute d MaximumTexture1dWidth\n u21 <- attribute d MaximumTexture2dWidth\n u22 <- attribute d MaximumTexture2dHeight\n u31 <- attribute d MaximumTexture3dWidth\n u32 <- attribute d MaximumTexture3dHeight\n u33 <- attribute d MaximumTexture3dDepth\n#endif\n#if CUDA_VERSION >= 4000\n ae <- attribute d AsyncEngineCount\n l2 <- attribute d L2CacheSize\n tm <- attribute d MaxThreadsPerMultiprocessor\n mw <- attribute d GlobalMemoryBusWidth\n mc <- attribute d MemoryClockRate\n pb <- attribute d PciBusId\n pd <- attribute d PciDeviceId\n pm <- attribute d PciDomainId\n ua <- toBool `fmap` attribute d UnifiedAddressing\n tcc <- toBool `fmap` attribute d TccDriver\n#endif\n#if CUDA_VERSION >= 5050\n sp <- toBool `fmap` attribute d StreamPrioritiesSupported\n#endif\n#if CUDA_VERSION >= 6000\n gl1 <- toBool `fmap` attribute d GlobalL1CacheSupported\n ll1 <- toBool `fmap` attribute d LocalL1CacheSupported\n mm <- toBool `fmap` attribute d ManagedMemory\n mg <- toBool `fmap` attribute d MultiGpuBoard\n mid <- attribute d MultiGpuBoardGroupId\n#endif\n\n return DeviceProperties\n {\n deviceName = n\n , computeCapability = cc\n , totalGlobalMem = gm\n , totalConstMem = cm\n , sharedMemPerBlock = sm\n , regsPerBlock = rb\n , warpSize = ws\n , maxThreadsPerBlock = tb\n , maxBlockSize = bs\n , maxGridSize = gs\n , clockRate = cl\n , multiProcessorCount = pc\n , memPitch = mp\n , textureAlignment = ta\n , computeMode = md\n , deviceOverlap = ov\n , kernelExecTimeoutEnabled = ke\n , integrated = tg\n , canMapHostMemory = hm\n#if CUDA_VERSION >= 3000\n , concurrentKernels = ck\n , eccEnabled = ee\n , maxTextureDim1D = u1\n , maxTextureDim2D = (u21,u22)\n , maxTextureDim3D = (u31,u32,u33)\n#endif\n#if CUDA_VERSION >= 4000\n , asyncEngineCount = ae\n , cacheMemL2 = l2\n , maxThreadsPerMultiProcessor = tm\n , memBusWidth = mw\n , memClockRate = mc\n , pciInfo = PCI pb pd pm\n , tccDriverEnabled = tcc\n , unifiedAddressing = ua\n#endif\n#if CUDA_VERSION >= 5050\n , streamPriorities = sp\n#endif\n#if CUDA_VERSION >= 6000\n , globalL1Cache = gl1\n , localL1Cache = ll1\n , managedMemory = mm\n , multiGPUBoard = mg\n , multiGPUBoardGroupID = mid\n#endif\n }\n\n#if CUDA_VERSION < 5000\n-- Deprecated as of CUDA-5.0\n{-# INLINE cuDeviceGetProperties #-}\n{# fun unsafe cuDeviceGetProperties\n { alloca- `CUDevProp' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- The total memory available on the device (bytes).\n--\n-- \n--\n{-# INLINEABLE totalMem #-}\ntotalMem :: Device -> IO Int64\ntotalMem !d = resultIfOk =<< cuDeviceTotalMem d\n\n{-# INLINE cuDeviceTotalMem #-}\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int64' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n#ifdef USE_EMPTY_CASE\n{-# LANGUAGE EmptyCase #-}\n#endif\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device (\n\n -- * Device Management\n Device(..),\n DeviceProperties(..), DeviceAttribute(..), Compute(..), ComputeMode(..), InitFlag,\n initialise, capability, device, attribute, count, name, props, totalMem\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\nimport Control.Applicative\nimport Prelude\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Eq, Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as DeviceAttribute\n { underscoreToCase\n , MAX as CU_DEVICE_ATTRIBUTE_MAX } -- ignore\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> CUDevProp nocode #}\n\n\n#if CUDA_VERSION < 5000\n--\n-- Properties of the compute device (internal helper).\n-- Replaced by cuDeviceGetAttribute in CUDA-5.0 and later.\n--\ndata CUDevProp = CUDevProp\n {\n cuMaxThreadsPerBlock :: !Int, -- Maximum number of threads per block\n cuMaxBlockSize :: !(Int,Int,Int), -- Maximum size of each dimension of a block\n cuMaxGridSize :: !(Int,Int,Int), -- Maximum size of each dimension of a grid\n cuSharedMemPerBlock :: !Int64, -- Shared memory available per block in bytes\n cuTotalConstMem :: !Int64, -- Constant memory available on device in bytes\n cuWarpSize :: !Int, -- Warp size in threads (SIMD width)\n cuMemPitch :: !Int64, -- Maximum pitch in bytes allowed by memory copies\n cuRegsPerBlock :: !Int, -- 32-bit registers available per block\n cuClockRate :: !Int, -- Clock frequency in kilohertz\n cuTextureAlignment :: !Int64 -- Alignment requirement for textures\n }\n deriving (Show)\n\n\ninstance Storable CUDevProp where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"no instance for Foreign.Storable.poke DeviceProperties\"\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n [t1,t2,t3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxThreadsDim#} p\n [g1,g2,g3] <- peekArrayWith cIntConv 3 =<< {#get CUdevprop.maxGridSize#} p\n\n return CUDevProp\n {\n cuMaxThreadsPerBlock = tb,\n cuMaxBlockSize = (t1,t2,t3),\n cuMaxGridSize = (g1,g2,g3),\n cuSharedMemPerBlock = sm,\n cuTotalConstMem = cm,\n cuWarpSize = ws,\n cuMemPitch = mp,\n cuRegsPerBlock = rb,\n cuClockRate = cl,\n cuTextureAlignment = ta\n }\n#endif\n\n\n-- |\n-- Possible option flags for CUDA initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata InitFlag\ninstance Enum InitFlag where\n#ifdef USE_EMPTY_CASE\n toEnum x = case x of {}\n fromEnum x = case x of {}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. This must be called before any other\n-- driver function.\n--\n-- \n--\n{-# INLINEABLE initialise #-}\ninitialise :: [InitFlag] -> IO ()\ninitialise !flags = nothingIfOk =<< cuInit flags\n\n{-# INLINE cuInit #-}\n{# fun unsafe cuInit\n { combineBitMasks `[InitFlag]' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\n{-# INLINEABLE capability #-}\ncapability :: Device -> IO Compute\n#if CUDA_VERSION >= 5000\ncapability !dev =\n Compute <$> attribute dev ComputeCapabilityMajor\n <*> attribute dev ComputeCapabilityMinor\n#else\n-- Deprecated as of CUDA-5.0\n--\ncapability !dev =\n (\\(!s,!a,!b) -> resultIfOk (s,Compute a b)) =<< cuDeviceComputeCapability dev\n\n{-# INLINE cuDeviceComputeCapability #-}\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return a handle to the compute device at the given ordinal.\n--\n-- \n--\n{-# INLINEABLE device #-}\ndevice :: Int -> IO Device\ndevice !d = resultIfOk =<< cuDeviceGet d\n\n{-# INLINE cuDeviceGet #-}\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peek\n\n\n-- |\n-- Return the selected attribute for the given device.\n--\n-- \n--\n{-# INLINEABLE attribute #-}\nattribute :: Device -> DeviceAttribute -> IO Int\nattribute !d !a = resultIfOk =<< cuDeviceGetAttribute a d\n\n{-# INLINE cuDeviceGetAttribute #-}\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `DeviceAttribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0.\n--\n-- \n--\n{-# INLINEABLE count #-}\ncount :: IO Int\ncount = resultIfOk =<< cuDeviceGetCount\n\n{-# INLINE cuDeviceGetCount #-}\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- The identifying name of the device.\n--\n-- \n--\n{-# INLINEABLE name #-}\nname :: Device -> IO String\nname !d = resultIfOk =<< cuDeviceGetName d\n\n{-# INLINE cuDeviceGetName #-}\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\n{-# INLINEABLE props #-}\nprops :: Device -> IO DeviceProperties\nprops !d = do\n\n#if CUDA_VERSION < 5000\n -- Old versions of the CUDA API used the separate cuDeviceGetProperties\n -- function to probe some properties, and cuDeviceGetAttribute for\n -- others. As of CUDA-5.0, the former was deprecated and its\n -- functionality subsumed by the latter, which we use below.\n --\n p <- resultIfOk =<< cuDeviceGetProperties d\n let cm = cuTotalConstMem p\n sm = cuSharedMemPerBlock p\n rb = cuRegsPerBlock p\n ws = cuWarpSize p\n tb = cuMaxThreadsPerBlock p\n bs = cuMaxBlockSize p\n gs = cuMaxGridSize p\n cl = cuClockRate p\n mp = cuMemPitch p\n ta = cuTextureAlignment p\n#else\n cm <- fromIntegral <$> attribute d TotalConstantMemory\n sm <- fromIntegral <$> attribute d SharedMemoryPerBlock\n mp <- fromIntegral <$> attribute d MaxPitch\n ta <- fromIntegral <$> attribute d TextureAlignment\n cl <- attribute d ClockRate\n ws <- attribute d WarpSize\n rb <- attribute d RegistersPerBlock\n tb <- attribute d MaxThreadsPerBlock\n bs <- (,,) <$> attribute d MaxBlockDimX\n <*> attribute d MaxBlockDimY\n <*> attribute d MaxBlockDimZ\n gs <- (,,) <$> attribute d MaxGridDimX\n <*> attribute d MaxGridDimY\n <*> attribute d MaxGridDimZ\n#endif\n\n -- The rest of the properties.\n --\n n <- name d\n cc <- capability d\n gm <- totalMem d\n pc <- attribute d MultiprocessorCount\n md <- toEnum `fmap` attribute d ComputeMode\n ov <- toBool `fmap` attribute d GpuOverlap\n ke <- toBool `fmap` attribute d KernelExecTimeout\n tg <- toBool `fmap` attribute d Integrated\n hm <- toBool `fmap` attribute d CanMapHostMemory\n#if CUDA_VERSION >= 3000\n ck <- toBool `fmap` attribute d ConcurrentKernels\n ee <- toBool `fmap` attribute d EccEnabled\n u1 <- attribute d MaximumTexture1dWidth\n u21 <- attribute d MaximumTexture2dWidth\n u22 <- attribute d MaximumTexture2dHeight\n u31 <- attribute d MaximumTexture3dWidth\n u32 <- attribute d MaximumTexture3dHeight\n u33 <- attribute d MaximumTexture3dDepth\n#endif\n#if CUDA_VERSION >= 4000\n ae <- attribute d AsyncEngineCount\n l2 <- attribute d L2CacheSize\n tm <- attribute d MaxThreadsPerMultiprocessor\n mw <- attribute d GlobalMemoryBusWidth\n mc <- attribute d MemoryClockRate\n pb <- attribute d PciBusId\n pd <- attribute d PciDeviceId\n pm <- attribute d PciDomainId\n ua <- toBool `fmap` attribute d UnifiedAddressing\n tcc <- toBool `fmap` attribute d TccDriver\n#endif\n#if CUDA_VERSION >= 5050\n sp <- toBool `fmap` attribute d StreamPrioritiesSupported\n#endif\n#if CUDA_VERSION >= 6000\n gl1 <- toBool `fmap` attribute d GlobalL1CacheSupported\n ll1 <- toBool `fmap` attribute d LocalL1CacheSupported\n mm <- toBool `fmap` attribute d ManagedMemory\n mg <- toBool `fmap` attribute d MultiGpuBoard\n mid <- attribute d MultiGpuBoardGroupId\n#endif\n\n return DeviceProperties\n {\n deviceName = n\n , computeCapability = cc\n , totalGlobalMem = gm\n , totalConstMem = cm\n , sharedMemPerBlock = sm\n , regsPerBlock = rb\n , warpSize = ws\n , maxThreadsPerBlock = tb\n , maxBlockSize = bs\n , maxGridSize = gs\n , clockRate = cl\n , multiProcessorCount = pc\n , memPitch = mp\n , textureAlignment = ta\n , computeMode = md\n , deviceOverlap = ov\n , kernelExecTimeoutEnabled = ke\n , integrated = tg\n , canMapHostMemory = hm\n#if CUDA_VERSION >= 3000\n , concurrentKernels = ck\n , eccEnabled = ee\n , maxTextureDim1D = u1\n , maxTextureDim2D = (u21,u22)\n , maxTextureDim3D = (u31,u32,u33)\n#endif\n#if CUDA_VERSION >= 4000\n , asyncEngineCount = ae\n , cacheMemL2 = l2\n , maxThreadsPerMultiProcessor = tm\n , memBusWidth = mw\n , memClockRate = mc\n , pciInfo = PCI pb pd pm\n , tccDriverEnabled = tcc\n , unifiedAddressing = ua\n#endif\n#if CUDA_VERSION >= 5050\n , streamPriorities = sp\n#endif\n#if CUDA_VERSION >= 6000\n , globalL1Cache = gl1\n , localL1Cache = ll1\n , managedMemory = mm\n , multiGPUBoard = mg\n , multiGPUBoardGroupID = mid\n#endif\n }\n\n#if CUDA_VERSION < 5000\n-- Deprecated as of CUDA-5.0\n{-# INLINE cuDeviceGetProperties #-}\n{# fun unsafe cuDeviceGetProperties\n { alloca- `CUDevProp' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- The total memory available on the device (bytes).\n--\n-- \n--\n{-# INLINEABLE totalMem #-}\ntotalMem :: Device -> IO Int64\ntotalMem !d = resultIfOk =<< cuDeviceTotalMem d\n\n{-# INLINE cuDeviceTotalMem #-}\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int64' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"04894e7ebf1fa038674c6a9b02e41f8f0edaf4be","subject":"Fix GtkSourceIter docs.","message":"Fix GtkSourceIter docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceIter.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceIter.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceIter\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--\n-- Adds extra useful methods for \"TextIter\" for searching forwards and\n-- backwards within a region in the buffer and matching brackets.\n--\n-- * There is no SourceIter object, just extra methods for \"TextIter\"\n--\nmodule Graphics.UI.Gtk.SourceView.SourceIter (\n-- * Enums\n SourceSearchFlags(..),\n\n-- * Methods\n sourceIterForwardSearch,\n sourceIterBackwardSearch,\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSearchFlags {underscoreToCase} deriving(Eq,Bounded,Show,Read) #}\n\ninstance Flags SourceSearchFlags\n\n-- methods\n\n-- | Searches forward for str. Any match is returned by setting @matchStart@ to the first character of the\n-- match and @matchEnd@ to the first character after the match. The search will not continue past\n-- limit. Note that a search is a linear or O(n) operation, so you may wish to use limit to avoid\n-- locking up your UI on large buffers.\n-- \n-- If the 'SourceSearchVisibleOnly' flag is present, the match may have invisible text\n-- interspersed in str. i.e. str will be a possibly-noncontiguous subsequence of the matched\n-- range. similarly, if you specify 'SourceSearchTextOnly', the match may have pixbufs or child\n-- widgets mixed inside the matched range. If these flags are not given, the match must be exact; the\n-- special 0xFFFC character in str will match embedded pixbufs or child widgets. If you specify the\n-- 'SourceSearchCaseInsensitive' flag, the text will be matched regardless of what case it is in.\n-- \n-- Same as 'textIterForwardSearch', but supports case insensitive searching.\nsourceIterForwardSearch :: TextIter -> String -> [SourceSearchFlags] -> \n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\nsourceIterForwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withUTFString str $ \\cStr ->\n {#call unsafe source_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-- | same as 'textIterForwardSearch' but allows\n-- case insensitive search and possibly in the future regular expressions.\n--\nsourceIterBackwardSearch :: TextIter -> String -> [SourceSearchFlags] -> \n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\nsourceIterBackwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withUTFString str $ \\cStr ->\n {#call unsafe source_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","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceIter\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--\n-- Adds extra useful methods for \"TextIter\" for searching forwards and\n-- backwards within a region in the buffer and matching brackets.\n--\n-- * There is no SourceIter object, just extra methods for \"TextIter\"\n--\nmodule Graphics.UI.Gtk.SourceView.SourceIter (\n SourceSearchFlags(..),\n sourceIterForwardSearch,\n sourceIterBackwardSearch,\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSearchFlags {underscoreToCase} deriving(Eq,Bounded,Show,Read) #}\n\ninstance Flags SourceSearchFlags\n\n-- methods\n\n-- | same as 'textIterForwardSearch' but allows\n-- case insensitive search and possibly in the future regular expressions.\n--\nsourceIterForwardSearch :: TextIter -> String -> [SourceSearchFlags] -> \n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\nsourceIterForwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withUTFString str $ \\cStr ->\n {#call unsafe source_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-- | same as 'textIterForwardSearch' but allows\n-- case insensitive search and possibly in the future regular expressions.\n--\nsourceIterBackwardSearch :: TextIter -> String -> [SourceSearchFlags] -> \n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\nsourceIterBackwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withUTFString str $ \\cStr ->\n {#call unsafe source_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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"12d023826fe5f3ebd968e8d3047eef931c60d423","subject":"Cleaned up description of the Matrix datatype.","message":"Cleaned up description of the Matrix datatype.\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation.\n--\n-- The Matrix type represents a 2x2 transformation matrix along with a\n-- translation vector. @Matrix a1 a2 b1 b2 c1 c2@ describes the\n-- transformation of a point with coordinates x,y that is defined by\n--\n-- > \/ x' \\ = \/ a1 b1 \\ \/ x \\ + \/ c1 \\\n-- > \\ y' \/ \\ a2 b2 \/ \\ y \/ \\ c2 \/\n--\n-- or\n--\n-- > x' = a1 * x + b1 * y + c1\n-- > y' = a2 * x + b2 * y + c2\n\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e2fbf928727f049d8bef6c45976bb5b8a5b22056","subject":"Break cycles in unnamed types by introducing type uprefs at conversion time.","message":"Break cycles in unnamed types by introducing type uprefs at conversion time.\n\nThis simplifies everything else and mimics what LLVM seems to do internally.\n","repos":"travitch\/llvm-analysis,wangxiayang\/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 ( 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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , typeIdSrc :: IORef Int\n , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> IORef Int -> KnotState\nemptyState r1 r2 = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref)\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 put s { typeMap = M.insert ip t (typeMap s) }\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 (_, TYPE_NAMED) ->\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 return $ TypeNamed (show uprefName) innerType\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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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\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 { 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","old_contents":"{-# 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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 ref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState ref)\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 put s { typeMap = M.insert ip t (typeMap s) }\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 (_, TYPE_NAMED) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) ->\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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\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 { 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6a84e487ac3e6cc319642dc7685c5850a28346f1","subject":"Made properties, smart","message":"Made properties, smart","repos":"TomMD\/CV,aleator\/CV,aleator\/CV,BeautifulDestinations\/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-- 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\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\ncvCAP_POS_FRAMES = 1\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","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-- 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\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\ncvCAP_POS_FRAMES = 1\ngetNumberOfFrames cap = unsafePerformIO $\n {#call cvGetCaptureProperty#} \n cap cvCAP_PROP_FRAME_COUNT\ngetFrameNumber cap = unsafePerformIO $\n {#call cvGetCaptureProperty#} \n cap cvCAP_POS_FRAMES\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bd631884cfc1bd08cb8909afdb2438a3230e39ac","subject":"Add an instance for CreateImage for BGR images.","message":"Add an instance for CreateImage for BGR 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, 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\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\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\ninstance CreateImage (Image BGR D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\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","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\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ae24fb6c6ca3827bb2032c8728d5509d728a0a81","subject":"Add Show instances to Enums.","message":"Add Show instances to Enums.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Enums.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Enums.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Enumerations\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon\n--\n-- Created: 13 Januar 1999\n--\n-- Copyright (C) 1999-2005 Manuel M. T. Chakravarty, 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-- General enumeration types.\n--\nmodule Graphics.UI.Gtk.Gdk.Enums (\n CapStyle(..),\n CrossingMode(..),\n Dither(..),\n DragProtocol(..),\n DragAction(..),\n EventMask(..),\n ExtensionMode(..),\n Fill(..),\n Function(..),\n InputCondition(..),\n JoinStyle(..),\n LineStyle(..),\n NotifyType(..),\n ScrollDirection(..),\n SubwindowMode(..),\n VisibilityState(..),\n WindowState(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n GrabStatus(..),\n ) where\n\nimport System.Glib.Flags\t(Flags)\n\n{#context lib=\"gdk\" prefix =\"gdk\"#}\n\n-- | Specify the how the ends of a line is drawn.\n--\n{#enum CapStyle {underscoreToCase}#}\n\n-- | How focus is crossing the widget.\n--\n{#enum CrossingMode {underscoreToCase} deriving(Show) #}\n\n-- | Used in 'Graphics.UI.Gtk.Gdk.Drag.DragContext' to indicate the protocol according to which DND is done.\n--\n{#enum DragProtocol {underscoreToCase} deriving (Bounded,Show)#}\n\n-- | Specify the kind of action performed on a drag event.\n{#enum DragAction {underscoreToCase} deriving (Bounded,Show)#}\n\ninstance Flags DragAction\n\n-- | Specify how to dither colors onto the screen.\n--\n{#enum RgbDither as Dither {underscoreToCase} deriving(Show) #}\n\n-- | specify which events a widget will emit signals on\n--\n{#enum EventMask {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags EventMask\n\n-- | specify which input extension a widget desires\n--\n{#enum ExtensionMode {underscoreToCase} deriving(Bounded,Show)#}\n\ninstance Flags ExtensionMode\n\n-- | How objects are filled.\n--\n{#enum Fill {underscoreToCase} deriving(Show) #}\n\n-- | Determine how bitmap operations are carried out.\n--\n{#enum Function {underscoreToCase} deriving(Show) #}\n\n-- | Specify on what file condition a callback should be\n-- done.\n--\n{#enum InputCondition {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags InputCondition\n\n-- | Determines how adjacent line ends are drawn.\n--\n{#enum JoinStyle {underscoreToCase}#}\n\n-- | Determines if a line is solid or dashed.\n--\n{#enum LineStyle {underscoreToCase}#}\n\n-- | Information on from what level of the widget hierarchy the mouse\n-- cursor came.\n--\n-- ['NotifyAncestor'] The window is entered from an ancestor or left towards\n-- an ancestor.\n--\n-- ['NotifyVirtual'] The pointer moves between an ancestor and an inferior\n-- of the window.\n--\n-- ['NotifyInferior'] The window is entered from an inferior or left\n-- towards an inferior.\n--\n-- ['NotifyNonlinear'] The window is entered from or left towards a\n-- window which is neither an ancestor nor an inferior.\n--\n-- ['NotifyNonlinearVirtual'] The pointer moves between two windows which\n-- are not ancestors of each other and the window is part of the ancestor\n-- chain between one of these windows and their least common ancestor.\n--\n-- ['NotifyUnknown'] The level change does not fit into any of the other\n-- categories or could not be determined.\n--\n{#enum NotifyType {underscoreToCase} deriving(Show) #}\n\n-- | in which direction was scrolled?\n--\n{#enum ScrollDirection {underscoreToCase} deriving(Show) #}\n\n-- | Determine if child widget may be overdrawn.\n--\n{#enum SubwindowMode {underscoreToCase} deriving(Show) #}\n\n-- | visibility of a window\n--\n{#enum VisibilityState {underscoreToCase,\n\t\t\tVISIBILITY_PARTIAL as VisibilityPartialObscured}\n\t\t\t deriving(Show) #}\n\n-- | The state a @DrawWindow@ is in.\n--\n{#enum WindowState {underscoreToCase} deriving (Bounded,Show)#}\n\ninstance Flags WindowState\n\n-- | Determines a window edge or corner.\n--\n{#enum WindowEdge {underscoreToCase} deriving(Show) #}\n\n-- | These are hints for the window manager that indicate what type of function\n-- the window has. The window manager can use this when determining decoration\n-- and behaviour of the window. The hint must be set before mapping the window.\n--\n-- See the extended window manager hints specification for more details about\n-- window types.\n--\n{#enum WindowTypeHint {underscoreToCase} #}\n\n-- | Defines the reference point of a window and the meaning of coordinates\n-- passed to 'Graphics.UI.Gtk.Windows.Window.windowMove'. See\n-- 'Graphics.UI.Gtk.Windows.Window.windowMove' and the \"implementation notes\"\n-- section of the extended window manager hints specification for more details.\n--\n{#enum Gravity {underscoreToCase} deriving(Show) #}\n\n-- | Returned by 'pointerGrab' and 'keyboardGrab' to indicate success or the\n-- reason for the failure of the grab attempt.\n--\n-- [@GrabSuccess@] the resource was successfully grabbed.\n--\n-- [@GrabAlreadyGrabbed@] the resource is actively grabbed by another client.\n--\n-- [@GrabInvalidTime@] the resource was grabbed more recently than the\n-- specified time.\n--\n-- [@GrabNotViewable@] the grab window or the confine_to window are not\n-- viewable.\n--\n-- [@GrabFrozen@] the resource is frozen by an active grab of another client.\n--\n{#enum GrabStatus {underscoreToCase} deriving(Show) #}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Enumerations\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon\n--\n-- Created: 13 Januar 1999\n--\n-- Copyright (C) 1999-2005 Manuel M. T. Chakravarty, 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-- General enumeration types.\n--\nmodule Graphics.UI.Gtk.Gdk.Enums (\n CapStyle(..),\n CrossingMode(..),\n Dither(..),\n DragProtocol(..),\n DragAction(..),\n EventMask(..),\n ExtensionMode(..),\n Fill(..),\n Function(..),\n InputCondition(..),\n JoinStyle(..),\n LineStyle(..),\n NotifyType(..),\n ScrollDirection(..),\n SubwindowMode(..),\n VisibilityState(..),\n WindowState(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n GrabStatus(..),\n ) where\n\nimport System.Glib.Flags\t(Flags)\n\n{#context lib=\"gdk\" prefix =\"gdk\"#}\n\n-- | Specify the how the ends of a line is drawn.\n--\n{#enum CapStyle {underscoreToCase}#}\n\n-- | How focus is crossing the widget.\n--\n{#enum CrossingMode {underscoreToCase}#}\n\n-- | Used in 'Graphics.UI.Gtk.Gdk.Drag.DragContext' to indicate the protocol according to which DND is done.\n--\n{#enum DragProtocol {underscoreToCase} deriving (Bounded)#}\n\n-- | Specify the kind of action performed on a drag event.\n{#enum DragAction {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags DragAction\n\n-- | Specify how to dither colors onto the screen.\n--\n{#enum RgbDither as Dither {underscoreToCase}#}\n\n-- | specify which events a widget will emit signals on\n--\n{#enum EventMask {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags EventMask\n\n-- | specify which input extension a widget desires\n--\n{#enum ExtensionMode {underscoreToCase} deriving(Bounded)#}\n\ninstance Flags ExtensionMode\n\n-- | How objects are filled.\n--\n{#enum Fill {underscoreToCase}#}\n\n-- | Determine how bitmap operations are carried out.\n--\n{#enum Function {underscoreToCase}#}\n\n-- | Specify on what file condition a callback should be\n-- done.\n--\n{#enum InputCondition {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags InputCondition\n\n-- | Determines how adjacent line ends are drawn.\n--\n{#enum JoinStyle {underscoreToCase}#}\n\n-- | Determines if a line is solid or dashed.\n--\n{#enum LineStyle {underscoreToCase}#}\n\n-- | Information on from what level of the widget hierarchy the mouse\n-- cursor came.\n--\n-- ['NotifyAncestor'] The window is entered from an ancestor or left towards\n-- an ancestor.\n--\n-- ['NotifyVirtual'] The pointer moves between an ancestor and an inferior\n-- of the window.\n--\n-- ['NotifyInferior'] The window is entered from an inferior or left\n-- towards an inferior.\n--\n-- ['NotifyNonlinear'] The window is entered from or left towards a\n-- window which is neither an ancestor nor an inferior.\n--\n-- ['NotifyNonlinearVirtual'] The pointer moves between two windows which\n-- are not ancestors of each other and the window is part of the ancestor\n-- chain between one of these windows and their least common ancestor.\n--\n-- ['NotifyUnknown'] The level change does not fit into any of the other\n-- categories or could not be determined.\n--\n{#enum NotifyType {underscoreToCase}#}\n\n-- | in which direction was scrolled?\n--\n{#enum ScrollDirection {underscoreToCase}#}\n\n-- | Determine if child widget may be overdrawn.\n--\n{#enum SubwindowMode {underscoreToCase}#}\n\n-- | visibility of a window\n--\n{#enum VisibilityState {underscoreToCase,\n\t\t\tVISIBILITY_PARTIAL as VisibilityPartialObscured}#}\n\n-- | The state a @DrawWindow@ is in.\n--\n{#enum WindowState {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags WindowState\n\n-- | Determines a window edge or corner.\n--\n{#enum WindowEdge {underscoreToCase} #}\n\n-- | These are hints for the window manager that indicate what type of function\n-- the window has. The window manager can use this when determining decoration\n-- and behaviour of the window. The hint must be set before mapping the window.\n--\n-- See the extended window manager hints specification for more details about\n-- window types.\n--\n{#enum WindowTypeHint {underscoreToCase} #}\n\n-- | Defines the reference point of a window and the meaning of coordinates\n-- passed to 'Graphics.UI.Gtk.Windows.Window.windowMove'. See\n-- 'Graphics.UI.Gtk.Windows.Window.windowMove' and the \"implementation notes\"\n-- section of the extended window manager hints specification for more details.\n--\n{#enum Gravity {underscoreToCase} #}\n\n-- | Returned by 'pointerGrab' and 'keyboardGrab' to indicate success or the\n-- reason for the failure of the grab attempt.\n--\n-- [@GrabSuccess@] the resource was successfully grabbed.\n--\n-- [@GrabAlreadyGrabbed@] the resource is actively grabbed by another client.\n--\n-- [@GrabInvalidTime@] the resource was grabbed more recently than the\n-- specified time.\n--\n-- [@GrabNotViewable@] the grab window or the confine_to window are not\n-- viewable.\n--\n-- [@GrabFrozen@] the resource is frozen by an active grab of another client.\n--\n{#enum GrabStatus {underscoreToCase} #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"2acce8c2ba53addfb5de32eb0e5875cd4ad93f11","subject":"Add description docs in SourceLange.chs","message":"Add description docs in SourceLange.chs\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.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) 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.SourceLanguage (\n-- * Description\n-- | 'SourceLanguage' encapsulates syntax and highlighting styles for a particular language. Use\n-- 'SourceLanguageManager' to obtain a 'SourceLanguage' instance, and\n-- 'sourceBufferSetLanguage' to apply it to a 'SourceBuffer'.\n\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n sourceLanguageGetStyleName,\n sourceLanguageGetStyleIds,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguage\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguage \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguage \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguage \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or empty if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the mime types or empty if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Returns the name of the style with ID @styleId@ defined by this language.\nsourceLanguageGetStyleName :: SourceLanguage \n -> String -- ^ @styleId@ a style ID\n -> IO String -- ^ returns the name of the style with ID @styleId@ defined by this language or empty if the style has no name or there is no style with ID @styleId@ defined by this language. The returned string is owned by the language and must not be modified.\nsourceLanguageGetStyleName sl styleId =\n withUTFString styleId $ \\styleIdPtr ->\n {#call gtk_source_language_get_style_name#}\n sl\n styleIdPtr\n >>= peekUTFString\n\n-- | Returns the ids of the styles defined by this language.\nsourceLanguageGetStyleIds :: SourceLanguage \n -> IO [String] -- ^ returns an array containing ids of the styles defined by this language or empty if no style is defined. \nsourceLanguageGetStyleIds sl = do\n globsArray <- {#call gtk_source_language_get_style_ids#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceLanguage (\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n sourceLanguageGetStyleName,\n sourceLanguageGetStyleIds,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguage\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguage \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguage \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguage \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or empty if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the mime types or empty if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Returns the name of the style with ID @styleId@ defined by this language.\nsourceLanguageGetStyleName :: SourceLanguage \n -> String -- ^ @styleId@ a style ID\n -> IO String -- ^ returns the name of the style with ID @styleId@ defined by this language or empty if the style has no name or there is no style with ID @styleId@ defined by this language. The returned string is owned by the language and must not be modified.\nsourceLanguageGetStyleName sl styleId =\n withUTFString styleId $ \\styleIdPtr ->\n {#call gtk_source_language_get_style_name#}\n sl\n styleIdPtr\n >>= peekUTFString\n\n-- | Returns the ids of the styles defined by this language.\nsourceLanguageGetStyleIds :: SourceLanguage \n -> IO [String] -- ^ returns an array containing ids of the styles defined by this language or empty if no style is defined. \nsourceLanguageGetStyleIds sl = do\n globsArray <- {#call gtk_source_language_get_style_ids#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d263cc598f872afe0eba8788f311d7baac927eb9","subject":"Add new functions : sourceGutterSetDataFunc and sourceGutterSetSizeFunc","message":"Add new functions : sourceGutterSetDataFunc and sourceGutterSetSizeFunc\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceGutter.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceGutter.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceGutter\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceGutter (\n-- * Description\n-- | The 'SourceGutter' object represents the left and right gutters of the text view. It is used by\n-- 'SourceView' to draw the line numbers and category marks that might be present on a line. By\n-- packing additional 'CellRenderer' objects in the gutter, you can extend the gutter with your own\n-- custom drawings.\n-- \n-- The gutter works very much the same way as cells rendered in a 'TreeView'. The concept is similar,\n-- with the exception that the gutter does not have an underlying 'TreeModel'. Instead, you should use\n-- 'sourceGutterSetCellDataFunc' to set a callback to fill in any of the cell renderers\n-- properties, given the line for which the cell is to be rendered. Renderers are inserted into the\n-- gutter at a certain position. \n-- The builtin line number renderer is at position\n-- 'SourceViewGutterPositionLines (-30)' and the marks renderer is at\n-- 'SourceViewGutterPositionMarks (-20)'. You can use these values to position custom renderers\n-- accordingly. The width of a cell renderer can be specified as either fixed (using\n-- 'cellRendererSetFixedSize') or dynamic, in which case you must set\n-- 'sourceGutterSetCellSizeFunc'. This callback is used to set the properties of the renderer\n-- such that @gtkCellRendererGetSize@ yields the maximum width of the cell.\n\n-- * Types\n SourceGutter,\n SourceGutterClass,\n\n-- * Methods\n sourceGutterGetWindow,\n sourceGutterInsert,\n sourceGutterReorder,\n sourceGutterRemove,\n sourceGutterQueueDraw,\n sourceGutterSetCellDataFunc,\n sourceGutterSetCellSizeFunc,\n\n-- * Attributes\n sourceGutterView,\n sourceGutterWindowType,\n\n-- * Signals\n sourceGutterCellActivated,\n sourceGutterQueryTooltip,\n) where\n\nimport Control.Monad\t(liftM)\nimport Control.Monad.Reader ( runReaderT )\n\nimport Graphics.UI.Gtk.Gdk.EventM (EventM, EAny)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.GtkInternals ( TextIter, mkTextIterCopy )\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Properties\nimport System.Glib.UTFString\n\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{#pointer SourceGutterDataFunc#}\n\nforeign import ccall \"wrapper\" mkSourceGutterDataFunc ::\n (Ptr SourceGutter -> Ptr CellRenderer -> {#type gint#} -> {#type gboolean#} -> Ptr () -> IO ())\n -> IO SourceGutterDataFunc\n\n{#pointer SourceGutterSizeFunc#}\n\nforeign import ccall \"wrapper\" mkSourceGutterSizeFunc ::\n (Ptr SourceGutter -> Ptr CellRenderer -> Ptr () -> IO ())\n -> IO SourceGutterSizeFunc\n\n-- | Get the 'Window' of the gutter. The window will only be available when the gutter has at least one,\n-- non-zero width, cell renderer packed.\nsourceGutterGetWindow :: SourceGutterClass sg => sg -> IO (Maybe DrawWindow)\nsourceGutterGetWindow sb =\n maybeNull (makeNewGObject mkDrawWindow) $\n {#call gtk_source_gutter_get_window #} (toSourceGutter sb)\n\n-- | Inserts renderer into gutter at position.\nsourceGutterInsert :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the renderers position \n -> IO ()\nsourceGutterInsert gutter renderer position =\n {#call gtk_source_gutter_insert #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Reorders renderer in gutter to new position.\nsourceGutterReorder :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the new renderer position \n -> IO ()\nsourceGutterReorder gutter renderer position =\n {#call gtk_source_gutter_reorder #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Removes renderer from gutter.\nsourceGutterRemove :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> IO ()\nsourceGutterRemove gutter renderer =\n {#call gtk_source_gutter_remove #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n\n-- | Invalidates the drawable area of the gutter. You can use this to force a redraw of the gutter if\n-- something has changed and needs to be redrawn.\nsourceGutterQueueDraw :: SourceGutterClass sg => sg -> IO ()\nsourceGutterQueueDraw sb =\n {#call gtk_source_gutter_queue_draw #} (toSourceGutter sb)\n\n-- | Sets the 'SourceGutterDataFunc' to use for renderer. This function is used to setup the cell\n-- renderer properties for rendering the current cell.\nsourceGutterSetCellDataFunc :: (SourceGutterClass sg, CellRendererClass cell)\n => sg\n -> cell\n -> (CellRenderer -> Int -> Bool -> IO ())\n -> IO ()\nsourceGutterSetCellDataFunc gutter cell func = do\n funcPtr <- mkSourceGutterDataFunc $ \\_ c line currentLine _ -> do\n func (toCellRenderer cell)\n (fromIntegral line)\n (toBool currentLine)\n {#call gtk_source_gutter_set_cell_data_func #}\n (toSourceGutter gutter)\n (toCellRenderer cell)\n funcPtr\n (castFunPtrToPtr funcPtr)\n destroyFunPtr\n\n-- | Sets the 'SourceGutterSizeFunc' to use for renderer. This function is used to setup the cell\n-- renderer properties for measuring the maximum size of the cell.\nsourceGutterSetCellSizeFunc :: (SourceGutterClass gutter, CellRendererClass cell)\n => gutter\n -> cell\n -> (CellRenderer -> IO ())\n -> IO ()\nsourceGutterSetCellSizeFunc gutter cell func = do\n funcPtr <- mkSourceGutterSizeFunc $ \\ _ c _ -> do\n func (toCellRenderer cell)\n {#call gtk_source_gutter_set_cell_size_func #}\n (toSourceGutter gutter)\n (toCellRenderer cell)\n funcPtr\n (castFunPtrToPtr funcPtr)\n destroyFunPtr\n\n-- | The 'SourceView' of the gutter\nsourceGutterView :: SourceGutterClass sg => Attr sg SourceView\nsourceGutterView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The text window type on which the window is placed\n-- \n-- Default value: 'TextWindowPrivate'\nsourceGutterWindowType :: SourceGutterClass sg => Attr sg TextWindowType\nsourceGutterWindowType = newAttrFromEnumProperty \"window-type\"\n {#call pure unsafe gtk_text_window_type_get_type #}\n \n-- | Emitted when a cell has been activated (for instance when there was a button press on the cell). The\n-- signal is only emitted for cells that have the activatable property set to 'True'.\nsourceGutterCellActivated :: SourceGutterClass sg => Signal sg (CellRenderer -> TextIter -> EventM EAny ()) \nsourceGutterCellActivated =\n Signal (\\after obj fun -> \n connect_OBJECT_PTR_BOXED__NONE \"cell-activated\" mkTextIterCopy after obj\n (\\cr eventPtr iter -> runReaderT (fun cr iter) eventPtr)\n )\n\n-- | Emitted when a tooltip is requested for a specific cell. Signal handlers can return 'True' to notify\n-- the tooltip has been handled.\nsourceGutterQueryTooltip :: SourceGutterClass sg => Signal sg (CellRenderer -> TextIter -> Tooltip -> IO Bool)\nsourceGutterQueryTooltip = \n Signal $ connect_OBJECT_BOXED_OBJECT__BOOL \"query-tooltip\" mkTextIterCopy\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceGutter\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceGutter (\n-- * Description\n-- | The 'SourceGutter' object represents the left and right gutters of the text view. It is used by\n-- 'SourceView' to draw the line numbers and category marks that might be present on a line. By\n-- packing additional 'CellRenderer' objects in the gutter, you can extend the gutter with your own\n-- custom drawings.\n-- \n-- The gutter works very much the same way as cells rendered in a 'TreeView'. The concept is similar,\n-- with the exception that the gutter does not have an underlying 'TreeModel'. Instead, you should use\n-- 'sourceGutterSetCellDataFunc' to set a callback to fill in any of the cell renderers\n-- properties, given the line for which the cell is to be rendered. Renderers are inserted into the\n-- gutter at a certain position. \n-- The builtin line number renderer is at position\n-- 'SourceViewGutterPositionLines (-30)' and the marks renderer is at\n-- 'SourceViewGutterPositionMarks (-20)'. You can use these values to position custom renderers\n-- accordingly. The width of a cell renderer can be specified as either fixed (using\n-- 'cellRendererSetFixedSize') or dynamic, in which case you must set\n-- 'sourceGutterSetCellSizeFunc'. This callback is used to set the properties of the renderer\n-- such that @gtkCellRendererGetSize@ yields the maximum width of the cell.\n\n-- * Types\n SourceGutter,\n SourceGutterClass,\n\n-- * Methods\n sourceGutterGetWindow,\n sourceGutterInsert,\n sourceGutterReorder,\n sourceGutterRemove,\n sourceGutterQueueDraw,\n\n-- * Attributes\n sourceGutterView,\n sourceGutterWindowType,\n\n-- * Signals\n sourceGutterCellActivated,\n sourceGutterQueryTooltip,\n) where\n\nimport Control.Monad\t(liftM)\nimport Control.Monad.Reader ( runReaderT )\n\nimport Graphics.UI.Gtk.Gdk.EventM (EventM, EAny)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.GtkInternals ( TextIter, mkTextIterCopy )\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Properties\nimport System.Glib.UTFString\n\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the 'Window' of the gutter. The window will only be available when the gutter has at least one,\n-- non-zero width, cell renderer packed.\nsourceGutterGetWindow :: SourceGutterClass sg => sg -> IO (Maybe DrawWindow)\nsourceGutterGetWindow sb =\n maybeNull (makeNewGObject mkDrawWindow) $\n {#call gtk_source_gutter_get_window #} (toSourceGutter sb)\n\n-- | Inserts renderer into gutter at position.\nsourceGutterInsert :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the renderers position \n -> IO ()\nsourceGutterInsert gutter renderer position =\n {#call gtk_source_gutter_insert #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Reorders renderer in gutter to new position.\nsourceGutterReorder :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the new renderer position \n -> IO ()\nsourceGutterReorder gutter renderer position =\n {#call gtk_source_gutter_reorder #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Removes renderer from gutter.\nsourceGutterRemove :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> IO ()\nsourceGutterRemove gutter renderer =\n {#call gtk_source_gutter_remove #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n\n-- | Invalidates the drawable area of the gutter. You can use this to force a redraw of the gutter if\n-- something has changed and needs to be redrawn.\nsourceGutterQueueDraw :: SourceGutterClass sg => sg -> IO ()\nsourceGutterQueueDraw sb =\n {#call gtk_source_gutter_queue_draw #} (toSourceGutter sb)\n\n-- | The 'SourceView' of the gutter\nsourceGutterView :: SourceGutterClass sg => Attr sg SourceView\nsourceGutterView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The text window type on which the window is placed\n-- \n-- Default value: 'TextWindowPrivate'\nsourceGutterWindowType :: SourceGutterClass sg => Attr sg TextWindowType\nsourceGutterWindowType = newAttrFromEnumProperty \"window-type\"\n {#call pure unsafe gtk_text_window_type_get_type #}\n \n-- | Emitted when a cell has been activated (for instance when there was a button press on the cell). The\n-- signal is only emitted for cells that have the activatable property set to 'True'.\nsourceGutterCellActivated :: SourceGutterClass sg => Signal sg (CellRenderer -> TextIter -> EventM EAny ()) \nsourceGutterCellActivated =\n Signal (\\after obj fun -> \n connect_OBJECT_PTR_BOXED__NONE \"cell-activated\" mkTextIterCopy after obj\n (\\cr eventPtr iter -> runReaderT (fun cr iter) eventPtr)\n )\n\n-- | Emitted when a tooltip is requested for a specific cell. Signal handlers can return 'True' to notify\n-- the tooltip has been handled.\nsourceGutterQueryTooltip :: SourceGutterClass sg => Signal sg (CellRenderer -> TextIter -> Tooltip -> IO Bool)\nsourceGutterQueryTooltip = \n Signal $ connect_OBJECT_BOXED_OBJECT__BOOL \"query-tooltip\" mkTextIterCopy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"df11bf6060109e88e5ef69299a0f318cbb074689","subject":"added non-polymorphic version of writeBand","message":"added non-polymorphic version of writeBand\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 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","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 , 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 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":"459819ef68ac068c0aeedc6d43b1dddc383fb7f7","subject":"Add function sourceCompletionCreateContext","message":"Add function sourceCompletionCreateContext\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n -- sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionGetInfoWindow,\n sourceCompletionCreateContext,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n -- sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\n-- sourceCompletionShow :: SourceCompletionClass sc => sc\n-- -> [SourceCompletionProvider]\n-- -> \n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | The info widget is the window where the completion displays optional extra information of the\n-- proposal.\nsourceCompletionGetInfoWindow :: SourceCompletionClass sc => sc -> IO SourceCompletionInfo\nsourceCompletionGetInfoWindow sc =\n makeNewObject mkSourceCompletionInfo $\n {#call gtk_source_completion_get_info_window #}\n (toSourceCompletion sc)\n\n-- | Create a new 'SourceCompletionContext' for completion. The position at which the completion using\n-- the new context will consider completion can be provider by position. If position is 'Nothing', the\n-- current cursor position will be used.\nsourceCompletionCreateContext :: SourceCompletionClass sc => sc\n -> Maybe TextIter\n -> IO SourceCompletionContext\nsourceCompletionCreateContext sc iter = \n makeNewGObject mkSourceCompletionContext $\n {#call gtk_source_completion_create_context #}\n (toSourceCompletion sc)\n (fromMaybe (TextIter nullForeignPtr) iter)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate_proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move_cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move_page\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n -- sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionGetInfoWindow,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n -- sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\n-- sourceCompletionShow :: SourceCompletionClass sc => sc\n-- -> [SourceCompletionProvider]\n-- -> \n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | The info widget is the window where the completion displays optional extra information of the\n-- proposal.\nsourceCompletionGetInfoWindow :: SourceCompletionClass sc => sc -> IO SourceCompletionInfo\nsourceCompletionGetInfoWindow sc =\n makeNewObject mkSourceCompletionInfo $\n {#call gtk_source_completion_get_info_window #}\n (toSourceCompletion sc)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate_proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move_cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move_page\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fd34a4a3ca7705eb623171813a17c3ac7fb3a76d","subject":"storable instance for textures","message":"storable instance for textures\n\nIgnore-this: 6aa1cda922eb9832c02b8b49b249869a\n\ndarcs-hash:20100610012250-dcabc-306b1b6d962d0094c75bfde601c05bf4e0a99a7b.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(..), AddressMode(..), FilterMode(..), Format(..),\n create, destroy,\n getPtr, getAddressMode, getFilterMode, getFormat,\n setPtr, setAddressMode, setFilterMode, setFormat\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\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-- |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-- |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-- |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-- |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--\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat tex fmt dim = nothingIfOk =<< cuTexRefSetFormat tex fmt dim\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(..), AddressMode(..), FilterMode(..), Format(..),\n create, destroy,\n getPtr, getAddressMode, getFilterMode, getFormat,\n setPtr, setAddressMode, setFilterMode, setFormat\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\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-- |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-- |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-- |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--\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat tex fmt dim = nothingIfOk =<< cuTexRefSetFormat tex fmt dim\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"a26f124c43e0222757021c0580a1f7cf4a393ce7","subject":"Some more index stuff","message":"Some more index stuff\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\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","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.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: 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":"6691b12a134704ad1920c687e4a7b1ebb1d6a4d8","subject":"style tweaks","message":"style tweaks\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 <$> 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 <- 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 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) = 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 <- (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 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 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 = Extension <$> peekElemOff (castPtr ptr) off\n pokeElemOff ptr off (Extension ex) = pokeElemOff (castPtr ptr) off ex\n peekByteOff ptr off = Extension <$> peekByteOff ptr off\n pokeByteOff ptr off (Extension ex) = pokeByteOff ptr off ex\n peek ptr = 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 = toBool <$> {#get query_extension_reply_t->present#} ext\n\nextensionMajorOpcode :: ExtensionInfo -> IO Word8\nextensionMajorOpcode (ExtensionInfo ext)\n = fromIntegral <$> {#get query_extension_reply_t->major_opcode#} ext\n\nextensionFirstEvent :: ExtensionInfo -> IO Word8\nextensionFirstEvent (ExtensionInfo ext)\n = fromIntegral <$> {#get query_extension_reply_t->first_event#} ext\n\nextensionFirstError :: ExtensionInfo -> IO Word8\nextensionFirstError (ExtensionInfo ext)\n = 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) <$> responseType ev\n\nisError :: HasResponseType a => a -> IO Bool\nisError ev = (== 2) <$> 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 GenericEvent <$> newForeignPtr finalizerFree evPtr\n\ninstance HasResponseType GenericEvent where\n responseType = eventResponseType\n\neventResponseType :: GenericEvent -> IO Int\neventResponseType ev = withGenericEvent ev $ \\evPtr ->\n 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 <$> {#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 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 <- 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 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 <$> 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 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 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.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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"fe229b348ba483116ac36b2a26ab5b41b8b758f0","subject":"Add some function to SourceCompletion module","message":"Add some function to SourceCompletion module\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletion.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionAddProvider,\n sourceCompletionRemoveProvider,\n sourceCompletionGetProviders,\n -- sourceCompletionShow,\n sourceCompletionHide,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n -- sourceCompletionPopulateContext,\n sourceCompletionShowSignal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Add a new 'SourceCompletionProvider' to the completion object. This will add a reference provider,\n-- so make sure to unref your own copy when you no longer need it.\nsourceCompletionAddProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully added, otherwise if error is provided, it will be set with the error and \nsourceCompletionAddProvider sc provider = \n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {# call gtk_source_completion_add_provider #} \n (toSourceCompletion sc)\n provider\n gErrorPtr\n\n-- | Remove provider from the completion.\nsourceCompletionRemoveProvider :: SourceCompletionClass sc => sc \n -> SourceCompletionProvider\n -> IO Bool -- ^ returns 'True' if provider was successfully removed, otherwise if error is provided, it will be set with the error and \nsourceCompletionRemoveProvider sc provider =\n liftM toBool $\n propagateGError $ \\gErrorPtr -> \n {#call gtk_source_completion_remove_provider #}\n (toSourceCompletion sc)\n provider\n gErrorPtr\n \n-- | Get list of providers registered on completion. The returned list is owned by the completion and\n-- should not be freed.\nsourceCompletionGetProviders :: SourceCompletionClass sc => sc -> IO [SourceCompletionProvider]\nsourceCompletionGetProviders sc = do\n glist <- {#call gtk_source_completion_get_providers #} (toSourceCompletion sc)\n glistPtrs <- fromGList glist\n mapM (makeNewGObject mkSourceCompletionProvider . return) glistPtrs \n\n-- | Starts a new completion with the specified 'SourceCompletionContext' and a list of potential\n-- candidate providers for completion.\n-- sourceCompletionShow :: SourceCompletionClass sc => sc\n-- -> [SourceCompletionProvider]\n-- -> \n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate-proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move-cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move-page\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShowSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShowSignal =\n Signal $ connect_NONE__NONE \"show\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletion\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletion (\n-- * Types\n SourceCompletion,\n SourceCompletionClass,\n\n-- * Methods\n sourceCompletionHide,\n sourceCompletionMoveWindow,\n sourceCompletionBlockInteractive,\n sourceCompletionUnblockInteractive,\n\n-- * Attributes\n sourceCompletionAccelerators,\n sourceCompletionAutoCompleteDelay,\n sourceCompletionProposalPageSize,\n sourceCompletionProviderPageSize,\n sourceCompletionRememberInfoVisibility,\n sourceCompletionSelectOnShow,\n sourceCompletionShowHeaders,\n sourceCompletionShowIcons,\n sourceCompletionView,\n\n-- * Signals\n sourceCompletionActivateProposal,\n sourceCompletionHideSignal,\n sourceCompletionMoveCursor,\n sourceCompletionMovePage,\n -- sourceCompletionPopulateContext,\n sourceCompletionShow,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.Gtk.General.Enums (ScrollStep (..))\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Hides the completion if it is active (visible).\nsourceCompletionHide :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionHide sc =\n {#call gtk_source_completion_hide #} (toSourceCompletion sc)\n\n-- | Move the completion window to a specific iter.\nsourceCompletionMoveWindow :: SourceCompletionClass sc => sc\n -> TextIter \n -> IO ()\nsourceCompletionMoveWindow sc iter = \n {#call gtk_source_completion_move_window #}\n (toSourceCompletion sc)\n iter\n\n-- | Block interactive completion. This can be used to disable interactive completion when inserting or\n-- deleting text from the buffer associated with the completion. Use\n-- 'sourceCompletionUnblockInteractive' to enable interactive completion again.\nsourceCompletionBlockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionBlockInteractive sc =\n {#call gtk_source_completion_block_interactive #}\n (toSourceCompletion sc)\n\n-- | Unblock interactive completion. This can be used after using 'sourceCompletionBlockInteractive'\n-- to enable interactive completion again.\nsourceCompletionUnblockInteractive :: SourceCompletionClass sc => sc -> IO ()\nsourceCompletionUnblockInteractive sc =\n {#call gtk_source_completion_unblock_interactive #}\n (toSourceCompletion sc)\n\n-- | Number of accelerators to show for the first proposals.\n-- \n-- Allowed values: <= 10\n-- \n-- Default value: 5\n--\nsourceCompletionAccelerators :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAccelerators = newAttrFromIntProperty \"accelerators\"\n\n-- | Determines the popup delay (in milliseconds) at which the completion will be shown for interactive\n-- completion.\n-- \n-- Default value: 250\n--\nsourceCompletionAutoCompleteDelay :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionAutoCompleteDelay = newAttrFromIntProperty \"auto-complete-delay\"\n\n-- | The scroll page size of the proposals in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProposalPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProposalPageSize = newAttrFromIntProperty \"proposal-page-size\"\n\n-- | The scroll page size of the provider pages in the completion window.\n-- \n-- Allowed values: >= 1\n-- \n-- Default value: 5\n--\nsourceCompletionProviderPageSize :: SourceCompletionClass sc => Attr sc Int\nsourceCompletionProviderPageSize = newAttrFromIntProperty \"provider-page-size\"\n\n-- | Determines whether the visibility of the info window should be saved when the completion is hidden,\n-- and restored when the completion is shown again.\n-- \n-- Default value: 'False'\n--\nsourceCompletionRememberInfoVisibility :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionRememberInfoVisibility = newAttrFromBoolProperty \"remember-info-visibility\"\n\n-- | Determines whether the first proposal should be selected when the completion is first shown.\n-- \n-- Default value: 'True'\n--\nsourceCompletionSelectOnShow :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionSelectOnShow = newAttrFromBoolProperty \"select-on-show\"\n\n-- | Determines whether provider headers should be shown in the proposal list if there is more than one\n-- provider with proposals.\n-- \n-- Default value: 'True'\nsourceCompletionShowHeaders :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowHeaders = newAttrFromBoolProperty \"show-headers\"\n\n-- | Determines whether provider and proposal icons should be shown in the completion popup.\n-- \n-- Default value: 'True'\n--\nsourceCompletionShowIcons :: SourceCompletionClass sc => Attr sc Bool\nsourceCompletionShowIcons = newAttrFromBoolProperty \"show-icons\"\n\n-- | The 'SourceView' bound to the completion object.\n--\nsourceCompletionView :: SourceCompletionClass sc => Attr sc SourceView\nsourceCompletionView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The 'activateProposal' signal is a keybinding signal which gets emitted when the user initiates a\n-- proposal activation.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the proposal activation programmatically.\nsourceCompletionActivateProposal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionActivateProposal = \n Signal $ connect_NONE__NONE \"activate-proposal\"\n\n-- | Emitted when the completion window is hidden. The default handler will actually hide the window.\nsourceCompletionHideSignal :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionHideSignal =\n Signal $ connect_NONE__NONE \"hide\"\n\n-- | The 'moveCursor' signal is a keybinding signal which gets emitted when the user initiates a cursor\n-- movement.\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the cursor programmatically.\nsourceCompletionMoveCursor :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMoveCursor =\n Signal $ connect_ENUM_INT__NONE \"move-cursor\"\n\n-- | The 'movePage' signal is a keybinding signal which gets emitted when the user initiates a page\n-- movement (i.e. switches between provider pages).\n-- \n-- Applications should not connect to it, but may emit it with @gSignalEmitByName@ if they need to\n-- control the page selection programmatically.\nsourceCompletionMovePage :: SourceCompletionClass sc => Signal sc (ScrollStep -> Int -> IO ())\nsourceCompletionMovePage =\n Signal $ connect_ENUM_INT__NONE \"move-page\"\n\n-- | Emitted when the completion window is shown. The default handler will actually show the window.\nsourceCompletionShow :: SourceCompletionClass sc => Signal sc (IO ())\nsourceCompletionShow =\n Signal $ connect_NONE__NONE \"show\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9ceefe907b501c869b2e78fca74c06e86edd028c","subject":"gstreamer: hopefully fix takeObject & peekObject for real this time","message":"gstreamer: hopefully fix takeObject & peekObject for real this time\n\ntakeObject: to be used when a function returns an object that must be unreffed at GC.\n If the object has a floating reference, the float flag is removed.\n\npeekObject: to be used when an object must not be unreffed. A ref is added, and is\n removed at GC. The floating flag is not touched.\n","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n cObjectRef cObject\n takeObject cObject\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat\n newForeignPtr (castPtr cObject) objectFinalizer\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7431cdc5e00a783adfbd251448f7e3b55b89ff84","subject":"Haddock for some group operations","message":"Haddock for some group operations\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. 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'. 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-- | 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\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\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-- | 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{-\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 :: 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 :: 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 (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 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 (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 (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\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{# 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'. 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-- | 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\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\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-- | 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{-\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 :: 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 :: 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 (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 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 (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 (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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6787c79e57a7a0ecfaaf448a943901e212e61d44","subject":"older c2hs needs the explicit import","message":"older c2hs needs the explicit import\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/Algorithms.chs","new_file":"src\/GDAL\/Internal\/Algorithms.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n\nmodule GDAL.Internal.Algorithms (\n Transformer (..)\n , TransformerFunc\n , GenImgProjTransformer (..)\n , GenImgProjTransformer2 (..)\n , GenImgProjTransformer3 (..)\n\n , rasterizeLayersBuf\n) where\n\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM)\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Default (Default(..))\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types (CDouble(..), CInt(..))\nimport qualified Foreign.C.Types as C2HSImp -- workaround c2hs 0.26\nimport Foreign.C.String (CString)\nimport Foreign.Marshal.Utils (fromBool)\nimport Foreign.Ptr (Ptr, FunPtr, nullPtr, castPtr, nullFunPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Storable (poke)\n\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.Types\nimport GDAL.Internal.CPLString\nimport GDAL.Internal.OSR (SpatialReference, withMaybeSRAsCString)\n{#import GDAL.Internal.CPLProgress#}\n{#import GDAL.Internal.OGR#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.GDAL#}\n\n#include \"gdal_alg.h\"\n\ndata GDALAlgorithmException\n = RasterizeStopped\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALAlgorithmException where\n rnf a = a `seq` ()\n\ninstance Exception GDALAlgorithmException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\nclass Transformer t where\n transformerFunc :: t s a b -> TransformerFunc\n createTransformer :: Ptr (RODataset s a) -> t s a b -> IO (Ptr (t s a b))\n destroyTransformer :: Ptr (t s a b) -> IO ()\n\n destroyTransformer = {# call GDALDestroyTransformer as ^#} . castPtr\n\n{# pointer GDALTransformerFunc as TransformerFunc #}\n\n{-\nwithTransformer :: Transformer t => t -> (Ptr (t s a b) -> IO c) -> IO c\nwithTransformer t = bracket\n-}\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform :: TransformerFunc\n\n\n-- ############################################################################\n-- GenImgProjTransformer\n-- ############################################################################\n\ndata GenImgProjTransformer s a b =\n GenImgProjTransformer {\n giptSrcDs :: Maybe (RODataset s a)\n , giptDstDs :: Maybe (RWDataset s b)\n , giptSrcSrs :: Maybe SpatialReference\n , giptDstSrs :: Maybe SpatialReference\n , giptUseGCP :: Bool\n , giptMaxError :: Double\n , giptOrder :: Int\n }\n\ninstance Default (GenImgProjTransformer s a b) where\n def = GenImgProjTransformer {\n giptSrcDs = Nothing\n , giptDstDs = Nothing\n , giptSrcSrs = Nothing\n , giptDstSrs = Nothing\n , giptUseGCP = True\n , giptMaxError = 1\n , giptOrder = 0\n }\n\ninstance Transformer GenImgProjTransformer where\n transformerFunc _ = c_GDALGenImgProjTransform\n createTransformer dsPtr GenImgProjTransformer{..}\n = throwIfError \"GDALCreateGenImgProjTransformer\" $\n withMaybeSRAsCString giptSrcSrs $ \\sSr ->\n withMaybeSRAsCString giptDstSrs $ \\dSr ->\n c_createGenImgProjTransformer\n (maybe dsPtr unDataset giptSrcDs)\n sSr\n (maybe nullPtr unDataset giptDstDs)\n dSr\n (fromBool giptUseGCP)\n (realToFrac giptMaxError)\n (fromIntegral giptOrder)\n\nforeign import ccall safe \"gdal_alg.h GDALCreateGenImgProjTransformer\"\n c_createGenImgProjTransformer\n :: Ptr (RODataset s a) -> CString -> Ptr (Dataset s m b) -> CString -> CInt\n -> CDouble -> CInt -> IO (Ptr (GenImgProjTransformer s a b))\n\n-- ############################################################################\n-- GenImgProjTransformer2\n-- ############################################################################\n\ndata GenImgProjTransformer2 s a b =\n GenImgProjTransformer2 {\n gipt2SrcDs :: Maybe (RODataset s a)\n , gipt2DstDs :: Maybe (RWDataset s b)\n , gipt2Options :: OptionList\n }\n\ninstance Default (GenImgProjTransformer2 s a b) where\n def = GenImgProjTransformer2 {\n gipt2SrcDs = Nothing\n , gipt2DstDs = Nothing\n , gipt2Options = []\n }\n\ninstance Transformer GenImgProjTransformer2 where\n transformerFunc _ = c_GDALGenImgProjTransform\n createTransformer dsPtr GenImgProjTransformer2{..}\n = throwIfError \"GDALCreateGenImgProjTransformer2\" $\n withOptionList gipt2Options $ \\opts ->\n c_createGenImgProjTransformer2\n (maybe dsPtr unDataset gipt2SrcDs)\n (maybe nullPtr unDataset gipt2DstDs)\n opts\n\nforeign import ccall safe \"gdal_alg.h GDALCreateGenImgProjTransformer2\"\n c_createGenImgProjTransformer2\n :: Ptr (RODataset s a) -> Ptr (RWDataset s b) -> Ptr CString\n -> IO (Ptr (GenImgProjTransformer2 s a b))\n\n-- ############################################################################\n-- GenImgProjTransformer3\n-- ############################################################################\n\ndata GenImgProjTransformer3 s a b =\n GenImgProjTransformer3 {\n gipt3SrcSrs :: Maybe SpatialReference\n , gipt3DstSrs :: Maybe SpatialReference\n , gipt3SrcGt :: Maybe Geotransform\n , gipt3DstGt :: Maybe Geotransform\n }\n\ninstance Default (GenImgProjTransformer3 s a b) where\n def = GenImgProjTransformer3 {\n gipt3SrcSrs = Nothing\n , gipt3DstSrs = Nothing\n , gipt3SrcGt = Nothing\n , gipt3DstGt = Nothing\n }\n\ninstance Transformer GenImgProjTransformer3 where\n transformerFunc _ = c_GDALGenImgProjTransform\n createTransformer _ GenImgProjTransformer3{..}\n = throwIfError \"GDALCreateGenImgProjTransformer3\" $\n withMaybeSRAsCString gipt3SrcSrs $ \\sSr ->\n withMaybeSRAsCString gipt3DstSrs $ \\dSr ->\n withMaybeGeotransformPtr gipt3SrcGt $ \\sGt ->\n withMaybeGeotransformPtr gipt3DstGt $ \\dGt ->\n c_createGenImgProjTransformer3 sSr sGt dSr dGt\n\nwithMaybeGeotransformPtr\n :: Maybe Geotransform -> (Ptr Geotransform -> IO a) -> IO a\nwithMaybeGeotransformPtr Nothing f = f nullPtr\nwithMaybeGeotransformPtr (Just g) f = alloca $ \\gp -> poke gp g >> f gp\n\nforeign import ccall safe \"gdal_alg.h GDALCreateGenImgProjTransformer3\"\n c_createGenImgProjTransformer3\n :: CString -> Ptr Geotransform -> CString -> Ptr Geotransform\n -> IO (Ptr (GenImgProjTransformer3 s a b))\n\n-- ############################################################################\n-- GDALRasterizeLayersBuf\n-- ############################################################################\n\nrasterizeLayersBuf\n :: forall s t a l. (GDALType a, Transformer t)\n => Size\n -> [ROLayer s l]\n -> SpatialReference\n -> Geotransform\n -> Maybe (t s a a)\n -> a\n -> a\n -> OptionList\n -> Maybe ProgressFun\n -> GDAL s (U.Vector (Value a))\nrasterizeLayersBuf\n size layers srs geotransform mTransformer nodataValue burnValue options\n progressFun = liftIO $ do\n ret <- withLockedLayerPtrs layers $ \\layerPtrs ->\n withArrayLen layerPtrs $ \\len lPtrPtr ->\n with geotransform $ \\gt ->\n withMaybeSRAsCString (Just srs) $ \\srsPtr ->\n withOptionList options $ \\opts ->\n withProgressFun progressFun $ \\pFun -> do\n mVec <- Stm.replicate (sizeLen size) nodataValue\n Stm.unsafeWith mVec $ \\vecPtr ->\n c_rasterizeLayersBuf vecPtr nx ny dt 0 0 (fromIntegral len)\n lPtrPtr srsPtr gt nullFunPtr nullPtr bValue opts pFun nullPtr\n return mVec\n maybe (throwBindingException RasterizeStopped)\n (liftM (stToUValue . St.map toValue) . St.unsafeFreeze) ret\n where\n toValue v = if toNodata v == ndValue then NoData else Value v\n dt = fromEnumC (datatype (Proxy :: Proxy a))\n bValue = toNodata burnValue\n ndValue = toNodata nodataValue\n XY nx ny = fmap fromIntegral size\n\nforeign import ccall safe \"gdal_alg.h GDALRasterizeLayersBuf\"\n c_rasterizeLayersBuf\n :: Ptr a -- pData\n -> CInt -- eBufXSize\n -> CInt -- eBufYSize\n -> CInt -- eBufType\n -> CInt -- nPixelSpace\n -> CInt -- nLineSpace\n -> CInt -- nLayerCount\n -> Ptr (Ptr (ROLayer s b)) -- pahLayers\n -> CString -- pszDstProjection\n -> Ptr Geotransform -- padfDstGeoTransform\n -> TransformerFunc -- pfnTransformer\n -> Ptr () -- pTransformerArg\n -> CDouble -- dfBurnValue\n -> Ptr CString -- papszOptions\n -> ProgressFunPtr -- pfnProgress\n -> Ptr () -- pProgressArg\n -> IO CInt\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n\nmodule GDAL.Internal.Algorithms (\n Transformer (..)\n , TransformerFunc\n , GenImgProjTransformer (..)\n , GenImgProjTransformer2 (..)\n , GenImgProjTransformer3 (..)\n\n , rasterizeLayersBuf\n) where\n\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM)\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Default (Default(..))\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types (CDouble(..), CInt(..))\nimport qualified Foreign.C.Types as C2HSImp -- workaround c2hs 0.26\nimport Foreign.C.String (CString)\nimport Foreign.Marshal.Utils (fromBool)\nimport Foreign.Ptr (Ptr, nullPtr, castPtr, nullFunPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Storable (poke)\n\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.Types\nimport GDAL.Internal.CPLString\nimport GDAL.Internal.OSR (SpatialReference, withMaybeSRAsCString)\n{#import GDAL.Internal.CPLProgress#}\n{#import GDAL.Internal.OGR#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.GDAL#}\n\n#include \"gdal_alg.h\"\n\ndata GDALAlgorithmException\n = RasterizeStopped\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALAlgorithmException where\n rnf a = a `seq` ()\n\ninstance Exception GDALAlgorithmException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\nclass Transformer t where\n transformerFunc :: t s a b -> TransformerFunc\n createTransformer :: Ptr (RODataset s a) -> t s a b -> IO (Ptr (t s a b))\n destroyTransformer :: Ptr (t s a b) -> IO ()\n\n destroyTransformer = {# call GDALDestroyTransformer as ^#} . castPtr\n\n{# pointer GDALTransformerFunc as TransformerFunc #}\n\n{-\nwithTransformer :: Transformer t => t -> (Ptr (t s a b) -> IO c) -> IO c\nwithTransformer t = bracket\n-}\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform :: TransformerFunc\n\n\n-- ############################################################################\n-- GenImgProjTransformer\n-- ############################################################################\n\ndata GenImgProjTransformer s a b =\n GenImgProjTransformer {\n giptSrcDs :: Maybe (RODataset s a)\n , giptDstDs :: Maybe (RWDataset s b)\n , giptSrcSrs :: Maybe SpatialReference\n , giptDstSrs :: Maybe SpatialReference\n , giptUseGCP :: Bool\n , giptMaxError :: Double\n , giptOrder :: Int\n }\n\ninstance Default (GenImgProjTransformer s a b) where\n def = GenImgProjTransformer {\n giptSrcDs = Nothing\n , giptDstDs = Nothing\n , giptSrcSrs = Nothing\n , giptDstSrs = Nothing\n , giptUseGCP = True\n , giptMaxError = 1\n , giptOrder = 0\n }\n\ninstance Transformer GenImgProjTransformer where\n transformerFunc _ = c_GDALGenImgProjTransform\n createTransformer dsPtr GenImgProjTransformer{..}\n = throwIfError \"GDALCreateGenImgProjTransformer\" $\n withMaybeSRAsCString giptSrcSrs $ \\sSr ->\n withMaybeSRAsCString giptDstSrs $ \\dSr ->\n c_createGenImgProjTransformer\n (maybe dsPtr unDataset giptSrcDs)\n sSr\n (maybe nullPtr unDataset giptDstDs)\n dSr\n (fromBool giptUseGCP)\n (realToFrac giptMaxError)\n (fromIntegral giptOrder)\n\nforeign import ccall safe \"gdal_alg.h GDALCreateGenImgProjTransformer\"\n c_createGenImgProjTransformer\n :: Ptr (RODataset s a) -> CString -> Ptr (Dataset s m b) -> CString -> CInt\n -> CDouble -> CInt -> IO (Ptr (GenImgProjTransformer s a b))\n\n-- ############################################################################\n-- GenImgProjTransformer2\n-- ############################################################################\n\ndata GenImgProjTransformer2 s a b =\n GenImgProjTransformer2 {\n gipt2SrcDs :: Maybe (RODataset s a)\n , gipt2DstDs :: Maybe (RWDataset s b)\n , gipt2Options :: OptionList\n }\n\ninstance Default (GenImgProjTransformer2 s a b) where\n def = GenImgProjTransformer2 {\n gipt2SrcDs = Nothing\n , gipt2DstDs = Nothing\n , gipt2Options = []\n }\n\ninstance Transformer GenImgProjTransformer2 where\n transformerFunc _ = c_GDALGenImgProjTransform\n createTransformer dsPtr GenImgProjTransformer2{..}\n = throwIfError \"GDALCreateGenImgProjTransformer2\" $\n withOptionList gipt2Options $ \\opts ->\n c_createGenImgProjTransformer2\n (maybe dsPtr unDataset gipt2SrcDs)\n (maybe nullPtr unDataset gipt2DstDs)\n opts\n\nforeign import ccall safe \"gdal_alg.h GDALCreateGenImgProjTransformer2\"\n c_createGenImgProjTransformer2\n :: Ptr (RODataset s a) -> Ptr (RWDataset s b) -> Ptr CString\n -> IO (Ptr (GenImgProjTransformer2 s a b))\n\n-- ############################################################################\n-- GenImgProjTransformer3\n-- ############################################################################\n\ndata GenImgProjTransformer3 s a b =\n GenImgProjTransformer3 {\n gipt3SrcSrs :: Maybe SpatialReference\n , gipt3DstSrs :: Maybe SpatialReference\n , gipt3SrcGt :: Maybe Geotransform\n , gipt3DstGt :: Maybe Geotransform\n }\n\ninstance Default (GenImgProjTransformer3 s a b) where\n def = GenImgProjTransformer3 {\n gipt3SrcSrs = Nothing\n , gipt3DstSrs = Nothing\n , gipt3SrcGt = Nothing\n , gipt3DstGt = Nothing\n }\n\ninstance Transformer GenImgProjTransformer3 where\n transformerFunc _ = c_GDALGenImgProjTransform\n createTransformer _ GenImgProjTransformer3{..}\n = throwIfError \"GDALCreateGenImgProjTransformer3\" $\n withMaybeSRAsCString gipt3SrcSrs $ \\sSr ->\n withMaybeSRAsCString gipt3DstSrs $ \\dSr ->\n withMaybeGeotransformPtr gipt3SrcGt $ \\sGt ->\n withMaybeGeotransformPtr gipt3DstGt $ \\dGt ->\n c_createGenImgProjTransformer3 sSr sGt dSr dGt\n\nwithMaybeGeotransformPtr\n :: Maybe Geotransform -> (Ptr Geotransform -> IO a) -> IO a\nwithMaybeGeotransformPtr Nothing f = f nullPtr\nwithMaybeGeotransformPtr (Just g) f = alloca $ \\gp -> poke gp g >> f gp\n\nforeign import ccall safe \"gdal_alg.h GDALCreateGenImgProjTransformer3\"\n c_createGenImgProjTransformer3\n :: CString -> Ptr Geotransform -> CString -> Ptr Geotransform\n -> IO (Ptr (GenImgProjTransformer3 s a b))\n\n-- ############################################################################\n-- GDALRasterizeLayersBuf\n-- ############################################################################\n\nrasterizeLayersBuf\n :: forall s t a l. (GDALType a, Transformer t)\n => Size\n -> [ROLayer s l]\n -> SpatialReference\n -> Geotransform\n -> Maybe (t s a a)\n -> a\n -> a\n -> OptionList\n -> Maybe ProgressFun\n -> GDAL s (U.Vector (Value a))\nrasterizeLayersBuf\n size layers srs geotransform mTransformer nodataValue burnValue options\n progressFun = liftIO $ do\n ret <- withLockedLayerPtrs layers $ \\layerPtrs ->\n withArrayLen layerPtrs $ \\len lPtrPtr ->\n with geotransform $ \\gt ->\n withMaybeSRAsCString (Just srs) $ \\srsPtr ->\n withOptionList options $ \\opts ->\n withProgressFun progressFun $ \\pFun -> do\n mVec <- Stm.replicate (sizeLen size) nodataValue\n Stm.unsafeWith mVec $ \\vecPtr ->\n c_rasterizeLayersBuf vecPtr nx ny dt 0 0 (fromIntegral len)\n lPtrPtr srsPtr gt nullFunPtr nullPtr bValue opts pFun nullPtr\n return mVec\n maybe (throwBindingException RasterizeStopped)\n (liftM (stToUValue . St.map toValue) . St.unsafeFreeze) ret\n where\n toValue v = if toNodata v == ndValue then NoData else Value v\n dt = fromEnumC (datatype (Proxy :: Proxy a))\n bValue = toNodata burnValue\n ndValue = toNodata nodataValue\n XY nx ny = fmap fromIntegral size\n\nforeign import ccall safe \"gdal_alg.h GDALRasterizeLayersBuf\"\n c_rasterizeLayersBuf\n :: Ptr a -- pData\n -> CInt -- eBufXSize\n -> CInt -- eBufYSize\n -> CInt -- eBufType\n -> CInt -- nPixelSpace\n -> CInt -- nLineSpace\n -> CInt -- nLayerCount\n -> Ptr (Ptr (ROLayer s b)) -- pahLayers\n -> CString -- pszDstProjection\n -> Ptr Geotransform -- padfDstGeoTransform\n -> TransformerFunc -- pfnTransformer\n -> Ptr () -- pTransformerArg\n -> CDouble -- dfBurnValue\n -> Ptr CString -- papszOptions\n -> ProgressFunPtr -- pfnProgress\n -> Ptr () -- pProgressArg\n -> IO CInt\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c6ae153e5e7a5ca6cae1ece67f5d50efa23400fd","subject":"gio: S.G.File: only export File(..) and FileClass(..), not all of module S.G.Types","message":"gio: S.G.File: only export File(..) and FileClass(..), not all of module S.G.Types\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0b8bf0810700b4687a6ccdd872ce916b567aac12","subject":"[project @ 2002-12-16 16:27:14 by as49] Removed an empty line.","message":"[project @ 2002-12-16 16:27:14 by as49]\nRemoved an empty line.\n","repos":"vincenthz\/webkit","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General@\n--\n-- Author : Axel Simon\n--\t Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.9 $ from $Date: 2002\/12\/16 16:27:14 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\nmodule General(\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport LocalData(newIORef, readIORef, writeIORef)\nimport Exception (ioError, Exception(ErrorCall))\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @function getDefaultLanguage@ 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 <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @function initGUI@ 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: @literal ErrorCall \"Cannot initialize GUI.\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\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 peekCString addrs'\n else ioError (ErrorCall \"Cannot initialize GUI.\")\n\n-- @function eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @function mainGUI@ Run GTK+'s main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- @function mainLevel@ Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call \n-- @ref function loopIteration@ to keep the GUI responsive. Each time\n-- the main loop is restarted this way, the main loop counter is\n-- increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @function mainQuit@ Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @function mainIteration@ Process an event, block if necessary.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @function mainIterationDo@ Process a single event.\n--\n-- * Called with @literal True@, this function behaves as\n-- @ref function loopIteration@ in that it waits until an event is available\n-- for processing. The function will return immediately, if passed\n-- @literal False@.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\n\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @function grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @function grabGetCurrent@ 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-- @function grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @function timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @function timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @function idleAdd@ Add a callback that is called whenever the system is\n-- idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @function idleRemove@ Remove a previously added idle handler by its\n-- @ref type TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General@\n--\n-- Author : Axel Simon\n--\t Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.8 $ from $Date: 2002\/12\/03 13:20:07 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, inputAdd, inputRemove\n--\nmodule General(\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify,\n timeoutAdd,\n timeoutRemove,\n idleAdd,\n idleRemove,\n HandlerId\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport LocalData(newIORef, readIORef, writeIORef)\nimport Exception (ioError, Exception(ErrorCall))\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @function getDefaultLanguage@ 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 <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @function initGUI@ Initialize the GUI binding.\n--\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: @literal ErrorCall \"Cannot initialize GUI.\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\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 peekCString addrs'\n else ioError (ErrorCall \"Cannot initialize GUI.\")\n\n-- @function eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @function mainGUI@ Run GTK+'s main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- @function mainLevel@ Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call \n-- @ref function loopIteration@ to keep the GUI responsive. Each time\n-- the main loop is restarted this way, the main loop counter is\n-- increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @function mainQuit@ Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @function mainIteration@ Process an event, block if necessary.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @function mainIterationDo@ Process a single event.\n--\n-- * Called with @literal True@, this function behaves as\n-- @ref function loopIteration@ in that it waits until an event is available\n-- for processing. The function will return immediately, if passed\n-- @literal False@.\n--\n-- * Returns @literal True@ if the @ref function loopQuit@ was called while\n-- processing the event.\n--\n\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @function grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @function grabGetCurrent@ 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-- @function grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @function timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @function timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @function idleAdd@ Add a callback that is called whenever the system is\n-- idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @function idleRemove@ Remove a previously added idle handler by its\n-- @ref type TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"511e7d7b192c07aebbd6cf8642f79a1b621e20c4","subject":"UncommentGValueCharFunctions","message":"UncommentGValueCharFunctions\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"glib\/System\/Glib\/GValueTypes.chs","new_file":"glib\/System\/Glib\/GValueTypes.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetUChar,\n valueGetUChar,\n valueSetChar,\n valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue (fromIntegral value)\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n liftM fromIntegral $ {# call unsafe value_get_uchar #} gvalue\n\n--these belong somewhere else, are in new c2hs's C2HS module\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\n--valueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar :: GValue -> Char -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue (cFromEnum value)\n\n--valueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar :: GValue -> IO Char\nvalueGetChar gvalue =\n liftM cToEnum $ {# call unsafe value_get_char #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the \n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n-- valueSetUChar,\n-- valueGetUChar,\n-- valueSetChar,\n-- valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\n{-\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue value\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n {# call unsafe value_get_uchar #} gvalue\n\nvalueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue value\n\nvalueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar gvalue =\n {# call unsafe value_get_char #} gvalue\n-}\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"20333c2fd4b9ba22f8f2b1e42bee94f04a6cdbf4","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","repos":"vincenthz\/webkit","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":"99d9a1577f7d76b194bbe7561d2f297b37503239","subject":"Added comment.","message":"Added comment.\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Bindings\/MPI\/Internal.chs","new_file":"src\/Bindings\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n (Comm, Datatype, Status (..), init, finalize, send, recv, commWorld, commRank, int) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\ntype Datatype = {# type MPI_Datatype #}\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\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_int\" int :: Datatype\n\n{# fun unsafe init_wrapper as init {} -> `Int' #}\n\n{# fun unsafe Finalize as ^ {} -> `Int' #}\n\nwithStorable :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithStorable x f = alloca (\\ptr -> poke ptr x >> f ptr)\n\nwithStorableCast :: Storable a => a -> (Ptr c -> IO b) -> IO b\nwithStorableCast x f = withStorable x (f . castPtr)\n\n-- int MPI_Comm_rank(MPI_Comm comm, int *rank)\n{# fun unsafe Comm_rank as ^ { id `Comm', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)\n{# fun unsafe Send as ^ `Storable a' => { withStorableCast* `a', `Int', id `Datatype', `Int', `Int', id `Comm' } -> `Int' #}\n\n-- int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)\n-- recv = {# call unsafe MPI_Recv as ^ #}\n-- XXX this should really make the storable thing an output.\n{# fun unsafe Recv as ^ `Storable a' => { withStorableCast* `a', `Int', id `Datatype', `Int', `Int', id `Comm', alloca- `Status' peek* } -> `Int' #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n (Comm, Datatype, Status (..), init, finalize, send, recv, commWorld, commRank, int) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\ntype Datatype = {# type MPI_Datatype #}\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\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_int\" int :: Datatype\n\n{# fun unsafe init_wrapper as init {} -> `Int' #}\n\n{# fun unsafe Finalize as ^ {} -> `Int' #}\n\nwithStorable :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithStorable x f = alloca (\\ptr -> poke ptr x >> f ptr)\n\nwithStorableCast :: Storable a => a -> (Ptr c -> IO b) -> IO b\nwithStorableCast x f = withStorable x (f . castPtr)\n\n-- int MPI_Comm_rank(MPI_Comm comm, int *rank)\n{# fun unsafe Comm_rank as ^ { id `Comm', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)\n{# fun unsafe Send as ^ `Storable a' => { withStorableCast* `a', `Int', id `Datatype', `Int', `Int', id `Comm' } -> `Int' #}\n\n-- int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)\n-- recv = {# call unsafe MPI_Recv as ^ #}\n{# fun unsafe Recv as ^ `Storable a' => { withStorableCast* `a', `Int', id `Datatype', `Int', `Int', id `Comm', alloca- `Status' peek* } -> `Int' #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"4369eb92d2a4a520a79dbdf53ab67e09580157d9","subject":"rename, more understandable when using top-level export","message":"rename, more understandable when using top-level export\n\nIgnore-this: 2e1e797ad24ed0c2e9b2ac1dd0486d69\n\ndarcs-hash:20091211002143-9241b-fdc7b4566e14d722cd91daf16406d06bbf6c7a0c.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Device.chs","new_file":"Foreign\/CUDA\/Driver\/Device.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device\n (\n Device(..), -- should be exported abstractly\n DeviceProperties(..), DeviceAttribute(..), InitFlag,\n\n initialise, capability, device, attribute, count, name, props, totalMem\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as DeviceAttribute\n { underscoreToCase }\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> DeviceProperties nocode #}\n\n\n-- |\n-- Properties of the compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n maxThreadsPerBlock :: Int, -- ^ Maximum number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Maximum size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Maximum size of each dimension of a grid\n sharedMemPerBlock :: Int, -- ^ Shared memory available per block in bytes\n totalConstantMemory :: Int, -- ^ Constant memory available on device in bytes\n warpSize :: Int, -- ^ Warp size in threads (SIMD width)\n memPitch :: Int, -- ^ Maximum pitch in bytes allowed by memory copies\n regsPerBlock :: Int, -- ^ 32-bit registers available per block\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n textureAlign :: Int -- ^ Alignment requirement for textures\n }\n deriving (Show)\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset' :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset' :: Ptr CInt)\n\n return DeviceProperties\n {\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n sharedMemPerBlock = sm,\n totalConstantMemory = cm,\n warpSize = ws,\n memPitch = mp,\n regsPerBlock = rb,\n clockRate = cl,\n textureAlign = ta\n }\n\n-- |\n-- Possible option flags for CUDA initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata InitFlag\n\ninstance Enum InitFlag where\n\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. Must be called before any other driver\n-- function.\n--\ninitialise :: [InitFlag] -> IO (Maybe String)\ninitialise flags = nothingIfOk `fmap` cuInit flags\n\n{# fun unsafe cuInit\n { combineBitMasks `[InitFlag]' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\ncapability :: Device -> IO (Either String Double)\ncapability dev =\n (\\(s,a,b) -> resultIfOk (s,cap a b)) `fmap` cuDeviceComputeCapability dev\n where\n cap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a device handle\n--\ndevice :: Int -> IO (Either String Device)\ndevice d = resultIfOk `fmap` cuDeviceGet d\n\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Return the selected attribute for the given device\n--\nattribute :: Device -> DeviceAttribute -> IO (Either String Int)\nattribute d a = resultIfOk `fmap` cuDeviceGetAttribute a d\n\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `DeviceAttribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cuDeviceGetCount\n\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Name of the device\n--\nname :: Device -> IO (Either String String)\nname d = resultIfOk `fmap` cuDeviceGetName d\n\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\nprops :: Device -> IO (Either String DeviceProperties)\nprops d = resultIfOk `fmap` cuDeviceGetProperties d\n\n{# fun unsafe cuDeviceGetProperties\n { alloca- `DeviceProperties' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Total memory available on the device (bytes)\n--\ntotalMem :: Device -> IO (Either String Int)\ntotalMem d = resultIfOk `fmap` cuDeviceTotalMem d\n\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device\n (\n Device(..), -- should be exported abstractly\n DeviceProperties(..), DeviceAttribute(..), InitFlag,\n\n initialise, capability, get, attribute, count, name, props, totalMem\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as DeviceAttribute\n { underscoreToCase }\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> DeviceProperties nocode #}\n\n\n-- |\n-- Properties of the compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n maxThreadsPerBlock :: Int, -- ^ Maximum number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Maximum size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Maximum size of each dimension of a grid\n sharedMemPerBlock :: Int, -- ^ Shared memory available per block in bytes\n totalConstantMemory :: Int, -- ^ Constant memory available on device in bytes\n warpSize :: Int, -- ^ Warp size in threads (SIMD width)\n memPitch :: Int, -- ^ Maximum pitch in bytes allowed by memory copies\n regsPerBlock :: Int, -- ^ 32-bit registers available per block\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n textureAlign :: Int -- ^ Alignment requirement for textures\n }\n deriving (Show)\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset' :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset' :: Ptr CInt)\n\n return DeviceProperties\n {\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n sharedMemPerBlock = sm,\n totalConstantMemory = cm,\n warpSize = ws,\n memPitch = mp,\n regsPerBlock = rb,\n clockRate = cl,\n textureAlign = ta\n }\n\n-- |\n-- Possible option flags for CUDA initialisation. Dummy instance until the API\n-- exports actual option values.\n--\ndata InitFlag\n\ninstance Enum InitFlag where\n\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. Must be called before any other driver\n-- function.\n--\ninitialise :: [InitFlag] -> IO (Maybe String)\ninitialise flags = nothingIfOk `fmap` cuInit flags\n\n{# fun unsafe cuInit\n { combineBitMasks `[InitFlag]' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\ncapability :: Device -> IO (Either String Double)\ncapability dev =\n (\\(s,a,b) -> resultIfOk (s,cap a b)) `fmap` cuDeviceComputeCapability dev\n where\n cap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a device handle\n--\nget :: Int -> IO (Either String Device)\nget d = resultIfOk `fmap` cuDeviceGet d\n\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Return the selected attribute for the given device\n--\nattribute :: Device -> DeviceAttribute -> IO (Either String Int)\nattribute d a = resultIfOk `fmap` cuDeviceGetAttribute a d\n\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `DeviceAttribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cuDeviceGetCount\n\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Name of the device\n--\nname :: Device -> IO (Either String String)\nname d = resultIfOk `fmap` cuDeviceGetName d\n\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\nprops :: Device -> IO (Either String DeviceProperties)\nprops d = resultIfOk `fmap` cuDeviceGetProperties d\n\n{# fun unsafe cuDeviceGetProperties\n { alloca- `DeviceProperties' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Total memory available on the device (bytes)\n--\ntotalMem :: Device -> IO (Either String Int)\ntotalMem d = resultIfOk `fmap` cuDeviceTotalMem d\n\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d70ac08eb56081e81ef7799b83c0eeaa921b8628","subject":"gio: don't use Control.Monad.>=> (it's not in ghc-6.6 or earlier)","message":"gio: don't use Control.Monad.>=> (it's not in ghc-6.6 or earlier)\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"62ad18c013520b6550db1b25c68bb323599ed71b","subject":"gstreamer: fix types for event handlers in Element.chs","message":"gstreamer: fix types for event handlers in Element.chs\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" 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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"3183f2ff0cd3fec3f7f6fe334e6fc7bf8118a146","subject":"Add function sourceCompletionProviderGetActivation","message":"Add function sourceCompletionProviderGetActivation\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionProvider.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderGetActivation,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.SourceView.Enums\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Get with what kind of activation the provider should be activated.\nsourceCompletionProviderGetActivation :: SourceCompletionProviderClass scp => scp\n -> IO SourceCompletionActivation\nsourceCompletionProviderGetActivation scp =\n liftM (toEnum . fromIntegral) $\n {#call gtk_source_completion_provider_get_activation #}\n (toSourceCompletionProvider scp)\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionProvider\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionProvider (\n-- * Description\n-- | You must implement this interface to provide proposals to 'SourceCompletion'\n\n-- * Types \n SourceCompletionProvider,\n SourceCompletionProviderClass,\n\n-- * Methods\n sourceCompletionProviderGetName,\n sourceCompletionProviderGetIcon,\n sourceCompletionProviderGetInteractiveDelay,\n sourceCompletionProviderGetPriority,\n sourceCompletionProviderGetInfoWidget,\n sourceCompletionProviderPopulate,\n sourceCompletionProviderActivateProposal,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the name of the provider. This should be a translatable name for display to the user. For\n-- example: _(\"Document word completion provider\"). \nsourceCompletionProviderGetName :: SourceCompletionProviderClass scp => scp \n -> IO String -- ^ returns A new string containing the name of the provider. \nsourceCompletionProviderGetName scp =\n {#call gtk_source_completion_provider_get_name #}\n (toSourceCompletionProvider scp)\n >>= peekUTFString\n\n-- | Get the icon of the provider.\nsourceCompletionProviderGetIcon :: SourceCompletionProviderClass scp => scp \n -> IO (Maybe Pixbuf)\nsourceCompletionProviderGetIcon scp =\n maybeNull (makeNewGObject mkPixbuf) $\n {#call gtk_source_completion_provider_get_icon #}\n (toSourceCompletionProvider scp)\n\n-- | Get the delay in milliseconds before starting interactive completion for this provider. A value of\n-- -1 indicates to use the default value as set by 'autoCompleteDelay'.\nsourceCompletionProviderGetInteractiveDelay :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the interactive delay in milliseconds. \nsourceCompletionProviderGetInteractiveDelay scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_interactive_delay #}\n (toSourceCompletionProvider scp)\n\n-- | Get the provider priority. The priority determines the order in which proposals appear in the\n-- completion popup. Higher priorities are sorted before lower priorities. The default priority is 0.\nsourceCompletionProviderGetPriority :: SourceCompletionProviderClass scp => scp \n -> IO Int -- ^ returns the provider priority. \nsourceCompletionProviderGetPriority scp =\n liftM fromIntegral $\n {#call gtk_source_completion_provider_get_priority #}\n (toSourceCompletionProvider scp)\n \n-- | Get a customized info widget to show extra information of a proposal. This allows for customized\n-- widgets on a proposal basis, although in general providers will have the same custom widget for all\n-- their proposals and proposal can be ignored. The implementation of this function is optional. If\n-- implemented, 'sourceCompletionProviderUpdateInfo' MUST also be implemented. If not\n-- implemented, the default 'sourceCompletionProposalGetInfo' will be used to display extra\n-- information about a 'SourceCompletionProposal'.\nsourceCompletionProviderGetInfoWidget :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal -- ^ @proposal@ The currently selected 'SourceCompletionProposal' \n -> IO Widget -- ^ returns a custom 'Widget' to show extra information about proposal. \nsourceCompletionProviderGetInfoWidget scp proposal =\n makeNewObject mkWidget $\n {#call gtk_source_completion_provider_get_info_widget #}\n (toSourceCompletionProvider scp)\n proposal\n\n-- | Populate context with proposals from provider\nsourceCompletionProviderPopulate :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionContext\n -> IO ()\nsourceCompletionProviderPopulate scp context =\n {#call gtk_source_completion_provider_populate #}\n (toSourceCompletionProvider scp)\n context\n\n-- | Activate proposal at iter. When this functions returns 'False', the default activation of proposal\n-- will take place which replaces the word at iter with the label of proposal.\nsourceCompletionProviderActivateProposal :: SourceCompletionProviderClass scp => scp\n -> SourceCompletionProposal\n -> TextIter\n -> IO Bool -- ^ returns 'True' to indicate that the proposal activation has been handled, 'False' otherwise.\nsourceCompletionProviderActivateProposal scp proposal iter =\n liftM toBool $\n {#call gtk_source_completion_provider_activate_proposal #}\n (toSourceCompletionProvider scp)\n proposal\n iter","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"37f823a01b0925d77eee984450d7c5f1e0f95b8b","subject":"combined allocation and marshalling","message":"combined allocation and marshalling\n\nIgnore-this: 16b0f88ef29f8b8c25a19c414e155b9\n\ndarcs-hash:20090722042758-115f9-c3bd2f4275aeb65118a5d163a0c4742491d54e47.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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream =\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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Data.Int\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.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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream =\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":"ba2de956e8287e5b454ae09e8356ba441dbba815","subject":"gstreamer: M.S.G.Core.Bus documentation cleanup","message":"gstreamer: M.S.G.Core.Bus documentation cleanup\n\ndarcs-hash:20080116040324-21862-6948221bdaeaed9cde0ce6fcd5c806c0ad22084d.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"8acca8143b41f1b4e6a890ea0c679ec9a0161db3","subject":"add CLError type","message":"add CLError type\n","repos":"IFCA\/opencl,Delan90\/opencl,Delan90\/opencl,IFCA\/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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLImageFormat(..), CLPlatformInfo(..),\n -- * Functions\n getProfilingInfoValue, getImageFormat, getDeviceTypeValue, \n getDeviceLocalMemType, getDeviceMemCacheType, getCommandType, \n getCommandExecutionStatus, bitmaskToDeviceTypes, bitmaskFromDeviceTypes, \n bitmaskToCommandQueueProperties, bitmaskFromCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, getPlatformInfoValue )\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 CLError {\n CLBUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n CLCOMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n CLDEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n CLDEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n CLIMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n CLIMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n CLINVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n CLINVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n CLINVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n CLINVALID_BINARY=CL_INVALID_BINARY,\n CLINVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n CLINVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n CLINVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n CLINVALID_CONTEXT=CL_INVALID_CONTEXT,\n CLINVALID_DEVICE=CL_INVALID_DEVICE,\n CLINVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n CLINVALID_EVENT=CL_INVALID_EVENT,\n CLINVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n CLINVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n CLINVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n CLINVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n CLINVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n CLINVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n CLINVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n CLINVALID_KERNEL=CL_INVALID_KERNEL,\n CLINVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n CLINVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n CLINVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n CLINVALID_OPERATION=CL_INVALID_OPERATION,\n CLINVALID_PLATFORM=CL_INVALID_PLATFORM,\n CLINVALID_PROGRAM=CL_INVALID_PROGRAM,\n CLINVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n CLINVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n CLINVALID_SAMPLER=CL_INVALID_SAMPLER,\n CLINVALID_VALUE=CL_INVALID_VALUE,\n CLINVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n CLINVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n CLINVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n CLMAP_FAILURE=CL_MAP_FAILURE,\n CLMEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n CLMEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n CLOUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n CLOUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n CLPROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n CLSUCCESS=CL_SUCCESS\n };\n#endc\n\n\n{-| \n* 'CLBUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CLCOMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CLDEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CLDEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CLIMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CLIMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CLINVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CLINVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CLINVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CLINVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CLINVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CLINVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CLINVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CLINVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CLINVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CLINVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CLINVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CLINVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CLINVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CLINVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CLINVALID_HOST_PTR', Returned if host_ptr is NULL and 'CLMEM_USE_HOST_PTR'\nor 'CLMEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CLMEM_COPY_HOST_PTR' or 'CLMEM_USE_HOST_PTR' are not set in flags.\n\n * 'CLINVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CLINVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CLINVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CLINVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CLINVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CLINVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CLINVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CLINVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CLINVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CLINVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CLINVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CLINVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CLINVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CLINVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CLINVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CLINVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CLINVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CLMAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CLMEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CLMEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CLOUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CLPROFILING_INFO_NOT_AVAILABLE', Returned if the 'CLQUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CLSUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} deriving( Show ) #}\n\ngetPlatformInfoValue :: CLPlatformInfo -> CLPlatformInfo_\ngetPlatformInfoValue = fromIntegral . fromEnum\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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-- -----------------------------------------------------------------------------\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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLImageFormat(..), CLPlatformInfo(..),\n -- * Functions\n getProfilingInfoValue, getImageFormat, getDeviceTypeValue, \n getDeviceLocalMemType, getDeviceMemCacheType, getCommandType, \n getCommandExecutionStatus, bitmaskToDeviceTypes, bitmaskFromDeviceTypes, \n bitmaskToCommandQueueProperties, bitmaskFromCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, getPlatformInfoValue )\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-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n \n [@FULL_PROFILE@] If the implementation supports the OpenCL specification \n(functionality defined as part of the core specification and does not require \nany extensions to be supported).\n \n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n \n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} #}\n\ngetPlatformInfoValue :: CLPlatformInfo -> CLPlatformInfo_\ngetPlatformInfoValue = fromIntegral . fromEnum\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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-- -----------------------------------------------------------------------------\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8c43a4c1cfe18298748e526c883b3bf636a6cd6a","subject":"gstreamer: small fixes in M.S.G.Core.Event","message":"gstreamer: small fixes in M.S.G.Core.Event\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.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 object describing events that are passed up and down a pipeline.\nmodule Media.Streaming.GStreamer.Core.Event (\n\n-- * Detail\n\n -- | An 'Event' is a message that is passed up and down a pipeline.\n -- \n -- There are a number of predefined events and functions returning\n -- events. To send an event an application will usually use\n -- 'Media.Streaming.GStreamer.Core.Element.elementSendEvent', and\n -- elements will use\n -- 'Media.Streaming.GStreamer.Core.Pad.padSendEvent' or\n -- 'Media.Streaming.GStreamer.Core.padPushEvent'.\n -- \n -- \n\n-- * Types\n Event,\n EventClass,\n EventType(..),\n\n-- * Event Operations\n eventType,\n eventNewCustom,\n eventNewEOS,\n eventNewFlushStart,\n eventNewFlushStop,\n eventNewLatency,\n eventNewNavigation,\n eventNewNewSegment,\n eventNewNewSegmentFull,\n eventNewQOS,\n eventNewSeek,\n eventNewTag,\n eventParseBufferSize,\n eventParseLatency,\n eventParseNewSegment,\n eventParseNewSegmentFull,\n eventParseQOS,\n eventParseSeek,\n eventParseTag,\n eventTypeGetName,\n eventTypeGetFlags,\n ) where\n\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: EventClass event\n => event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject (toEvent event) cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: EventClass event\n => event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} (toEvent event)\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: EventClass event\n => event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} (toEvent event)\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: EventClass event\n => event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} (toEvent event)\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: EventClass event\n => event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} (toEvent event)\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: EventClass event\n => event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} (toEvent event)\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: EventClass event\n => event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} (toEvent event)\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: EventClass event\n => event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} (toEvent event) (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n | otherwise = Nothing\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\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.Event (\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: Event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject event cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: Event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} event\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: Event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} event\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: Event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} event\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: Event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} event\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: Event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} event\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: Event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} event\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: Event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} event (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"12c6b7aef82c38536bdef535b499e951d53c2c4b","subject":"Included roadmap for high level API","message":"Included roadmap for high level API\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 , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , csInsnOffset\n , CsErr(..)\n , csSupport\n , csOpen\n , csClose\n , csOption\n , csErrno\n , csStrerror\n , csDisasm\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\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, withCString)\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-- TODO: what is this SKIPDATA business whose callback function\n-- we happily omitted?\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 ({#offsetof cs_detail.groups_count#} + 1)\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr p)\n CsArchArm64 -> Arm64 <$> peek (castPtr p)\n CsArchArm -> Arm <$> peek (castPtr p)\n CsArchMips -> Mips <$> peek (castPtr p)\n CsArchPpc -> Ppc <$> peek (castPtr p)\n CsArchSparc -> Sparc <$> peek (castPtr p)\n CsArchSysz -> SysZ <$> peek (castPtr p)\n CsArchXcore -> XCore <$> peek (castPtr p)\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 :: 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 =<< {#get cs_insn->mnemonic#} p)\n <*> (peekCString =<< {#get cs_insn->op_str#} p)\n <*> (castPtr <$> {#get cs_insn->detail#} p >>= peek)\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 withCString m ({#set cs_insn->mnemonic#} p)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else withCString o ({#set cs_insn->op_str#} p)\n csDetailPtr <- castPtr <$> ({#get cs_insn->detail#} p)\n poke csDetailPtr d\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 <- mapM (peek . plusPtr resPtr . ({#sizeof cs_insn#} *)) [0..resNum]\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-- TODO: decide whether we want cs_disasm_iter\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 , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , csInsnOffset\n , CsErr(..)\n , csSupport\n , csOpen\n , csClose\n , csOption\n , csErrno\n , csStrerror\n , csDisasm\n , csFree\n , csMalloc\n , csRegName\n , csInsnName\n , csGroupName\n , csInsnGroup\n , csRegRead\n , csRegWrite\n , csOpCount\n , csOpIndex\n ) where\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, withCString)\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-- TODO: what is this SKIPDATA business whose callback function\n-- we happily omitted?\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 ({#offsetof cs_detail.groups_count#} + 1)\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr p)\n CsArchArm64 -> Arm64 <$> peek (castPtr p)\n CsArchArm -> Arm <$> peek (castPtr p)\n CsArchMips -> Mips <$> peek (castPtr p)\n CsArchPpc -> Ppc <$> peek (castPtr p)\n CsArchSparc -> Sparc <$> peek (castPtr p)\n CsArchSysz -> SysZ <$> peek (castPtr p)\n CsArchXcore -> XCore <$> peek (castPtr p)\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 :: 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 =<< {#get cs_insn->mnemonic#} p)\n <*> (peekCString =<< {#get cs_insn->op_str#} p)\n <*> (castPtr <$> {#get cs_insn->detail#} p >>= peek)\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 withCString m ({#set cs_insn->mnemonic#} p)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else withCString o ({#set cs_insn->op_str#} p)\n csDetailPtr <- castPtr <$> ({#get cs_insn->detail#} p)\n poke csDetailPtr d\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 <- mapM (peek . plusPtr resPtr . ({#sizeof cs_insn#} *)) [0..resNum]\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-- TODO: decide whether we want cs_disasm_iter\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":"8d4ce76c518af98a4418b3b532da07c150991029","subject":"Added CV.Transforms.gaussianPyramid","message":"Added CV.Transforms.gaussianPyramid\n","repos":"aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV,aleator\/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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n DIST_LABEL_CCOMP = CV_DIST_LABEL_CCOMP\n ,DIST_LABEL_PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\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#ifdef OpenCV24\n (fromIntegral . fromEnum $ DIST_LABEL_CCOMP)\n#endif\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 = 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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n DIST_LABEL_CCOMP = CV_DIST_LABEL_CCOMP\n ,DIST_LABEL_PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\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#ifdef OpenCV24\n (fromIntegral . fromEnum $ DIST_LABEL_CCOMP)\n#endif\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":"8d00d4f1bc58efa9a45f5609c1dbc23273fb42bb","subject":"Implement exponential backoff in polling hyperclient_loop","message":"Implement exponential backoff in polling hyperclient_loop\n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Client.chs","new_file":"src\/Database\/HyperDex\/Internal\/Client.chs","new_contents":"{-# LANGUAGE ViewPatterns #-}\n\nmodule Database.HyperDex.Internal.Client \n ( Hyperclient, Client\n , ConnectInfo (..)\n , defaultConnectInfo\n , ConnectOptions (..)\n , defaultConnectOptions\n , BackoffMethod (..)\n , Handle\n , Result, AsyncResult, AsyncResultHandle\n , connect, close\n , loopClient, loopClientUntil\n , withClient, withClientImmediate\n )\n where\n\n{# import Database.HyperDex.Internal.ReturnCode #}\nimport Database.HyperDex.Internal.Util\n\nimport Data.Maybe\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\nimport Control.Concurrent (yield, threadDelay)\nimport Control.Concurrent.MVar\n\nimport Data.Word (Word16)\n\nimport Data.Text.Encoding (encodeUtf8)\nimport qualified Data.Text as Text (pack) \n\nimport Data.Default\n\nimport Debug.Trace\n\n#include \"hyperclient.h\"\n\n{#pointer *hyperclient as Hyperclient #}\n\n-- | Parameters for connecting to a HyperDex cluster.\ndata ConnectInfo =\n ConnectInfo\n { connectHost :: String\n , connectPort :: Word16\n , connectOptions :: ConnectOptions\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectInfo where\n def = \n ConnectInfo\n { connectHost = \"127.0.0.1\"\n , connectPort = 1982\n , connectOptions = def\n }\n\ndefaultConnectInfo :: ConnectInfo\ndefaultConnectInfo = def\n\n-- | Additional options for connecting and managing the connection\n-- to a HyperDex cluster.\ndata ConnectOptions =\n ConnectOptions\n { backoff :: BackoffMethod\n , backoffCap :: Maybe Int\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectOptions where\n def =\n ConnectOptions\n { backoff = BackoffExponential 10 2 -- 10 * 2^n\n , backoffCap = Just 500000 -- Half a second.\n }\n\n-- | Sane defaults for HyperDex connection options.\ndefaultConnectOptions :: ConnectOptions\ndefaultConnectOptions = def\n\n-- | A backoff method controls how frequently the client polls internally.\n-- \n-- This is provided to allow fine-tuning performance. Do note that \n-- this does not affect any method the HyperClient C library uses to poll\n-- its connection to a HyperDex cluster.\n--\n-- All integer values are in microseconds.\ndata BackoffMethod\n -- | No delay is used except the thread is yielded.\n = BackoffYield\n -- | Delay a constant number of microseconds each inter.\n | BackoffConstant Int\n -- | Delay with an initial number of microseconds, increasing linearly by the second value. \n | BackoffLinear Int Int\n -- | Delay with an initial number of microseconds, increasing exponentially by the second value. \n | BackoffExponential Int Double\n deriving (Eq, Read, Show)\n\ntype HyperclientWrapper = MVar (Maybe Hyperclient, Map Handle (IO ()))\n\ndata ClientData =\n ClientData\n { hyperclientWrapper :: HyperclientWrapper\n , connectionInfo :: ConnectInfo\n }\n\n-- | A connection to a HyperDex cluster.\nnewtype Client = Client { unClientData :: ClientData } \n\n-- | Internal method for returning the (MVar) wrapped connection. \ngetClient :: Client -> HyperclientWrapper\ngetClient = hyperclientWrapper . unClientData\n\n-- | Get the connection info used for a 'Client'.\ngetConnectInfo :: Client -> ConnectInfo\ngetConnectInfo = connectionInfo . unClientData\n\n-- | Get the connection options for a 'Client'.\ngetConnectOptions :: Client -> ConnectOptions\ngetConnectOptions = connectOptions . getConnectInfo\n\n-- | Return value from hyperclient operations.\n--\n-- Per the specification, it's guaranteed to be a unique integer for\n-- each outstanding operation using a given HyperClient. In practice\n-- it is monotonically increasing while operations are outstanding,\n-- lower values are used first, and negative values represent an\n-- error.\ntype Handle = {# type int64_t #}\n\n-- | A return value from HyperDex.\ntype Result a = IO (Either ReturnCode a)\n\n-- | A return value used internally by HyperClient operations.\n--\n-- Internally the wrappers to the HyperDex library will return\n-- a computation that yields a 'Handle' referring to that request\n-- and a continuation that will force the request to return an \n-- error in the form of a ReturnCode or a result.\n--\n-- The result of forcing the result is undefined.\n-- The HyperClient and its workings are not party to the MVar locking\n-- mechanism, and the ReturnCode and\/or return value may be in the\n-- process of being modified when the computation is forced.\n--\n-- Consequently, the only safe way to use this is with a wrapper such\n-- as 'withClient', which only allows the continuation to be run after\n-- the HyperClient has returned the corresponding Handle or after the\n-- HyperClient has been destroyed.\ntype AsyncResultHandle a = IO (Handle, Result a)\n\n-- | A return value from HyperDex in an asynchronous wrapper.\n--\n-- The full type is an IO (IO (Either ReturnCode a)). Evaluating\n-- the result of an asynchronous call, such as the default get and\n-- put operations starts the request to the HyperDex cluster. Evaluating\n-- the result of that evaluation will poll internally, using the \n-- connection's 'BackoffMethod' until the result is available.\n--\n-- This API may be deprecated in favor of exclusively using MVars in\n-- a future version.\ntype AsyncResult a = IO (Result a)\n\n-- | Connect to a HyperDex cluster.\nconnect :: ConnectInfo -> IO Client\nconnect info = do\n hyperclient <- hyperclientCreate (encodeUtf8 . Text.pack . connectHost $ info) (connectPort info)\n clientData <- newMVar (Just hyperclient, Map.empty)\n return $\n Client\n $ ClientData\n { hyperclientWrapper = clientData \n , connectionInfo = info\n }\n\n\n-- | Close a connection and terminate any outstanding asynchronous\n-- requests.\n--\n-- \/Note:\/ This does force all asynchronous requests to complete\n-- immediately. Any outstanding requests at the time the 'Client'\n-- is closed ought to return a 'ReturnCode' indicating the failure\n-- condition, but the behavior is ultimately undefined. Any pending\n-- requests should be disregarded. \nclose :: Client -> IO ()\nclose (getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> error \"HyperDex client error - cannot close a client connection twice.\"\n (Just hc, handles) -> do\n hyperclientDestroy hc\n sequence_ $ Map.elems handles \n putMVar c (Nothing, Map.empty)\n\ndoExponentialBackoff :: Int -> Double -> (Int, BackoffMethod)\ndoExponentialBackoff b x = \n let result = ceiling (fromIntegral b ** x) in\n (result, BackoffExponential result x)\n\ncappedBackoff :: Int -> Maybe Int -> (Int, Bool)\ncappedBackoff n Nothing = (n, False)\ncappedBackoff n (Just c) | n < c = (n, False)\n | n >= c = (c, True)\n\nperformBackoff :: BackoffMethod -> Maybe Int -> IO (BackoffMethod)\nperformBackoff method cap = do\n let (delay, newBackoff) = case method of\n BackoffYield -> (0, method)\n BackoffConstant n -> (0, method)\n BackoffLinear m b -> (m, BackoffLinear (m+b) b)\n BackoffExponential b x -> doExponentialBackoff b x\n (backoff, capped) = cappedBackoff delay cap\n let delay = case backoff of\n 0 -> yield\n n -> threadDelay n\n next = case capped of\n True -> BackoffConstant backoff\n False -> newBackoff\n delay >> return next\n\n-- | Runs hyperclient_loop exactly once, setting the appropriate MVar.\nloopClient' :: Bool -> Client -> IO (Maybe Handle)\nloopClient' debug client@(getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> return Nothing\n (Just hc, handles) -> do\n -- TODO: Examine returnCode for things that might matter.\n (handle, returnCode) <- hyperclientLoop hc 0\n case returnCode of\n HyperclientSuccess -> do\n if debug\n then traceIO $ \"Recovering from failure, returncode: \" ++ show returnCode\n else return ()\n fromMaybe (return ()) $ Map.lookup handle handles\n putMVar c (Just hc, Map.delete handle handles)\n return $ Just handle\n HyperclientTimeout -> do\n putMVar c (Just hc, handles)\n loopClient' False client\n HyperclientNonepending -> do\n sequence_ $ Map.elems handles\n putMVar c (Just hc, Map.empty)\n return $ Just handle\n _ -> do\n traceIO $ \"Encountered \" ++ show returnCode\n putMVar c (Just hc, handles)\n loopClient' True client\n\nloopClient :: Client -> IO (Maybe Handle)\nloopClient = loopClient' False\n\n-- | Run hyperclient_loop at most N times or forever until a handle\n-- is returned.\nloopClientUntil :: Client -> BackoffMethod -> Handle -> Maybe Int -> MVar (Either ReturnCode a) -> IO (Bool)\nloopClientUntil _ _ _ (Just 0) _ = return False\n\nloopClientUntil client back h (Just n) v = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential backoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return True\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> do\n back' <- performBackoff back (backoffCap . getConnectOptions $ client)\n loopClientUntil client back' h (Just $ n - 1) v\n False -> return True\n\nloopClientUntil client back h (Nothing) v = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential backoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return False\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> do \n back' <- performBackoff back (backoffCap . getConnectOptions $ client)\n loopClientUntil client back' h (Nothing) v\n False -> return True\n\n-- | Peek at the value of an 'MVar' and return its contents if full.\n-- \n-- \/Note:\/ This isn't truly a reliable way of performing this operation\n-- as between the 'tryTakeMVar' and the 'putMVar', another thread could\n-- perform the 'putMVar'. However, it is implicitly guaranteed that the\n-- internal API will never have multiple-writer contention on the \n-- 'HyperclientWrapper'. Every operation performs a 'TakeMVar' before a\n-- 'PutMVar', and the surface area is small enough to guarantee that.\n--\n-- Per 'Control.Concurrent.MVar', this function is only atomic if there\n-- are no other producers for this 'MVar'.\npeekMVar :: MVar a -> IO (Maybe a)\npeekMVar m = do\n res <- tryTakeMVar m\n case res of\n Just r -> do\n putMVar m r\n return $ Just r\n Nothing -> return $ Nothing\n\n-- | Wrap a HyperClient request and wait until completion or failure.\nwithClientImmediate :: Client -> (Hyperclient -> IO a) -> IO a\nwithClientImmediate (getClient -> c) f =\n withMVar c $ \\value -> do\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, _) -> f hc\n\n-- | Wrap a Hyperclient request.\nwithClient :: Client -> (Hyperclient -> AsyncResultHandle a) -> AsyncResult a\nwithClient client@(getClient -> c) f = do\n value <- takeMVar c\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, handles) -> do\n (h, cont) <- f hc\n case h > 0 of\n True -> do\n v <- newEmptyMVar :: IO (MVar (Either ReturnCode a))\n putMVar c (Just hc, Map.insert h (cont >>= putMVar v) handles)\n return $ do\n _ <- loopClientUntil client (backoff . getConnectOptions $ client) h Nothing v \n res <- peekMVar v\n return $ fromMaybe (error \"This should not occur!\") res\n False -> do\n putMVar c (Just hc, handles)\n return cont\n\n-- | C wrapper for hyperclient_create. Creates a HyperClient given a host\n-- and a port.\n--\n-- C definition:\n-- \n-- > struct hyperclient*\n-- > hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: ByteString -> Word16 -> IO Hyperclient\nhyperclientCreate h port = withCBString h $ \\host -> {# call hyperclient_create #} host (fromIntegral port)\n\n-- | C wrapper for hyperclient_destroy. Destroys a HyperClient.\n--\n-- \/Note:\/ This does not ensure resources are freed. Any memory \n-- allocated as staging for incomplete requests will not be returned.\n--\n-- C definition:\n-- \n-- > void\n-- > hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: Hyperclient -> IO ()\nhyperclientDestroy client = do\n {# call hyperclient_destroy #} client\n\n-- | C wrapper for hyperclient_loop. Waits up to some number of\n-- milliseconds for a result before returning.\n--\n-- A negative 'Handle' return value indicates a failure condition\n-- or timeout, a positive value indicates completion of an asynchronous\n-- request.\n--\n-- C definition:\n--\n-- > int64_t\n-- > hyperclient_loop(struct hyperclient* client, int timeout,\n-- > enum hyperclient_returncode* status);\nhyperclientLoop :: Hyperclient -> Int -> IO (Handle, ReturnCode)\nhyperclientLoop client timeout =\n alloca $ \\returnCodePtr -> do\n handle <- {# call hyperclient_loop #} client (fromIntegral timeout) returnCodePtr\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n return (handle, returnCode)\n","old_contents":"{-# LANGUAGE ViewPatterns #-}\n\nmodule Database.HyperDex.Internal.Client \n ( Hyperclient, Client\n , ConnectInfo (..)\n , defaultConnectInfo\n , ConnectOptions (..)\n , defaultConnectOptions\n , BackoffMethod (..)\n , Handle\n , Result, AsyncResult, AsyncResultHandle\n , connect, close\n , loopClient, loopClientUntil\n , withClient, withClientImmediate\n )\n where\n\n{# import Database.HyperDex.Internal.ReturnCode #}\nimport Database.HyperDex.Internal.Util\n\nimport Data.Maybe\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\nimport Control.Concurrent.MVar\n\nimport Data.Word (Word16)\n\nimport Data.Text.Encoding (encodeUtf8)\nimport qualified Data.Text as Text (pack) \n\nimport Data.Default\n\nimport Debug.Trace\n\n#include \"hyperclient.h\"\n\n{#pointer *hyperclient as Hyperclient #}\n\n-- | Parameters for connecting to a HyperDex cluster.\ndata ConnectInfo =\n ConnectInfo\n { connectHost :: String\n , connectPort :: Word16\n , connectOptions :: ConnectOptions\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectInfo where\n def = \n ConnectInfo\n { connectHost = \"127.0.0.1\"\n , connectPort = 1982\n , connectOptions = def\n }\n\ndefaultConnectInfo :: ConnectInfo\ndefaultConnectInfo = def\n\n-- | Additional options for connecting and managing the connection\n-- to a HyperDex cluster.\ndata ConnectOptions =\n ConnectOptions\n { backoff :: BackoffMethod\n , backoffCap :: Maybe Int\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectOptions where\n def =\n ConnectOptions\n { backoff = BackoffExponential 10 2 -- 10 * 2^n\n , backoffCap = Just 500000 -- Half a second.\n }\n\n-- | Sane defaults for HyperDex connection options.\ndefaultConnectOptions :: ConnectOptions\ndefaultConnectOptions = def\n\n-- | A backoff method controls how frequently the client polls internally.\n-- \n-- This is provided to allow fine-tuning performance. Do note that \n-- this does not affect any method the HyperClient C library uses to poll\n-- its connection to a HyperDex cluster.\n--\n-- All integer values are in microseconds.\ndata BackoffMethod\n -- | No delay is used and the connection is polled until completion or failure.\n = BackoffNone\n -- | Delay a constant number of microseconds each inter.\n | BackoffConstant Int\n -- | Delay with an initial number of microseconds, increasing linearly by the second value. \n | BackoffLinear Int Int\n -- | Delay with an initial number of microseconds, increasing exponentially by the second value. \n | BackoffExponential Int Double\n deriving (Eq, Read, Show)\n\ntype HyperclientWrapper = MVar (Maybe Hyperclient, Map Handle (IO ()))\n\ndata ClientData =\n ClientData\n { hyperclientWrapper :: HyperclientWrapper\n , connectionInfo :: ConnectInfo\n }\n\n-- | A connection to a HyperDex cluster.\nnewtype Client = Client { unClientData :: ClientData } \n\n-- | Internal method for returning the (MVar) wrapped connection. \ngetClient :: Client -> HyperclientWrapper\ngetClient = hyperclientWrapper . unClientData\n\n-- | Return value from hyperclient operations.\n--\n-- Per the specification, it's guaranteed to be a unique integer for\n-- each outstanding operation using a given HyperClient. In practice\n-- it is monotonically increasing while operations are outstanding,\n-- lower values are used first, and negative values represent an\n-- error.\ntype Handle = {# type int64_t #}\n\n-- | A return value from HyperDex.\ntype Result a = IO (Either ReturnCode a)\n\n-- | A return value used internally by HyperClient operations.\n--\n-- Internally the wrappers to the HyperDex library will return\n-- a computation that yields a 'Handle' referring to that request\n-- and a continuation that will force the request to return an \n-- error in the form of a ReturnCode or a result.\n--\n-- The result of forcing the result is undefined.\n-- The HyperClient and its workings are not party to the MVar locking\n-- mechanism, and the ReturnCode and\/or return value may be in the\n-- process of being modified when the computation is forced.\n--\n-- Consequently, the only safe way to use this is with a wrapper such\n-- as 'withClient', which only allows the continuation to be run after\n-- the HyperClient has returned the corresponding Handle or after the\n-- HyperClient has been destroyed.\ntype AsyncResultHandle a = IO (Handle, Result a)\n\n-- | A return value from HyperDex in an asynchronous wrapper.\n--\n-- The full type is an IO (IO (Either ReturnCode a)). Evaluating\n-- the result of an asynchronous call, such as the default get and\n-- put operations starts the request to the HyperDex cluster. Evaluating\n-- the result of that evaluation will poll internally, using the \n-- connection's 'BackoffMethod' until the result is available.\n--\n-- This API may be deprecated in favor of exclusively using MVars in\n-- a future version.\ntype AsyncResult a = IO (Result a)\n\n-- | Connect to a HyperDex cluster.\nconnect :: ConnectInfo -> IO Client\nconnect info = do\n hyperclient <- hyperclientCreate (encodeUtf8 . Text.pack . connectHost $ info) (connectPort info)\n clientData <- newMVar (Just hyperclient, Map.empty)\n return $\n Client\n $ ClientData\n { hyperclientWrapper = clientData \n , connectionInfo = info\n }\n\n\n-- | Close a connection and terminate any outstanding asynchronous\n-- requests.\n--\n-- \/Note:\/ This does force all asynchronous requests to complete\n-- immediately. Any outstanding requests at the time the 'Client'\n-- is closed ought to return a 'ReturnCode' indicating the failure\n-- condition, but the behavior is ultimately undefined. Any pending\n-- requests should be disregarded. \nclose :: Client -> IO ()\nclose (getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> error \"HyperDex client error - cannot close a client connection twice.\"\n (Just hc, handles) -> do\n hyperclientDestroy hc\n sequence_ $ Map.elems handles \n putMVar c (Nothing, Map.empty)\n\n-- | Runs hyperclient_loop exactly once, setting the appropriate MVar.\nloopClient' :: Bool -> Client -> IO (Maybe Handle)\nloopClient' debug client@(getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> return Nothing\n (Just hc, handles) -> do\n -- TODO: Examine returnCode for things that might matter.\n (handle, returnCode) <- hyperclientLoop hc 0\n case returnCode of\n HyperclientSuccess -> do\n if debug\n then traceIO $ \"Recovering from failure, returncode: \" ++ show returnCode\n else return ()\n fromMaybe (return ()) $ Map.lookup handle handles\n putMVar c (Just hc, Map.delete handle handles)\n return $ Just handle\n HyperclientTimeout -> do\n putMVar c (Just hc, handles)\n loopClient' False client\n HyperclientNonepending -> do\n sequence_ $ Map.elems handles\n putMVar c (Just hc, Map.empty)\n return $ Just handle\n _ -> do\n traceIO $ \"Encountered \" ++ show returnCode\n putMVar c (Just hc, handles)\n loopClient' True client\n\nloopClient :: Client -> IO (Maybe Handle)\nloopClient = loopClient' False\n\n-- | Run hyperclient_loop at most N times or forever until a handle\n-- is returned.\nloopClientUntil :: Client -> Handle -> Maybe Int -> MVar (Either ReturnCode a) -> IO (Bool)\nloopClientUntil _ _ (Just 0) _ = return False\n\nloopClientUntil client h (Just n) v = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential backoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return True\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> loopClientUntil client h (Just $ n - 1) v \n False -> return True\n\nloopClientUntil client h (Nothing) v = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential backoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return False\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> loopClientUntil client h (Nothing) v \n False -> return True\n\n-- | Peek at the value of an 'MVar' and return its contents if full.\n-- \n-- \/Note:\/ This isn't truly a reliable way of performing this operation\n-- as between the 'tryTakeMVar' and the 'putMVar', another thread could\n-- perform the 'putMVar'. However, it is implicitly guaranteed that the\n-- internal API will never have multiple-writer contention on the \n-- 'HyperclientWrapper'. Every operation performs a 'TakeMVar' before a\n-- 'PutMVar', and the surface area is small enough to guarantee that.\n--\n-- Per 'Control.Concurrent.MVar', this function is only atomic if there\n-- are no other producers for this 'MVar'.\npeekMVar :: MVar a -> IO (Maybe a)\npeekMVar m = do\n res <- tryTakeMVar m\n case res of\n Just r -> do\n putMVar m r\n return $ Just r\n Nothing -> return $ Nothing\n\n-- | Wrap a HyperClient request and wait until completion or failure.\nwithClientImmediate :: Client -> (Hyperclient -> IO a) -> IO a\nwithClientImmediate (getClient -> c) f =\n withMVar c $ \\value -> do\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, _) -> f hc\n\n-- | Wrap a Hyperclient request.\nwithClient :: Client -> (Hyperclient -> AsyncResultHandle a) -> AsyncResult a\nwithClient client@(getClient -> c) f = do\n value <- takeMVar c\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, handles) -> do\n (h, cont) <- f hc\n case h > 0 of\n True -> do\n v <- newEmptyMVar :: IO (MVar (Either ReturnCode a))\n putMVar c (Just hc, Map.insert h (cont >>= putMVar v) handles)\n return $ do\n _ <- loopClientUntil client h Nothing v \n res <- peekMVar v\n return $ fromMaybe (error \"This should not occur!\") res\n False -> do\n putMVar c (Just hc, handles)\n return cont\n\n-- | C wrapper for hyperclient_create. Creates a HyperClient given a host\n-- and a port.\n--\n-- C definition:\n-- \n-- > struct hyperclient*\n-- > hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: ByteString -> Word16 -> IO Hyperclient\nhyperclientCreate h port = withCBString h $ \\host -> {# call hyperclient_create #} host (fromIntegral port)\n\n-- | C wrapper for hyperclient_destroy. Destroys a HyperClient.\n--\n-- \/Note:\/ This does not ensure resources are freed. Any memory \n-- allocated as staging for incomplete requests will not be returned.\n--\n-- C definition:\n-- \n-- > void\n-- > hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: Hyperclient -> IO ()\nhyperclientDestroy client = do\n {# call hyperclient_destroy #} client\n\n-- | C wrapper for hyperclient_loop. Waits up to some number of\n-- milliseconds for a result before returning.\n--\n-- A negative 'Handle' return value indicates a failure condition\n-- or timeout, a positive value indicates completion of an asynchronous\n-- request.\n--\n-- C definition:\n--\n-- > int64_t\n-- > hyperclient_loop(struct hyperclient* client, int timeout,\n-- > enum hyperclient_returncode* status);\nhyperclientLoop :: Hyperclient -> Int -> IO (Handle, ReturnCode)\nhyperclientLoop client timeout =\n alloca $ \\returnCodePtr -> do\n handle <- {# call hyperclient_loop #} client (fromIntegral timeout) returnCodePtr\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n return (handle, returnCode)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"4e1fe240bf705d4263e91fc60be25db90aed9687","subject":"error strings exist in constant memory, and is thus pure","message":"error strings exist in constant memory, and is thus pure\n\nIgnore-this: 4cd0d5bd1f8c86be933726d10f2f6984\n\ndarcs-hash:20090718051315-115f9-8fcfe986c7ab69a603777cf92f1e48324476a0f9.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Utils.chs","new_file":"Foreign\/CUDA\/Utils.chs","new_contents":"{-\n - Utilities\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Utils\n (\n getErrorString, resultIfOk, nothingIfOk\n )\n where\n\nimport Foreign.CUDA.Types\n\nimport Foreign.CUDA.Internal.C2HS\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Error Handling\n--------------------------------------------------------------------------------\n\n--\n-- Return the descriptive string associated with a particular error code.\n-- Logically, this must a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n{# fun pure unsafe GetErrorString as ^\n { cFromEnum `Result' } -> `String' #}\n\n\nresultIfOk :: (Result, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (getErrorString status)\n\nnothingIfOk :: Result -> Maybe String\nnothingIfOk = nothingIf (\/= Success) getErrorString\n\n","old_contents":"{-\n - Utilities\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Utils\n (\n resultIfSuccess, nothingIfSuccess\n )\n where\n\nimport Foreign.CUDA.Types\n\nimport Foreign.CUDA.Internal.C2HS\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Error Handling\n--------------------------------------------------------------------------------\n\n--\n-- Return the descriptive string associated with a particular error code\n--\n{# fun unsafe GetErrorString as ^\n { cFromEnum `Result' } -> `String' #}\n\n\nresultIfSuccess :: (Result, a) -> IO (Either String a)\nresultIfSuccess (status,result) =\n case status of\n Success -> (return.Right) result\n _ -> getErrorString status >>= (return.Left)\n\n\nnothingIfSuccess :: Result -> IO (Maybe String)\nnothingIfSuccess status =\n case status of\n Success -> return Nothing\n _ -> getErrorString status >>= (return.Just)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bd5adfa7a430772dc9cab3295afcae44b5f1a6e8","subject":"Remove a type signature of 'withBDD', since recent version of c2hs automatically generate it.","message":"Remove a type signature of 'withBDD', since recent version of c2hs automatically generate it.\n","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 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","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\nwithBDD :: BDD -> (Ptr BDD -> IO a) -> IO a\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":"bc64875fc4fa341a2c4a65018929c99868da5569","subject":"expose io funcs","message":"expose io funcs\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OSR.chs","new_file":"src\/GDAL\/Internal\/OSR.chs","new_contents":"{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule GDAL.Internal.OSR (\n SpatialReference\n , CoordinateTransformation\n , Projectable (..)\n\n , srsFromWkt\n , srsFromProj4\n , srsFromEPSG\n , srsFromEPSGIO\n , srsFromXML\n\n , srsToWkt\n , srsToProj4\n , srsToXML\n\n , isGeographic\n , isLocal\n , isProjected\n , isSameGeogCS\n , isSame\n\n , getAngularUnits\n , getLinearUnits\n\n , coordinateTransformation\n , coordinateTransformationIO\n\n , cleanup\n , initialize\n , srsFromWktIO\n , withSpatialReference\n , withMaybeSRAsCString\n , withMaybeSpatialReference\n , maybeSpatialReferenceFromCString\n , withCoordinateTransformation\n , newSpatialRefHandle\n , newSpatialRefBorrowedHandle\n , maybeNewSpatialRefHandle\n , maybeNewSpatialRefBorrowedHandle\n) where\n\n#include \"ogr_srs_api.h\"\n\n{# context lib = \"gdal\" prefix = \"OSR\" #}\n\nimport Control.Monad.Catch (throwM, mask_, try)\nimport Control.Monad (liftM, (>=>), when, void)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\n\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Storable as St\n\nimport Foreign.C.String (CString, peekCString)\nimport Foreign.C.Types (CInt(..), CDouble(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLString (peekCPLString)\n\n{#pointer OGRSpatialReferenceH as SpatialReference foreign newtype#}\n\ninstance Show SpatialReference where\n show = show . srsToWkt\n\nsrsToWkt :: SpatialReference -> ByteString\nsrsToWkt s = exportWith fun s\n where\n fun s' p = {#call unsafe ExportToPrettyWkt as ^#} s' p 1\n\nsrsToProj4 :: SpatialReference -> ByteString\nsrsToProj4 = exportWith {#call unsafe ExportToProj4 as ^#}\n\nsrsToXML :: SpatialReference -> ByteString\nsrsToXML = exportWith fun\n where\n fun s' p = {#call unsafe ExportToXML as ^#} s' p (castPtr nullPtr)\n\nexportWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CInt)\n -> SpatialReference\n -> ByteString\nexportWith fun srs =\n unsafePerformIO $\n withSpatialReference srs $ \\pSrs ->\n peekCPLString $\n checkOGRError \"srsTo\" . fun pSrs\n{-# NOINLINE exportWith #-}\n\n\nforeign import ccall \"ogr_srs_api.h &OSRRelease\"\n c_release :: FunPtr (Ptr SpatialReference -> IO ())\n\nnewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefHandle = maybeNewSpatialRefHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefHandle io =\n mask_ $ do\n p <- io\n if p==nullPtr\n then return Nothing\n else liftM (Just . SpatialReference) (newForeignPtr c_release p)\n\nnewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefBorrowedHandle =\n maybeNewSpatialRefBorrowedHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefBorrowedHandle alloc = maybeNewSpatialRefHandle $ do\n p <- alloc\n when (p \/= nullPtr) (void ({#call unsafe OSRReference as ^#} p))\n return p\n\nemptySpatialRef :: IO SpatialReference\nemptySpatialRef =\n newSpatialRefHandle ({#call unsafe NewSpatialReference as ^#} nullPtr)\n\nsrsFromWkt, srsFromProj4, srsFromXML\n :: ByteString -> Either OGRException SpatialReference\nsrsFromWkt =\n unsafePerformIO . flip useAsCString srsFromWktIO\n{-# NOINLINE srsFromWkt #-}\n\nsrsFromWktIO :: CString -> IO (Either OGRException SpatialReference)\nsrsFromWktIO a =\n try $\n newSpatialRefHandle $\n checkGDALCall checkIt ({#call unsafe NewSpatialReference as ^#} a)\n where\n checkIt e p\n | p==nullPtr = Just (maybe defExc toOgrExc e)\n | otherwise = fmap toOgrExc e\n defExc = NullSpatialReference\n toOgrExc = gdalToOgrException Failure\n\nsrsFromProj4 = fromImporter importFromProj4\n{-# NOINLINE srsFromProj4 #-}\n\nsrsFromXML = fromImporter importFromXML\n{-# NOINLINE srsFromXML #-}\n\nsrsFromEPSG :: Int -> Either OGRException SpatialReference\nsrsFromEPSG = fromImporter importFromEPSG\n{-# NOINLINE srsFromEPSG #-}\n\nsrsFromEPSGIO :: Int -> IO (Either OGRException SpatialReference)\nsrsFromEPSGIO = fromImporterIO importFromEPSG\n\nfromImporter\n :: (SpatialReference -> a -> IO CInt) -> a\n -> Either OGRException SpatialReference\nfromImporter f = unsafePerformIO . fromImporterIO f\n{-# NOINLINE fromImporter #-}\n\nfromImporterIO\n :: (SpatialReference -> a -> IO CInt) -> a\n -> IO (Either OGRException SpatialReference)\nfromImporterIO f s = do\n r <- emptySpatialRef\n try (checkOGRError \"srsFrom\" (f r s) >> return r)\n\n\n{#fun ImportFromProj4 as ^\n { withSpatialReference* `SpatialReference'\n , useAsCString* `ByteString'} -> `CInt' #}\n\n{#fun ImportFromEPSG as ^\n {withSpatialReference* `SpatialReference', `Int'} -> `CInt' #}\n\n{#fun ImportFromXML as ^\n { withSpatialReference* `SpatialReference'\n , useAsCString* `ByteString'} -> `CInt' #}\n\n{#fun pure unsafe IsGeographic as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsLocal as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsProjected as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSameGeogCS as ^\n { withSpatialReference* `SpatialReference'\n , withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSame as ^\n { withSpatialReference* `SpatialReference'\n , withSpatialReference* `SpatialReference'} -> `Bool'#}\n\ninstance Eq SpatialReference where\n (==) = isSame\n\ngetLinearUnits :: SpatialReference -> (Double, String)\ngetLinearUnits =\n unsafePerformIO . getUnitsWith {#call unsafe OSRGetLinearUnits as ^#}\n\ngetAngularUnits :: SpatialReference -> (Double, String)\ngetAngularUnits =\n unsafePerformIO . getUnitsWith {#call unsafe OSRGetAngularUnits as ^#}\n\ngetUnitsWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CDouble)\n -> SpatialReference\n -> IO (Double, String)\ngetUnitsWith fun s = alloca $ \\p -> do\n value <- withSpatialReference s (\\s' -> fun s' p)\n ptr <- peek p\n units <- peekCString ptr\n return (realToFrac value, units)\n\nwithMaybeSRAsCString :: Maybe SpatialReference -> (CString -> IO a) -> IO a\nwithMaybeSRAsCString =\n unsafeUseAsCString . maybe \"\\0\" srsToWkt\n\nmaybeSpatialReferenceFromCString :: CString -> IO (Maybe SpatialReference)\nmaybeSpatialReferenceFromCString srs = do\n c <- peek srs\n if c == 0\n then return Nothing\n else srsFromWktIO srs >>= either throwM (return . Just)\n\nwithMaybeSpatialReference\n :: Maybe SpatialReference -> (Ptr SpatialReference -> IO a) -> IO a\nwithMaybeSpatialReference Nothing = ($ nullPtr)\nwithMaybeSpatialReference (Just s) = withSpatialReference s\n\n{#pointer OGRCoordinateTransformationH as CoordinateTransformation\n foreign newtype#}\n\ncoordinateTransformation\n :: SpatialReference -> SpatialReference\n -> Either OGRException CoordinateTransformation\ncoordinateTransformation source =\n unsafePerformIO . coordinateTransformationIO source\n{-# NOINLINE coordinateTransformation #-}\n\ncoordinateTransformationIO\n :: SpatialReference\n -> SpatialReference\n -> IO (Either OGRException CoordinateTransformation)\ncoordinateTransformationIO source target =\n try $\n liftM CoordinateTransformation $\n withSpatialReference source $ \\pSource ->\n withSpatialReference target $ \\pTarget ->\n mask_ $\n newForeignPtr c_destroyCT =<<\n (checkGDALCall checkIt\n ({#call unsafe OCTNewCoordinateTransformation as ^#} pSource pTarget))\n where\n checkIt e p\n | p==nullPtr = Just (maybe defExc toOgrExc e)\n | otherwise = Nothing\n defExc = NullCoordinateTransformation\n toOgrExc = gdalToOgrException Failure\n\nforeign import ccall \"ogr_srs_api.h &OCTDestroyCoordinateTransformation\"\n c_destroyCT :: FunPtr (Ptr CoordinateTransformation -> IO ())\n\nclass Projectable a where\n transformWith :: a -> CoordinateTransformation -> Maybe a\n\ninstance Projectable (St.Vector (Pair Double)) where\n transformWith = flip transformPoints\n\ntransformPoints\n :: CoordinateTransformation\n -> St.Vector (Pair Double)\n -> Maybe (St.Vector (Pair Double))\ntransformPoints ct v = unsafePerformIO $ withQuietErrorHandler $ do\n xs <- St.unsafeThaw (St.unsafeCast (St.map pFst v))\n ys <- St.unsafeThaw (St.unsafeCast (St.map pSnd v))\n zs <- Stm.replicate len 0\n ok <- liftM toBool $\n withCoordinateTransformation ct $ \\pCt ->\n Stm.unsafeWith xs $ \\pXs ->\n Stm.unsafeWith ys $ \\pYs ->\n Stm.unsafeWith zs $ \\pZs ->\n {#call unsafe OCTTransform as ^#} pCt (fromIntegral len) pXs pYs pZs\n if not ok\n then return Nothing\n else do\n fXs <- liftM St.unsafeCast (St.unsafeFreeze xs)\n fYs <- liftM St.unsafeCast (St.unsafeFreeze ys)\n return (Just (St.zipWith (:+:) fXs fYs))\n where len = St.length v\n\n\n{#fun OSRCleanup as cleanup {} -> `()'#}\n\n-- | GDAL doesn't call ogr\/ogrct.cpp:LoadProj4Library in a thread-safe way\n-- (at least in 1.11.2). We indirectly make sure it is called at startup\n-- in the main thread (via 'withGDAL') with this function which creates\n-- a dummy 'CoordinateTransformation'\ninitialize :: IO ()\ninitialize = do\n dummy <- emptySpatialRef\n void (coordinateTransformationIO dummy dummy)\n","old_contents":"{-# OPTIONS_GHC -fno-warn-orphans #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE FlexibleInstances #-}\n\nmodule GDAL.Internal.OSR (\n SpatialReference\n , CoordinateTransformation\n , Projectable (..)\n\n , srsFromWkt\n , srsFromProj4\n , srsFromEPSG\n , srsFromXML\n\n , srsToWkt\n , srsToProj4\n , srsToXML\n\n , isGeographic\n , isLocal\n , isProjected\n , isSameGeogCS\n , isSame\n\n , getAngularUnits\n , getLinearUnits\n\n , coordinateTransformation\n\n , cleanup\n , initialize\n , srsFromWktIO\n , withSpatialReference\n , withMaybeSRAsCString\n , withMaybeSpatialReference\n , maybeSpatialReferenceFromCString\n , withCoordinateTransformation\n , newSpatialRefHandle\n , newSpatialRefBorrowedHandle\n , maybeNewSpatialRefHandle\n , maybeNewSpatialRefBorrowedHandle\n) where\n\n#include \"ogr_srs_api.h\"\n\n{# context lib = \"gdal\" prefix = \"OSR\" #}\n\nimport Control.Monad.Catch (throwM, mask_, try)\nimport Control.Monad (liftM, (>=>), when, void)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\n\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Storable as St\n\nimport Foreign.C.String (CString, peekCString)\nimport Foreign.C.Types (CInt(..), CDouble(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLString (peekCPLString)\n\n{#pointer OGRSpatialReferenceH as SpatialReference foreign newtype#}\n\ninstance Show SpatialReference where\n show = show . srsToWkt\n\nsrsToWkt :: SpatialReference -> ByteString\nsrsToWkt s = exportWith fun s\n where\n fun s' p = {#call unsafe ExportToPrettyWkt as ^#} s' p 1\n\nsrsToProj4 :: SpatialReference -> ByteString\nsrsToProj4 = exportWith {#call unsafe ExportToProj4 as ^#}\n\nsrsToXML :: SpatialReference -> ByteString\nsrsToXML = exportWith fun\n where\n fun s' p = {#call unsafe ExportToXML as ^#} s' p (castPtr nullPtr)\n\nexportWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CInt)\n -> SpatialReference\n -> ByteString\nexportWith fun srs =\n unsafePerformIO $\n withSpatialReference srs $ \\pSrs ->\n peekCPLString $\n checkOGRError \"srsTo\" . fun pSrs\n{-# NOINLINE exportWith #-}\n\n\nforeign import ccall \"ogr_srs_api.h &OSRRelease\"\n c_release :: FunPtr (Ptr SpatialReference -> IO ())\n\nnewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefHandle = maybeNewSpatialRefHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefHandle io =\n mask_ $ do\n p <- io\n if p==nullPtr\n then return Nothing\n else liftM (Just . SpatialReference) (newForeignPtr c_release p)\n\nnewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefBorrowedHandle =\n maybeNewSpatialRefBorrowedHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefBorrowedHandle alloc = maybeNewSpatialRefHandle $ do\n p <- alloc\n when (p \/= nullPtr) (void ({#call unsafe OSRReference as ^#} p))\n return p\n\nemptySpatialRef :: IO SpatialReference\nemptySpatialRef =\n newSpatialRefHandle ({#call unsafe NewSpatialReference as ^#} nullPtr)\n\nsrsFromWkt, srsFromProj4, srsFromXML\n :: ByteString -> Either OGRException SpatialReference\nsrsFromWkt =\n unsafePerformIO . flip useAsCString srsFromWktIO\n{-# NOINLINE srsFromWkt #-}\n\nsrsFromWktIO :: CString -> IO (Either OGRException SpatialReference)\nsrsFromWktIO a =\n try $\n newSpatialRefHandle $\n checkGDALCall checkIt ({#call unsafe NewSpatialReference as ^#} a)\n where\n checkIt e p\n | p==nullPtr = Just (maybe defExc toOgrExc e)\n | otherwise = fmap toOgrExc e\n defExc = NullSpatialReference\n toOgrExc = gdalToOgrException Failure\n\nsrsFromProj4 = fromImporter importFromProj4\n{-# NOINLINE srsFromProj4 #-}\n\nsrsFromXML = fromImporter importFromXML\n{-# NOINLINE srsFromXML #-}\n\nsrsFromEPSG :: Int -> Either OGRException SpatialReference\nsrsFromEPSG = fromImporter importFromEPSG\n{-# NOINLINE srsFromEPSG #-}\n\nfromImporter\n :: (SpatialReference -> a -> IO CInt) -> a\n -> Either OGRException SpatialReference\nfromImporter f s = unsafePerformIO $ do\n r <- emptySpatialRef\n try (checkOGRError \"srsFrom\" (f r s) >> return r)\n{-# NOINLINE fromImporter #-}\n\n\n{#fun ImportFromProj4 as ^\n { withSpatialReference* `SpatialReference'\n , useAsCString* `ByteString'} -> `CInt' #}\n\n{#fun ImportFromEPSG as ^\n {withSpatialReference* `SpatialReference', `Int'} -> `CInt' #}\n\n{#fun ImportFromXML as ^\n { withSpatialReference* `SpatialReference'\n , useAsCString* `ByteString'} -> `CInt' #}\n\n{#fun pure unsafe IsGeographic as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsLocal as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsProjected as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSameGeogCS as ^\n { withSpatialReference* `SpatialReference'\n , withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSame as ^\n { withSpatialReference* `SpatialReference'\n , withSpatialReference* `SpatialReference'} -> `Bool'#}\n\ninstance Eq SpatialReference where\n (==) = isSame\n\ngetLinearUnits :: SpatialReference -> (Double, String)\ngetLinearUnits =\n unsafePerformIO . getUnitsWith {#call unsafe OSRGetLinearUnits as ^#}\n\ngetAngularUnits :: SpatialReference -> (Double, String)\ngetAngularUnits =\n unsafePerformIO . getUnitsWith {#call unsafe OSRGetAngularUnits as ^#}\n\ngetUnitsWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CDouble)\n -> SpatialReference\n -> IO (Double, String)\ngetUnitsWith fun s = alloca $ \\p -> do\n value <- withSpatialReference s (\\s' -> fun s' p)\n ptr <- peek p\n units <- peekCString ptr\n return (realToFrac value, units)\n\nwithMaybeSRAsCString :: Maybe SpatialReference -> (CString -> IO a) -> IO a\nwithMaybeSRAsCString =\n unsafeUseAsCString . maybe \"\\0\" srsToWkt\n\nmaybeSpatialReferenceFromCString :: CString -> IO (Maybe SpatialReference)\nmaybeSpatialReferenceFromCString srs = do\n c <- peek srs\n if c == 0\n then return Nothing\n else srsFromWktIO srs >>= either throwM (return . Just)\n\nwithMaybeSpatialReference\n :: Maybe SpatialReference -> (Ptr SpatialReference -> IO a) -> IO a\nwithMaybeSpatialReference Nothing = ($ nullPtr)\nwithMaybeSpatialReference (Just s) = withSpatialReference s\n\n{#pointer OGRCoordinateTransformationH as CoordinateTransformation\n foreign newtype#}\n\ncoordinateTransformation\n :: SpatialReference -> SpatialReference\n -> Either OGRException CoordinateTransformation\ncoordinateTransformation source =\n unsafePerformIO . coordinateTransformationIO source\n{-# NOINLINE coordinateTransformation #-}\n\ncoordinateTransformationIO\n :: SpatialReference\n -> SpatialReference\n -> IO (Either OGRException CoordinateTransformation)\ncoordinateTransformationIO source target =\n try $\n liftM CoordinateTransformation $\n withSpatialReference source $ \\pSource ->\n withSpatialReference target $ \\pTarget ->\n mask_ $\n newForeignPtr c_destroyCT =<<\n (checkGDALCall checkIt\n ({#call unsafe OCTNewCoordinateTransformation as ^#} pSource pTarget))\n where\n checkIt e p\n | p==nullPtr = Just (maybe defExc toOgrExc e)\n | otherwise = Nothing\n defExc = NullCoordinateTransformation\n toOgrExc = gdalToOgrException Failure\n\nforeign import ccall \"ogr_srs_api.h &OCTDestroyCoordinateTransformation\"\n c_destroyCT :: FunPtr (Ptr CoordinateTransformation -> IO ())\n\nclass Projectable a where\n transformWith :: a -> CoordinateTransformation -> Maybe a\n\ninstance Projectable (St.Vector (Pair Double)) where\n transformWith = flip transformPoints\n\ntransformPoints\n :: CoordinateTransformation\n -> St.Vector (Pair Double)\n -> Maybe (St.Vector (Pair Double))\ntransformPoints ct v = unsafePerformIO $ withQuietErrorHandler $ do\n xs <- St.unsafeThaw (St.unsafeCast (St.map pFst v))\n ys <- St.unsafeThaw (St.unsafeCast (St.map pSnd v))\n zs <- Stm.replicate len 0\n ok <- liftM toBool $\n withCoordinateTransformation ct $ \\pCt ->\n Stm.unsafeWith xs $ \\pXs ->\n Stm.unsafeWith ys $ \\pYs ->\n Stm.unsafeWith zs $ \\pZs ->\n {#call unsafe OCTTransform as ^#} pCt (fromIntegral len) pXs pYs pZs\n if not ok\n then return Nothing\n else do\n fXs <- liftM St.unsafeCast (St.unsafeFreeze xs)\n fYs <- liftM St.unsafeCast (St.unsafeFreeze ys)\n return (Just (St.zipWith (:+:) fXs fYs))\n where len = St.length v\n\n\n{#fun OSRCleanup as cleanup {} -> `()'#}\n\n-- | GDAL doesn't call ogr\/ogrct.cpp:LoadProj4Library in a thread-safe way\n-- (at least in 1.11.2). We indirectly make sure it is called at startup\n-- in the main thread (via 'withGDAL') with this function which creates\n-- a dummy 'CoordinateTransformation'\ninitialize :: IO ()\ninitialize = do\n dummy <- emptySpatialRef\n void (coordinateTransformationIO dummy dummy)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"95eb2e5eab01ae317cfb64c5bb5297f9601b69eb","subject":"Update on\/afterEdited to use new TreeIter and to use connect_STRING_STRING__NONE rather than connect_PTR_STRING__NONE. This is a different implementation than the one in ModelView since the latter has a different type too. So this is just an intrim implementation.","message":"Update on\/afterEdited to use new TreeIter\nand to use connect_STRING_STRING__NONE rather than \nconnect_PTR_STRING__NONE. This is a different implementation than the \none in ModelView since the latter has a different type too. So this is \njust an intrim implementation.\n\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CellRendererText.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CellRendererText.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CellRendererText TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.7 $ 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-- A 'CellRenderer' which displays a single-line text.\n--\nmodule Graphics.UI.Gtk.TreeList.CellRendererText (\n-- * Detail\n-- \n-- | This widget derives from 'CellRenderer'. It provides the \n-- possibility to display some text by setting the 'Attribute' \n-- 'cellText' to the column of a 'TreeModel' by means of \n-- 'treeViewAddAttribute' from 'TreeModelColumn'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'CellRenderer'\n-- | +----CellRendererText\n-- | +----'CellRendererCombo'\n-- @\n\n-- * Types\n CellRendererText,\n CellRendererTextClass,\n castToCellRendererText,\n toCellRendererText,\n\n-- * Constructors\n cellRendererTextNew,\n\n-- * Attributes\n cellText,\n cellMarkup,\n cellBackground,\n cellForeground,\n cellEditable,\n\n-- * Signals\n onEdited,\n afterEdited\n ) where\n\nimport Maybe\t(fromMaybe)\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\nimport Graphics.UI.Gtk.General.Structs\t\t(treeIterSize)\nimport Graphics.UI.Gtk.TreeList.CellRenderer\t(Attribute(..))\nimport System.Glib.StoreValue\t\t\t(GenericValue(..), TMType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new CellRendererText object.\n--\ncellRendererTextNew :: IO CellRendererText\ncellRendererTextNew =\n makeNewObject mkCellRendererText $\n liftM (castPtr :: Ptr CellRenderer -> Ptr CellRendererText) $\n {# call unsafe cell_renderer_text_new #}\n\n-- helper function\n--\nstrAttr :: [String] -> Attribute CellRendererText String\nstrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring . Just)\n\t\t(\\[GVstring str] -> return (fromMaybe \"\" str))\n\nmStrAttr :: [String] -> Attribute CellRendererText (Maybe String)\nmStrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring)\n\t\t(\\[GVstring str] -> return str)\n\n--------------------\n-- Properties\n\n-- | Define the attribute that specifies the text to be\n-- rendered.\n--\ncellText :: Attribute CellRendererText String\ncellText = strAttr [\"text\"]\n\n-- | Define a markup string instead of a text.\n--\ncellMarkup :: Attribute CellRendererText String\ncellMarkup = strAttr [\"markup\"]\n\n-- | A named color for the background paint.\n--\ncellBackground :: Attribute CellRendererText (Maybe String)\ncellBackground = mStrAttr [\"background\"]\n\n-- | A named color for the foreground paint.\n--\ncellForeground :: Attribute CellRendererText (Maybe String)\ncellForeground = mStrAttr [\"foreground\"]\n\n-- | Determines wether the content can be altered.\n--\n-- * If this flag is set, the user can alter the cell.\n--\ncellEditable :: Attribute CellRendererText (Maybe Bool)\ncellEditable = Attribute [\"editable\",\"editable-set\"] [TMboolean,TMboolean]\n\t (\\mb -> return $ case mb of\n\t\t (Just bool) -> [GVboolean bool, GVboolean True]\n\t\t Nothing -> [GVboolean True, GVboolean False])\n\t\t (\\[GVboolean e, GVboolean s] -> return $\n\t\t if s then Just e else Nothing)\n\n-- | Emitted when the user finished editing a cell.\n--\n-- * This signal is not emitted when editing is disabled (see \n-- 'cellEditable') or when the user aborts editing.\n--\nonEdited, afterEdited :: TreeModelClass tm => CellRendererText -> tm ->\n\t\t\t (TreeIter -> String -> IO ()) ->\n\t\t\t IO (ConnectId CellRendererText)\nonEdited cr tm user = connect_STRING_STRING__NONE \"edited\" False cr $\n \\path string ->\n alloca $ \\iterPtr ->\n withCString path $ \\pathPtr -> do\n res <- {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iterPtr\n pathPtr\n if toBool res\n then do\n iter <- peek iterPtr\n user iter string\n else\n putStrLn \"edited signal: invalid tree path\"\n\nafterEdited cr tm user = connect_STRING_STRING__NONE \"edited\" True cr $\n \\path string ->\n alloca $ \\iterPtr ->\n withCString path $ \\pathPtr -> do\n res <- {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iterPtr\n pathPtr\n if toBool res\n then do\n iter <- peek iterPtr\n user iter string\n else\n putStrLn \"edited signal: invalid tree path\"\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CellRendererText TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.7 $ 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-- A 'CellRenderer' which displays a single-line text.\n--\nmodule Graphics.UI.Gtk.TreeList.CellRendererText (\n-- * Detail\n-- \n-- | This widget derives from 'CellRenderer'. It provides the \n-- possibility to display some text by setting the 'Attribute' \n-- 'cellText' to the column of a 'TreeModel' by means of \n-- 'treeViewAddAttribute' from 'TreeModelColumn'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'CellRenderer'\n-- | +----CellRendererText\n-- | +----'CellRendererCombo'\n-- @\n\n-- * Types\n CellRendererText,\n CellRendererTextClass,\n castToCellRendererText,\n toCellRendererText,\n\n-- * Constructors\n cellRendererTextNew,\n\n-- * Attributes\n cellText,\n cellMarkup,\n cellBackground,\n cellForeground,\n cellEditable,\n\n-- * Signals\n onEdited,\n afterEdited\n ) where\n\nimport Maybe\t(fromMaybe)\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\nimport Graphics.UI.Gtk.General.Structs\t\t(treeIterSize)\nimport Graphics.UI.Gtk.TreeList.CellRenderer\t(Attribute(..))\nimport System.Glib.StoreValue\t\t\t(GenericValue(..), TMType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new CellRendererText object.\n--\ncellRendererTextNew :: IO CellRendererText\ncellRendererTextNew =\n makeNewObject mkCellRendererText $\n liftM (castPtr :: Ptr CellRenderer -> Ptr CellRendererText) $\n {# call unsafe cell_renderer_text_new #}\n\n-- helper function\n--\nstrAttr :: [String] -> Attribute CellRendererText String\nstrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring . Just)\n\t\t(\\[GVstring str] -> return (fromMaybe \"\" str))\n\nmStrAttr :: [String] -> Attribute CellRendererText (Maybe String)\nmStrAttr str = Attribute str [TMstring]\n\t (return . (\\x -> [x]) . GVstring)\n\t\t(\\[GVstring str] -> return str)\n\n--------------------\n-- Properties\n\n-- | Define the attribute that specifies the text to be\n-- rendered.\n--\ncellText :: Attribute CellRendererText String\ncellText = strAttr [\"text\"]\n\n-- | Define a markup string instead of a text.\n--\ncellMarkup :: Attribute CellRendererText String\ncellMarkup = strAttr [\"markup\"]\n\n-- | A named color for the background paint.\n--\ncellBackground :: Attribute CellRendererText (Maybe String)\ncellBackground = mStrAttr [\"background\"]\n\n-- | A named color for the foreground paint.\n--\ncellForeground :: Attribute CellRendererText (Maybe String)\ncellForeground = mStrAttr [\"foreground\"]\n\n-- | Determines wether the content can be altered.\n--\n-- * If this flag is set, the user can alter the cell.\n--\ncellEditable :: Attribute CellRendererText (Maybe Bool)\ncellEditable = Attribute [\"editable\",\"editable-set\"] [TMboolean,TMboolean]\n\t (\\mb -> return $ case mb of\n\t\t (Just bool) -> [GVboolean bool, GVboolean True]\n\t\t Nothing -> [GVboolean True, GVboolean False])\n\t\t (\\[GVboolean e, GVboolean s] -> return $\n\t\t if s then Just e else Nothing)\n\n-- | Emitted when the user finished editing a cell.\n--\n-- * This signal is not emitted when editing is disabled (see \n-- 'cellEditable') or when the user aborts editing.\n--\nonEdited, afterEdited :: TreeModelClass tm => CellRendererText -> tm ->\n\t\t\t (TreeIter -> String -> IO ()) ->\n\t\t\t IO (ConnectId CellRendererText)\nonEdited cr tm user = connect_PTR_STRING__NONE \"edited\" False cr $\n \\strPtr string ->\n mallocTreeIter >>= \\iter ->\n {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iter\n strPtr\n >>= \\res -> if toBool res then user iter string else\n putStrLn \"edited signal: invalid tree path\"\n\nafterEdited cr tm user = connect_PTR_STRING__NONE \"edited\" True cr $\n \\strPtr string ->\n mallocTreeIter >>= \\iter ->\n {# call gtk_tree_model_get_iter_from_string #}\n (toTreeModel tm)\n iter\n strPtr\n >>= \\res -> if toBool res then user iter string else\n putStrLn \"edited signal: invalid tree path\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"418fff8648fc5dac7284f648938e2b4b15759a44","subject":"Fix for gtk 3.6","message":"Fix for gtk 3.6\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionContext.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceCompletionContext.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionContext\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionContext (\n-- * Types\n SourceCompletionContext,\n SourceCompletionContextClass,\n\n-- * Enums\n SourceCompletionActivation,\n\n-- * Methods\n sourceCompletionContextAddProposals,\n sourceCompletionContextGetIter,\n\n-- * Attributes \n sourceCompletionContextActivation,\n sourceCompletionContextCompletion,\n\n-- * Signals \n sourceCompletionContextCancelled,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport Graphics.UI.Gtk.SourceView.Enums\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport System.Glib.Properties\nimport System.Glib.UTFString\n\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Providers can use this function to add proposals to the completion. They can do so asynchronously by\n-- means of the finished argument. Providers must ensure that they always call this function with\n-- finished set to 'True' once each population (even if no proposals need to be added).\nsourceCompletionContextAddProposals :: (SourceCompletionContextClass scc, SourceCompletionProviderClass scp) => scc\n -> scp\n -> [SourceCompletionProposal] -- ^ @proposals@ The list of proposals to add \n -> Bool -- ^ @finished@ Whether the provider is finished adding proposals \n -> IO ()\nsourceCompletionContextAddProposals scc provider proposals finished = \n withForeignPtrs (map unSourceCompletionProposal proposals) $ \\proposalsPtr ->\n#if !MIN_VERSION_gtksourceview_3_0(3,6,0)\n withForeignPtr (unSourceCompletionProvider $ toSourceCompletionProvider provider) $ \\providerPtr ->\n#endif\n withGList proposalsPtr $ \\glist ->\n {#call gtk_source_completion_context_add_proposals #}\n (toSourceCompletionContext scc)\n#if MIN_VERSION_gtksourceview_3_0(3,6,0)\n (toSourceCompletionProvider provider)\n#else\n (castPtr providerPtr)\n#endif\n glist\n (fromBool finished)\n\n-- | Get the iter at which the completion was invoked. Providers can use this to determine how and if to\n-- match proposals.\nsourceCompletionContextGetIter :: SourceCompletionContextClass scc => scc\n -> IO TextIter\nsourceCompletionContextGetIter scc = do\n iter <- makeEmptyTextIter\n {#call gtk_source_completion_context_get_iter #}\n (toSourceCompletionContext scc)\n iter\n return iter\n\n-- | The completion activation\nsourceCompletionContextActivation :: SourceCompletionContextClass scc => Attr scc SourceCompletionActivation\nsourceCompletionContextActivation = newAttrFromEnumProperty \"activation\"\n {#call pure unsafe gtk_source_completion_activation_get_type #}\n\n-- | The 'SourceCompletion' associated with the context.\nsourceCompletionContextCompletion :: SourceCompletionContextClass scc => Attr scc SourceCompletion\nsourceCompletionContextCompletion = newAttrFromObjectProperty \"completion\"\n {#call pure unsafe gtk_source_completion_get_type #}\n\n-- | Emitted when the current population of proposals has been cancelled. Providers adding proposals\n-- asynchronously should connect to this signal to know when to cancel running proposal queries.\nsourceCompletionContextCancelled :: SourceCompletionContextClass scc => Signal scc (IO ())\nsourceCompletionContextCancelled = Signal $ connect_NONE__NONE \"cancelled\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceCompletionContext\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceCompletionContext (\n-- * Types\n SourceCompletionContext,\n SourceCompletionContextClass,\n\n-- * Enums\n SourceCompletionActivation,\n\n-- * Methods\n sourceCompletionContextAddProposals,\n sourceCompletionContextGetIter,\n\n-- * Attributes \n sourceCompletionContextActivation,\n sourceCompletionContextCompletion,\n\n-- * Signals \n sourceCompletionContextCancelled,\n) where\n\nimport Control.Monad\t(liftM)\n\nimport Graphics.UI.Gtk.SourceView.Enums\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.GList\t\t(fromGList, withGList)\nimport System.Glib.Properties\nimport System.Glib.UTFString\n\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Providers can use this function to add proposals to the completion. They can do so asynchronously by\n-- means of the finished argument. Providers must ensure that they always call this function with\n-- finished set to 'True' once each population (even if no proposals need to be added).\nsourceCompletionContextAddProposals :: (SourceCompletionContextClass scc, SourceCompletionProviderClass scp) => scc\n -> scp\n -> [SourceCompletionProposal] -- ^ @proposals@ The list of proposals to add \n -> Bool -- ^ @finished@ Whether the provider is finished adding proposals \n -> IO ()\nsourceCompletionContextAddProposals scc provider proposals finished = \n withForeignPtrs (map unSourceCompletionProposal proposals) $ \\proposalsPtr ->\n#if !MIN_VERSION_gtksourceview_3_0(3,6,0)\n withForeignPtr (unSourceCompletionProvider $ toSourceCompletionProvider provider) $ \\providerPtr ->\n#endif\n withGList proposalsPtr $ \\glist ->\n {#call gtk_source_completion_context_add_proposals #}\n (toSourceCompletionContext scc)\n#if MIN_VERSION_gtksourceview_3_0(3,6,0)\n (castPtr $ toSourceCompletionProvider provider)\n#else\n (castPtr providerPtr)\n#endif\n glist\n (fromBool finished)\n\n-- | Get the iter at which the completion was invoked. Providers can use this to determine how and if to\n-- match proposals.\nsourceCompletionContextGetIter :: SourceCompletionContextClass scc => scc\n -> IO TextIter\nsourceCompletionContextGetIter scc = do\n iter <- makeEmptyTextIter\n {#call gtk_source_completion_context_get_iter #}\n (toSourceCompletionContext scc)\n iter\n return iter\n\n-- | The completion activation\nsourceCompletionContextActivation :: SourceCompletionContextClass scc => Attr scc SourceCompletionActivation\nsourceCompletionContextActivation = newAttrFromEnumProperty \"activation\"\n {#call pure unsafe gtk_source_completion_activation_get_type #}\n\n-- | The 'SourceCompletion' associated with the context.\nsourceCompletionContextCompletion :: SourceCompletionContextClass scc => Attr scc SourceCompletion\nsourceCompletionContextCompletion = newAttrFromObjectProperty \"completion\"\n {#call pure unsafe gtk_source_completion_get_type #}\n\n-- | Emitted when the current population of proposals has been cancelled. Providers adding proposals\n-- asynchronously should connect to this signal to know when to cancel running proposal queries.\nsourceCompletionContextCancelled :: SourceCompletionContextClass scc => Signal scc (IO ())\nsourceCompletionContextCancelled = Signal $ connect_NONE__NONE \"cancelled\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7edddd32c4632f38c1e17285618c4cbc15a5b0b1","subject":"Fixes issue #3. Failing to read an image now throws CvIOError","message":"Fixes issue #3. Failing to read an image now throws CvIOError\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 #-}\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\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 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 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 -> 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-- | 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 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\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\ndata CvIOError = CvIOError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\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\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 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 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\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\ndata CvIOError = CvIOError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\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":"ddfaf4642b9cd081ea70fa5117cc21d4a0b316b7","subject":"Add internal documentation","message":"Add internal documentation\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . peek\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\npeekAudioPort = maybeForeignPtr_ AudioPort\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n\npeekStream = maybeForeignPtr_ Stream\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","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\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\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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . 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 {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":"35f7486bba90907391b6014c0d3d98a6868fedad","subject":"gstreamer: small fixes in M.S.G.Core.Event","message":"gstreamer: small fixes in M.S.G.Core.Event\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.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 object describing events that are passed up and down a pipeline.\nmodule Media.Streaming.GStreamer.Core.Event (\n\n-- * Detail\n\n -- | An 'Event' is a message that is passed up and down a pipeline.\n -- \n -- There are a number of predefined events and functions returning\n -- events. To send an event an application will usually use\n -- 'Media.Streaming.GStreamer.Core.Element.elementSendEvent', and\n -- elements will use\n -- 'Media.Streaming.GStreamer.Core.Pad.padSendEvent' or\n -- 'Media.Streaming.GStreamer.Core.padPushEvent'.\n -- \n -- \n\n-- * Types\n Event,\n EventClass,\n EventType(..),\n\n-- * Event Operations\n eventType,\n eventNewCustom,\n eventNewEOS,\n eventNewFlushStart,\n eventNewFlushStop,\n eventNewLatency,\n eventNewNavigation,\n eventNewNewSegment,\n eventNewNewSegmentFull,\n eventNewQOS,\n eventNewSeek,\n eventNewTag,\n eventParseBufferSize,\n eventParseLatency,\n eventParseNewSegment,\n eventParseNewSegmentFull,\n eventParseQOS,\n eventParseSeek,\n eventParseTag,\n eventTypeGetName,\n eventTypeGetFlags,\n ) where\n\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: EventClass event\n => event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject (toEvent event) cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: EventClass event\n => event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} (toEvent event)\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: EventClass event\n => event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} (toEvent event)\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: EventClass event\n => event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} (toEvent event)\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: EventClass event\n => event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} (toEvent event)\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: EventClass event\n => event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} (toEvent event)\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: EventClass event\n => event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} (toEvent event)\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: EventClass event\n => event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} (toEvent event) (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n | otherwise = Nothing\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\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.Event (\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: Event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject event cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: Event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} event\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: Event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} event\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: Event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} event\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: Event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} event\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: Event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} event\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: Event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} event\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: Event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} event (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"6ae832b0a657ad6cc4c636dfbebe46d7d82d15b1","subject":"gstreamer: small fixes in M.S.G.Core.Event","message":"gstreamer: small fixes in M.S.G.Core.Event\n\ndarcs-hash:20080519004859-21862-f6117ffecf21c2d48a379122b6686293b2dfbf18.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Event.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 object describing events that are passed up and down a pipeline.\nmodule Media.Streaming.GStreamer.Core.Event (\n\n-- * Detail\n\n -- | An 'Event' is a message that is passed up and down a pipeline.\n -- \n -- There are a number of predefined events and functions returning\n -- events. To send an event an application will usually use\n -- 'Media.Streaming.GStreamer.Core.Element.elementSendEvent', and\n -- elements will use\n -- 'Media.Streaming.GStreamer.Core.Pad.padSendEvent' or\n -- 'Media.Streaming.GStreamer.Core.padPushEvent'.\n -- \n -- \n\n-- * Types\n Event,\n EventClass,\n EventType(..),\n\n-- * Event Operations\n eventType,\n eventNewCustom,\n eventNewEOS,\n eventNewFlushStart,\n eventNewFlushStop,\n eventNewLatency,\n eventNewNavigation,\n eventNewNewSegment,\n eventNewNewSegmentFull,\n eventNewQOS,\n eventNewSeek,\n eventNewTag,\n eventParseBufferSize,\n eventParseLatency,\n eventParseNewSegment,\n eventParseNewSegmentFull,\n eventParseQOS,\n eventParseSeek,\n eventParseTag,\n eventTypeGetName,\n eventTypeGetFlags,\n ) where\n\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: EventClass event\n => event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject (toEvent event) cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: EventClass event\n => event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} (toEvent event)\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: EventClass event\n => event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} (toEvent event)\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: EventClass event\n => event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} (toEvent event)\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: EventClass event\n => event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} (toEvent event)\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: EventClass event\n => event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} (toEvent event)\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: EventClass event\n => event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} (toEvent event)\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: EventClass event\n => event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} (toEvent event) (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n | otherwise = Nothing\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\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.Event (\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\neventType :: Event\n -> EventType\neventType event =\n cToEnum $ unsafePerformIO $ withMiniObject event cEventType\nforeign import ccall unsafe \"_hs_gst_event_type\"\n cEventType :: Ptr Event\n -> IO {# type GstEventType #}\n\neventNewCustom :: EventType\n -> Structure\n -> IO Event\neventNewCustom eventType structure =\n {# call event_new_custom #} (cFromEnum eventType)\n structure >>=\n takeMiniObject\n\neventNewEOS, eventNewFlushStart, eventNewFlushStop :: IO Event\neventNewEOS = {# call event_new_eos #} >>= takeMiniObject\neventNewFlushStart = {# call event_new_flush_start #} >>= takeMiniObject\neventNewFlushStop = {# call event_new_flush_stop #} >>= takeMiniObject\n\neventNewLatency :: ClockTime\n -> IO Event\neventNewLatency latency =\n {# call event_new_latency #} (fromIntegral latency) >>=\n takeMiniObject\n\neventNewNavigation :: Structure\n -> IO Event\neventNewNavigation structure =\n {# call event_new_navigation #} structure >>=\n takeMiniObject\n\neventNewNewSegment :: Bool\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegment update rate format start stop position =\n {# call event_new_new_segment #} (fromBool update)\n (realToFrac rate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewNewSegmentFull :: Bool\n -> Double\n -> Double\n -> Format\n -> Int64\n -> Int64\n -> Int64\n -> IO Event\neventNewNewSegmentFull update appliedRate rate format start stop position =\n {# call event_new_new_segment_full #} (fromBool update)\n (realToFrac rate)\n (realToFrac appliedRate)\n (cFromEnum format)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral position) >>=\n takeMiniObject\n\neventNewQOS :: Double\n -> ClockTimeDiff\n -> ClockTime\n -> IO Event\neventNewQOS proportion diff timestamp =\n {# call event_new_qos #} (realToFrac proportion)\n (fromIntegral diff)\n (fromIntegral timestamp) >>=\n takeMiniObject\n\neventNewSeek :: Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Event\neventNewSeek rate format flags startType start stopType stop =\n {# call event_new_seek #} (realToFrac rate)\n (cFromEnum format)\n (cFromFlags flags)\n (cFromEnum startType)\n (fromIntegral start)\n (cFromEnum stopType)\n (fromIntegral stop) >>=\n takeMiniObject\n\neventNewTag :: TagList\n -> IO Event\neventNewTag tagList =\n withTagList tagList ({# call event_new_tag #} . castPtr) >>=\n takeMiniObject\n\neventParseBufferSize :: Event\n -> Maybe (Format, Int64, Int64, Bool)\neventParseBufferSize event | eventType event == EventBufferSize =\n Just $ unsafePerformIO $ alloca $ \\formatPtr -> alloca $ \\minSizePtr ->\n alloca $ \\maxSizePtr -> alloca $ \\asyncPtr ->\n do {# call event_parse_buffer_size #} event\n formatPtr\n minSizePtr\n maxSizePtr\n asyncPtr\n format <- liftM cToEnum $ peek formatPtr\n minSize <- liftM fromIntegral $ peek minSizePtr\n maxSize <- liftM fromIntegral $ peek maxSizePtr\n async <- liftM toBool $ peek asyncPtr\n return (format, minSize, maxSize, async)\n | otherwise = Nothing\n\neventParseLatency :: Event\n -> Maybe ClockTime\neventParseLatency event | eventType event == EventLatency =\n Just $ unsafePerformIO $ alloca $ \\latencyPtr ->\n do {# call event_parse_latency #} event\n latencyPtr\n liftM fromIntegral $ peek latencyPtr\n | otherwise = Nothing\n\neventParseNewSegment :: Event\n -> Maybe (Bool, Double, Format, Int64, Int64, Int64)\neventParseNewSegment event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\formatPtr ->\n alloca $ \\startPtr -> alloca $ \\stopPtr ->\n alloca $ \\positionPtr ->\n do {# call event_parse_new_segment #} event\n ratePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseNewSegmentFull :: Event\n -> Maybe (Bool, Double, Double, Format, Int64, Int64, Int64)\neventParseNewSegmentFull event | eventType event == EventNewSegment =\n Just $ unsafePerformIO $ alloca $ \\updatePtr ->\n alloca $ \\ratePtr -> alloca $ \\appliedRatePtr ->\n alloca $ \\formatPtr -> alloca $ \\startPtr ->\n alloca $ \\stopPtr -> alloca $ \\positionPtr ->\n do {# call event_parse_new_segment_full #} event\n ratePtr\n appliedRatePtr\n updatePtr\n formatPtr\n startPtr\n stopPtr\n positionPtr\n update <- liftM toBool $ peek updatePtr\n rate <- liftM realToFrac $ peek ratePtr\n appliedRate <- liftM realToFrac $ peek appliedRatePtr\n format <- liftM cToEnum $ peek formatPtr\n start <- liftM fromIntegral $ peek startPtr\n stop <- liftM fromIntegral $ peek stopPtr\n position <- liftM fromIntegral $ peek positionPtr\n return (update, rate, appliedRate, format, start, stop, position)\n | otherwise = Nothing\n\neventParseQOS :: Event\n -> Maybe (Double, ClockTimeDiff, ClockTime)\neventParseQOS event | eventType event == EventQOS =\n Just $ unsafePerformIO $ alloca $ \\proportionPtr ->\n alloca $ \\diffPtr -> alloca $ \\timestampPtr ->\n do {# call event_parse_qos #} event\n proportionPtr\n diffPtr\n timestampPtr\n proportion <- liftM realToFrac $ peek proportionPtr\n diff <- liftM fromIntegral $ peek diffPtr\n timestamp <- liftM fromIntegral $ peek timestampPtr\n return (proportion, diff, timestamp)\n | otherwise = Nothing\n\neventParseSeek :: Event\n -> Maybe (Double, Format, [SeekFlags], SeekType, Int64, SeekType, Int64)\neventParseSeek event | eventType event == EventSeek =\n Just $ unsafePerformIO $ alloca $ \\ratePtr ->\n alloca $ \\formatPtr -> alloca $ \\flagsPtr ->\n alloca $ \\startTypePtr -> alloca $ \\startPtr ->\n alloca $ \\stopTypePtr -> alloca $ \\stopPtr ->\n do {# call event_parse_seek #} event\n ratePtr\n formatPtr\n flagsPtr\n startTypePtr\n startPtr\n stopTypePtr\n stopPtr\n rate <- liftM realToFrac $ peek ratePtr\n format <- liftM cToEnum $ peek formatPtr\n flags <- liftM cToFlags $ peek flagsPtr\n startType <- liftM cToEnum $ peek startTypePtr\n start <- liftM fromIntegral $ peek startPtr\n stopType <- liftM cToEnum $ peek stopTypePtr\n stop <- liftM fromIntegral $ peek stopPtr\n return (rate, format, flags, startType, start, stopType, stop)\n | otherwise = Nothing\n\neventParseTag :: Event\n -> Maybe TagList\neventParseTag event | eventType event == EventTag =\n Just $ unsafePerformIO $ alloca $ \\tagListPtr ->\n do {# call event_parse_tag #} event (castPtr tagListPtr)\n peek tagListPtr >>= peekTagList\n\neventTypeGetName :: EventType\n -> String\neventTypeGetName eventType =\n unsafePerformIO $\n {# call event_type_get_name #} (cFromEnum eventType) >>=\n peekUTFString\n\neventTypeGetFlags :: EventType\n -> [EventTypeFlags]\neventTypeGetFlags =\n cToFlags . {# call fun event_type_get_flags #} . cFromEnum\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fca223b3a8b7b0905f81f87231a8db1a5e3754d8","subject":"Add extra exports to Preferences","message":"Add extra exports to Preferences\n","repos":"reinerp\/CoreFoundation","old_file":"CoreFoundation\/Preferences.chs","new_file":"CoreFoundation\/Preferences.chs","new_contents":"{- |\nCore Foundation provides a simple, standard way to manage user (and application) preferences. Core Foundation stores preferences as key-value pairs that are assigned a scope using a combination of user name, application ID, and host (computer) names. This makes it possible to save and retrieve preferences that apply to different classes of users. Core Foundation preferences is useful to all applications that support user preferences. Note that modification of some preferences domains (those not belonging to the \\\"Current User\\\") requires root privileges (or Admin privileges prior to Mac OS X v10.6)-see Authorization Services Programming Guide ()\nfor information on how to gain suitable privileges.\n-}\nmodule CoreFoundation.Preferences(\n -- * Types\n Key,\n SuiteID,\n AppID,\n anyApp,\n currentApp,\n HostID,\n anyHost,\n currentHost,\n UserID,\n anyUser,\n currentUser,\n -- * Getting\n getAppValue,\n getKeyList,\n getMultiple,\n getValue,\n -- * Setting\n setAppValue,\n setMultiple,\n setValue,\n -- * Synchronizing\n SyncFailed(..),\n appSync,\n sync,\n -- * Suite preferences\n addSuiteToApp,\n removeSuiteFromApp,\n -- * Misc\n appValueIsForced,\n getAppList,\n ) where\n\nimport Prelude hiding(String)\n\nimport CoreFoundation.Base\nimport CoreFoundation.String\nimport CoreFoundation.Array\nimport CoreFoundation.Dictionary\nimport CoreFoundation.PropertyList\n#include \n#include \"cbits.h\"\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Data.Typeable\nimport Foreign\nimport Foreign.C.Types\n\n{#pointer CFStringRef -> CFString#}\n{#pointer CFArrayRef -> CFArray#}\n{#pointer CFDictionaryRef -> CFDictionary#}\n{#pointer CFPropertyListRef -> CFPropertyList#}\n\n-- | Keys. These can be constructed using the OverloadedStrings\n-- language extension.\ntype Key = String\n\n-- | ID of a suite, for example @com.apple.iApps@.\ntype SuiteID = String\n\n-- | Application ID. Takes the form of a java package name, @com.foosoft@, or one of the constants 'anyApp', 'currentApp'.\ntype AppID = String\n\n-- | Matches any application. This may be passed to functions which \\\"search\\\", such as 'getAppValue', 'getValue', 'getKeyList', etc. However, this may not be passed to functions which put a value in a specific location, such as 'setAppValue', 'syncApp'.\nanyApp :: AppID\nanyApp = constant {#call pure unsafe hsAnyApp#}\n\n-- | Specifies the current application\ncurrentApp :: AppID\ncurrentApp = constant {#call pure unsafe hsCurrentApp#}\n\n-- | Host ID. User-provided, or see the constants 'anyHost', 'currentHost'\ntype HostID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any host. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all hosts.\nanyHost :: HostID\nanyHost = constant {#call pure unsafe hsAnyHost#}\n\n-- | Current host\ncurrentHost :: HostID\ncurrentHost = constant {#call pure unsafe hsCurrentHost#}\n\n-- | User ID. User-provided, or see the constants 'anyUser',\n -- 'currentUser'\ntype UserID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any user. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all users.\nanyUser :: UserID\nanyUser = constant {#call pure unsafe hsAnyUser#}\n\n-- | Current user\ncurrentUser :: UserID\ncurrentUser = constant {#call pure unsafe hsCurrentUser#}\n\n------------------------- Getting ----------------------------\n{- |\nObtains a preference value for the specified key and application. Wraps CFPreferencesCopyAppValue.\n-}\ngetAppValue :: Key -> AppID -> IO (Maybe Plist)\ngetAppValue = call2 createNullable {#call unsafe CFPreferencesCopyAppValue as ^#}\n\n{- |\nConstructs and returns the list of all keys set in the specified domain. Wraps CFPreferencesCopyKeyList\n-}\ngetKeyList :: AppID -> UserID -> HostID -> IO (Array Key)\ngetKeyList = call3 create {#call unsafe CFPreferencesCopyKeyList as ^ #}\n\n{- |\nReturns a dictionary containing preference values for multiple keys. If no values were located, returns an empty dictionary. \n-}\ngetMultiple :: Array Key -> AppID -> UserID -> HostID -> IO (Dictionary Key Plist)\ngetMultiple = call4 create {#call unsafe CFPreferencesCopyMultiple as ^ #}\n\n{- |\nReturns a preference value for a given domain.\n\nThis function is the primitive get mechanism for the higher level preference function 'getAppValue'. Unlike the high-level function, 'getValue' searches only the exact domain specified. Do not use this function directly unless you have a need. Do not use arbitrary user and host names, instead pass the pre-defined domain qualifier constants (i.e. 'currentUser', 'anyUser', 'currentHost', 'anyHost').\n-}\ngetValue :: Key -> AppID -> UserID -> HostID -> IO (Maybe Plist)\ngetValue = call4 createNullable {#call unsafe CFPreferencesCopyValue as ^ #}\n\n-------------------------- Setting ---------------------------\n{- |\nAdds, modifies, or removes a preference.\n\nNew preference values are stored in the standard application preference location, <~\/Library\/Preferences\/>. When called with 'currentApp', modifications are performed in the preference domain \\\"Current User, Current Application, Any Host.\\\" If you need to create preferences in some other domain, use the low-level function 'setValue'.\n\nYou must call the 'appSync' function in order for your changes to be saved to permanent storage.\n\nWraps @CFPreferencesSetAppValue@.\n-}\nsetAppValue :: Key -> Maybe Plist -> AppID -> IO ()\nsetAppValue key val app =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n {#call unsafe CFPreferencesSetAppValue as ^ #} k v a\n\n{- |\nConvenience function that allows you to set and remove multiple preference values.\n\nBehavior is undefined if a key is in both keysToSet and keysToRemove.\n\nWraps @CFPreferencesSetMultiple@.\n-}\nsetMultiple :: \n Dictionary Key Plist -- ^ values to set\n -> Array Key -- ^ keys to remove \n -> AppID \n -> UserID \n -> HostID \n -> IO ()\nsetMultiple = call5 idScheme {#call unsafe CFPreferencesSetMultiple as ^ #}\n\n{- |\nAdds, modifies, or removes a preference value for the specified domain.\n\nThis function is the primitive set mechanism for the higher level preference function 'setAppValue'. Only the exact domain specified is modified. Do not use this function directly unless you have a specific need. Do not use arbitrary user and host names, instead pass the pre-defined constants.\n\nYou must call the 'sync' function in order for your changes to be saved to permanent storage. Note that you can only save preferences for \\\"Any User\\\" if you have root privileges (or Admin privileges prior to Mac OS X v10.6).\n-}\nsetValue :: Key -> Maybe Plist -> AppID -> UserID -> HostID -> IO ()\nsetValue key val app user host =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n withObject user $ \\u ->\n withObject host $ \\h ->\n {#call unsafe CFPreferencesSetValue as ^ #} k v a u h\n\n------------------------- Synchronizing ---------------\n-- | Exception thrown when 'appSync' or 'sync' fail.\ndata SyncFailed = SyncFailed\n deriving(Typeable)\ninstance Show SyncFailed where\n show _ = \"Syncing Apple preferences failed\"\ninstance Exception SyncFailed\n\n{- |\nWrites to permanent storage all pending changes to the preference data for the application, and reads the latest preference data from permanent storage.\n\nCalling the function 'setAppValue' is not in itself sufficient for storing preferences. The 'appSync' function writes to permanent storage all pending preference changes for the application. Typically you would call this function after multiple calls to 'setAppValue'. Conversely, preference data is cached after it is first read. Changes made externally are not automatically incorporated. The 'appSync' function reads the latest preferences from permanent storage.\n\nThrows 'SyncFailed' if synchronization failed.\n-}\nappSync :: AppID -> IO ()\nappSync = call1 (checkError SyncFailed) {#call unsafe CFPreferencesAppSynchronize as ^ #}\n\n{- |\nFor the specified domain, writes all pending changes to preference data to permanent storage, and reads latest preference data from permanent storage.\n\nThis function is the primitive synchronize mechanism for the higher level preference function 'appSync'; it writes updated preferences to permanent storage, and reads the latest preferences from permanent storage. Only the exact domain specified is modified. Note that to modify \\\"Any User\\\" preferences requires root privileges (or Admin privileges prior to Mac OS X v10.6) - see \n-}\nsync :: AppID -> UserID -> HostID -> IO ()\nsync = call3 (checkError SyncFailed) {#call unsafe CFPreferencesSynchronize as ^ #}\n\n---------------------- Suite preferences -----------\n{- |\nAdds suite preferences to an application\u2019s preference search chain.\n\nSuite preferences allow you to maintain a set of preferences that are common to all applications in the suite. When a suite is added to an application\u2019s search chain, all of the domains pertaining to that suite are inserted into the chain. Suite preferences are added between the \\\"Current Application\\\" domains and the \\\"Any Application\\\" domains. If you add multiple suite preferences to one application, the order of the suites in the search chain is non-deterministic. You can override a suite preference for a given application by defining the same preference key in the application specific preferences.\n\nWraps @CFPreferencesAddSuitePreferencesToApp@.\n-}\naddSuiteToApp :: AppID -> SuiteID -> IO ()\naddSuiteToApp = call2 idScheme {#call unsafe CFPreferencesAddSuitePreferencesToApp as ^ #}\n\n{- |\nRemoves suite preferences from an application\u2019s search chain.\n-}\nremoveSuiteFromApp :: AppID -> SuiteID -> IO ()\nremoveSuiteFromApp = call2 idScheme {#call unsafe CFPreferencesRemoveSuitePreferencesFromApp as ^ #}\n\n----------------------- Misc ------------------\n{- |\nDetermines whether or not a given key has been imposed on the user.\n\nIn cases where machines and\/or users are under some kind of management, you should use this function to determine whether or not to disable UI elements corresponding to those preference keys.\n-}\nappValueIsForced :: Key -> AppID -> IO Bool\nappValueIsForced = call2 (Foreign.toBool <$>) {#call unsafe CFPreferencesAppValueIsForced as ^ #}\n\n{- |\nConstructs and returns the list of all applications that have preferences in the scope of the specified user and host.\n-}\ngetAppList :: UserID -> HostID -> IO (Array AppID)\ngetAppList = call2 create {#call unsafe CFPreferencesCopyApplicationList as ^ #}\n\n\n-- marshalling utils\ncheckError exception gen = do\n res <- gen\n when (res == 0) $ throw exception\n\nwithMaybe Nothing f = f nullPtr\nwithMaybe (Just o) f = withObject o f\n\ncall1 scheme f = \\arg1 ->\n withObject arg1 $ \\parg1 ->\n scheme $\n f parg1\n\ncall2 scheme f = \\arg1 arg2 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n scheme $\n f parg1 parg2\n\ncall3 scheme f = \\arg1 arg2 arg3 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n scheme $\n f parg1 parg2 parg3\n\ncall4 scheme f = \\arg1 arg2 arg3 arg4 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n scheme $\n f parg1 parg2 parg3 parg4\n\ncall5 scheme f = \\arg1 arg2 arg3 arg4 arg5 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n withObject arg5 $ \\parg5 ->\n scheme $\n f parg1 parg2 parg3 parg4 parg5\n\n","old_contents":"{- |\nCore Foundation provides a simple, standard way to manage user (and application) preferences. Core Foundation stores preferences as key-value pairs that are assigned a scope using a combination of user name, application ID, and host (computer) names. This makes it possible to save and retrieve preferences that apply to different classes of users. Core Foundation preferences is useful to all applications that support user preferences. Note that modification of some preferences domains (those not belonging to the \\\"Current User\\\") requires root privileges (or Admin privileges prior to Mac OS X v10.6)-see Authorization Services Programming Guide ()\nfor information on how to gain suitable privileges.\n-}\nmodule CoreFoundation.Preferences(\n -- * Types\n Key,\n AppID,\n anyApp,\n currentApp,\n HostID,\n anyHost,\n currentHost,\n UserID,\n anyUser,\n currentUser,\n -- * Getting\n getAppValue,\n getKeyList,\n getMultiple,\n getValue,\n -- * Setting\n setAppValue,\n setMultiple,\n setValue,\n -- * Synchronizing\n SyncFailed(..),\n appSync,\n sync,\n -- * Misc\n appValueIsForced,\n getAppList,\n ) where\n\nimport Prelude hiding(String)\n\nimport CoreFoundation.Base\nimport CoreFoundation.String\nimport CoreFoundation.Array\nimport CoreFoundation.Dictionary\nimport CoreFoundation.PropertyList\n#include \n#include \"cbits.h\"\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Exception\nimport Data.Typeable\nimport Foreign\nimport Foreign.C.Types\n\n{#pointer CFStringRef -> CFString#}\n{#pointer CFArrayRef -> CFArray#}\n{#pointer CFDictionaryRef -> CFDictionary#}\n{#pointer CFPropertyListRef -> CFPropertyList#}\n\n-- | Keys. These can be constructed using the OverloadedStrings\n-- language extension.\ntype Key = String\n\n-- | ID of a suite, for example @com.apple.iApps@.\ntype SuiteID = String\n\n-- | Application ID. Takes the form of a java package name, @com.foosoft@, or one of the constants 'anyApp', 'currentApp'.\ntype AppID = String\n\n-- | Matches any application. This may be passed to functions which \\\"search\\\", such as 'getAppValue', 'getValue', 'getKeyList', etc. However, this may not be passed to functions which put a value in a specific location, such as 'setAppValue', 'syncApp'.\nanyApp :: AppID\nanyApp = constant {#call pure unsafe hsAnyApp#}\n\n-- | Specifies the current application\ncurrentApp :: AppID\ncurrentApp = constant {#call pure unsafe hsCurrentApp#}\n\n-- | Host ID. User-provided, or see the constants 'anyHost', 'currentHost'\ntype HostID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any host. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all hosts.\nanyHost :: HostID\nanyHost = constant {#call pure unsafe hsAnyHost#}\n\n-- | Current host\ncurrentHost :: HostID\ncurrentHost = constant {#call pure unsafe hsCurrentHost#}\n\n-- | User ID. User-provided, or see the constants 'anyUser',\n -- 'currentUser'\ntype UserID = String\n\n-- | When passed to functions which \\\"search\\\", such as 'getValue', 'getKeyList', etc, this allows the search to match any user. When passed to \\\"setting\\\" functions such as 'setValue', 'sync', it sets the value for all users.\nanyUser :: UserID\nanyUser = constant {#call pure unsafe hsAnyUser#}\n\n-- | Current user\ncurrentUser :: UserID\ncurrentUser = constant {#call pure unsafe hsCurrentUser#}\n\n------------------------- Getting ----------------------------\n{- |\nObtains a preference value for the specified key and application. Wraps CFPreferencesCopyAppValue.\n-}\ngetAppValue :: Key -> AppID -> IO (Maybe Plist)\ngetAppValue = call2 createNullable {#call unsafe CFPreferencesCopyAppValue as ^#}\n\n{- |\nConstructs and returns the list of all keys set in the specified domain. Wraps CFPreferencesCopyKeyList\n-}\ngetKeyList :: AppID -> UserID -> HostID -> IO (Array Key)\ngetKeyList = call3 create {#call unsafe CFPreferencesCopyKeyList as ^ #}\n\n{- |\nReturns a dictionary containing preference values for multiple keys. If no values were located, returns an empty dictionary. \n-}\ngetMultiple :: Array Key -> AppID -> UserID -> HostID -> IO (Dictionary Key Plist)\ngetMultiple = call4 create {#call unsafe CFPreferencesCopyMultiple as ^ #}\n\n{- |\nReturns a preference value for a given domain.\n\nThis function is the primitive get mechanism for the higher level preference function 'getAppValue'. Unlike the high-level function, 'getValue' searches only the exact domain specified. Do not use this function directly unless you have a need. Do not use arbitrary user and host names, instead pass the pre-defined domain qualifier constants (i.e. 'currentUser', 'anyUser', 'currentHost', 'anyHost').\n-}\ngetValue :: Key -> AppID -> UserID -> HostID -> IO (Maybe Plist)\ngetValue = call4 createNullable {#call unsafe CFPreferencesCopyValue as ^ #}\n\n-------------------------- Setting ---------------------------\n{- |\nAdds, modifies, or removes a preference.\n\nNew preference values are stored in the standard application preference location, <~\/Library\/Preferences\/>. When called with 'currentApp', modifications are performed in the preference domain \\\"Current User, Current Application, Any Host.\\\" If you need to create preferences in some other domain, use the low-level function 'setValue'.\n\nYou must call the 'appSync' function in order for your changes to be saved to permanent storage.\n\nWraps @CFPreferencesSetAppValue@.\n-}\nsetAppValue :: Key -> Maybe Plist -> AppID -> IO ()\nsetAppValue key val app =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n {#call unsafe CFPreferencesSetAppValue as ^ #} k v a\n\n{- |\nConvenience function that allows you to set and remove multiple preference values.\n\nBehavior is undefined if a key is in both keysToSet and keysToRemove.\n\nWraps @CFPreferencesSetMultiple@.\n-}\nsetMultiple :: \n Dictionary Key Plist -- ^ values to set\n -> Array Key -- ^ keys to remove \n -> AppID \n -> UserID \n -> HostID \n -> IO ()\nsetMultiple = call5 idScheme {#call unsafe CFPreferencesSetMultiple as ^ #}\n\n{- |\nAdds, modifies, or removes a preference value for the specified domain.\n\nThis function is the primitive set mechanism for the higher level preference function 'setAppValue'. Only the exact domain specified is modified. Do not use this function directly unless you have a specific need. Do not use arbitrary user and host names, instead pass the pre-defined constants.\n\nYou must call the 'sync' function in order for your changes to be saved to permanent storage. Note that you can only save preferences for \\\"Any User\\\" if you have root privileges (or Admin privileges prior to Mac OS X v10.6).\n-}\nsetValue :: Key -> Maybe Plist -> AppID -> UserID -> HostID -> IO ()\nsetValue key val app user host =\n withObject key $ \\k ->\n withMaybe val $ \\v ->\n withObject app $ \\a ->\n withObject user $ \\u ->\n withObject host $ \\h ->\n {#call unsafe CFPreferencesSetValue as ^ #} k v a u h\n\n------------------------- Synchronizing ---------------\n-- | Exception thrown when 'appSync' or 'sync' fail.\ndata SyncFailed = SyncFailed\n deriving(Typeable)\ninstance Show SyncFailed where\n show _ = \"Syncing Apple preferences failed\"\ninstance Exception SyncFailed\n\n{- |\nWrites to permanent storage all pending changes to the preference data for the application, and reads the latest preference data from permanent storage.\n\nCalling the function 'setAppValue' is not in itself sufficient for storing preferences. The 'appSync' function writes to permanent storage all pending preference changes for the application. Typically you would call this function after multiple calls to 'setAppValue'. Conversely, preference data is cached after it is first read. Changes made externally are not automatically incorporated. The 'appSync' function reads the latest preferences from permanent storage.\n\nThrows 'SyncFailed' if synchronization failed.\n-}\nappSync :: AppID -> IO ()\nappSync = call1 (checkError SyncFailed) {#call unsafe CFPreferencesAppSynchronize as ^ #}\n\n{- |\nFor the specified domain, writes all pending changes to preference data to permanent storage, and reads latest preference data from permanent storage.\n\nThis function is the primitive synchronize mechanism for the higher level preference function 'appSync'; it writes updated preferences to permanent storage, and reads the latest preferences from permanent storage. Only the exact domain specified is modified. Note that to modify \\\"Any User\\\" preferences requires root privileges (or Admin privileges prior to Mac OS X v10.6) - see \n-}\nsync :: AppID -> UserID -> HostID -> IO ()\nsync = call3 (checkError SyncFailed) {#call unsafe CFPreferencesSynchronize as ^ #}\n\n---------------------- Suite preferences -----------\n{- |\nAdds suite preferences to an application\u2019s preference search chain.\n\nSuite preferences allow you to maintain a set of preferences that are common to all applications in the suite. When a suite is added to an application\u2019s search chain, all of the domains pertaining to that suite are inserted into the chain. Suite preferences are added between the \\\"Current Application\\\" domains and the \\\"Any Application\\\" domains. If you add multiple suite preferences to one application, the order of the suites in the search chain is non-deterministic. You can override a suite preference for a given application by defining the same preference key in the application specific preferences.\n\nWraps @CFPreferencesAddSuitePreferencesToApp@.\n-}\naddSuiteToApp :: AppID -> SuiteID -> IO ()\naddSuiteToApp = call2 idScheme {#call unsafe CFPreferencesAddSuitePreferencesToApp as ^ #}\n\n{- |\nRemoves suite preferences from an application\u2019s search chain.\n-}\nremoveSuiteFromApp :: AppID -> SuiteID -> IO ()\nremoveSuiteFromApp = call2 idScheme {#call unsafe CFPreferencesRemoveSuitePreferencesFromApp as ^ #}\n\n----------------------- Misc ------------------\n{- |\nDetermines whether or not a given key has been imposed on the user.\n\nIn cases where machines and\/or users are under some kind of management, you should use this function to determine whether or not to disable UI elements corresponding to those preference keys.\n-}\nappValueIsForced :: Key -> AppID -> IO Bool\nappValueIsForced = call2 (Foreign.toBool <$>) {#call unsafe CFPreferencesAppValueIsForced as ^ #}\n\n{- |\nConstructs and returns the list of all applications that have preferences in the scope of the specified user and host.\n-}\ngetAppList :: UserID -> HostID -> IO (Array AppID)\ngetAppList = call2 create {#call unsafe CFPreferencesCopyApplicationList as ^ #}\n\n\n-- marshalling utils\ncheckError exception gen = do\n res <- gen\n when (res == 0) $ throw exception\n\nwithMaybe Nothing f = f nullPtr\nwithMaybe (Just o) f = withObject o f\n\ncall1 scheme f = \\arg1 ->\n withObject arg1 $ \\parg1 ->\n scheme $\n f parg1\n\ncall2 scheme f = \\arg1 arg2 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n scheme $\n f parg1 parg2\n\ncall3 scheme f = \\arg1 arg2 arg3 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n scheme $\n f parg1 parg2 parg3\n\ncall4 scheme f = \\arg1 arg2 arg3 arg4 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n scheme $\n f parg1 parg2 parg3 parg4\n\ncall5 scheme f = \\arg1 arg2 arg3 arg4 arg5 ->\n withObject arg1 $ \\parg1 ->\n withObject arg2 $ \\parg2 ->\n withObject arg3 $ \\parg3 ->\n withObject arg4 $ \\parg4 ->\n withObject arg5 $ \\parg5 ->\n scheme $\n f parg1 parg2 parg3 parg4 parg5\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"25260d44fa7f93f0a13e73980393b3ccc1a9aac7","subject":"add compute-compatibility 3.7","message":"add compute-compatibility 3.7\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 2 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Jetson TK1 (speculative)\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 3 7 -> DeviceResources 32 2048 16 64 192 114688 256 131072 256 4 266 Warp -- Kepler GK21x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n Compute 5 2 -> DeviceResources 32 2048 32 64 128 98304 256 65536 256 4 255 Warp -- Maxwell GM20x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: Unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 2 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Jetson TK1 (speculative)\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n Compute 5 2 -> DeviceResources 32 2048 32 64 128 98304 256 65536 256 4 255 Warp -- Maxwell GM20x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: Unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1b0688d1649d93f4545f25e9bbeb594371ac5c0a","subject":"Generalized blit to work on color images","message":"Generalized blit to work on color images\n","repos":"BeautifulDestinations\/CV,aleator\/CV,aleator\/CV,TomMD\/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 -- | 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","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, 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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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":"25bae01cad20e847b32d26ffb4d07b66e2171fee","subject":"type role Ref nominal","message":"type role Ref nominal\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Types.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Types.chs","new_contents":"{-# LANGUAGE CPP, EmptyDataDecls, ExistentialQuantification, RoleAnnotations #-}\n\n#ifdef CALLSTACK_AVAILABLE\n{-# LANGUAGE ImplicitParams #-}\n#endif\n\nmodule Graphics.UI.FLTK.LowLevel.Fl_Types where\n#include \"Fl_Types.h\"\n#include \"Fl_Text_EditorC.h\"\n#include \"FL\/platform_types.h\"\nimport Foreign\nimport Foreign.C hiding (CClock)\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport qualified Foreign.ForeignPtr.Unsafe as Unsafe\nimport Debug.Trace\nimport Control.Exception\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport qualified Data.Text as T\n#if defined(CALLSTACK_AVAILABLE) || defined(HASCALLSTACK_AVAILABLE)\nimport GHC.Stack\n#endif\nimport qualified Data.ByteString as B\n#c\n enum SliderType {\n VertSliderType = FL_VERT_SLIDER,\n HorSliderType = FL_HOR_SLIDER,\n VertFillSliderType = FL_VERT_FILL_SLIDER,\n HorFillSliderType = FL_HOR_FILL_SLIDER,\n VertNiceSliderType = FL_VERT_NICE_SLIDER,\n HorNiceSliderType = FL_HOR_NICE_SLIDER\n };\n enum ScrollbarType {\n VertScrollbar = FL_VERT_SLIDER,\n HorScrollbar = FL_HOR_SLIDER\n };\n enum BrowserType {\n NormalBrowserType = FL_NORMAL_BROWSER,\n SelectBrowserType = FL_SELECT_BROWSER,\n HoldBrowserType = FL_HOLD_BROWSER,\n MultiBrowserType = FL_MULTI_BROWSER\n };\n enum SortType {\n SortAscending = FL_SORT_ASCENDING,\n SortDescending = FL_SORT_DESCENDING\n };\n enum FileBrowserType {\n FileBrowserFiles = FL_FILE_BROWSER_FILES,\n FileBrowserDirectories = FL_FILE_BROWSER_DIRECTORIES,\n };\n enum FileIconType {\n FileIconAny = FL_FILE_ICON_ANY,\n FileIconPlain = FL_FILE_ICON_PLAIN,\n FileIconFifo = FL_FILE_ICON_FIFO,\n FileIconDevice = FL_FILE_ICON_DEVICE,\n FileIconLink = FL_FILE_ICON_LINK,\n FileIconDirectory = FL_FILE_ICON_DIRECTORY\n };\n enum FileIconProps {\n FileIconEnd = FL_FILE_ICON_END,\n FileIconColor = FL_FILE_ICON_COLOR,\n FileIconLine = FL_FILE_ICON_LINE,\n FileIconClosedline = FL_FILE_ICON_CLOSEDLINE,\n FileIconPolygon = FL_FILE_ICON_POLYGON,\n FileIconOutlinepolygon = FL_FILE_ICON_OUTLINEPOLYGON,\n FileIconVertex = FL_FILE_ICON_VERTEX\n };\n enum FileChooserType {\n FileChooserSingle = FL_FILE_CHOOSER_SINGLE,\n FileChooserMulti = FL_FILE_CHOOSER_MULTI,\n FileChooserCreate = FL_FILE_CHOOSER_CREATE,\n FileChooserDirectory = FL_FILE_CHOOSER_DIRECTORY\n };\n enum ButtonType{\n NormalButtonType = FL_NORMAL_BUTTON,\n ToggleButtonType = FL_TOGGLE_BUTTON,\n RadioButtonType = FL_RADIO_BUTTON,\n HiddenButtonType = FL_HIDDEN_BUTTON\n };\n enum TreeReasonType {\n TreeReasonNone = FL_TREE_REASON_NONE,\n TreeReasonSelected = FL_TREE_REASON_SELECTED,\n TreeReasonDeselected = FL_TREE_REASON_DESELECTED,\n TreeReasonReselected = FL_TREE_REASON_RESELECTED,\n TreeReasonOpened = FL_TREE_REASON_OPENED,\n TreeReasonClosed = FL_TREE_REASON_CLOSED,\n TreeReasonDragged = FL_TREE_REASON_DRAGGED\n };\n enum MenuItemFlag{\n MenuItemNormal = 0,\n MenuItemInactive = FL_MENU_INACTIVE,\n MenuItemToggle = FL_MENU_TOGGLE,\n MenuItemValue = FL_MENU_VALUE,\n MenuItemRadio = FL_MENU_RADIO,\n MenuItemInvisible = FL_MENU_INVISIBLE,\n SubmenuPointer = FL_SUBMENU_POINTER,\n Submenu = FL_SUBMENU,\n MenuItemDivider = FL_MENU_DIVIDER,\n MenuItemHorizontal = FL_MENU_HORIZONTAL\n };\n enum ScrollbarMode {\n HorizontalScrollBar = HORIZONTAL,\n VerticalScrollBar = VERTICAL,\n BothScrollBar = BOTH,\n AlwaysOnScrollBar = ALWAYS_ON,\n HorizontalAlwaysScrollBar = HORIZONTAL_ALWAYS,\n VerticalAlwaysScrollBar = VERTICAL_ALWAYS,\n BothAlwaysScrollBar = BOTH_ALWAYS\n };\n enum CursorType {\n NormalCursor = NORMAL_CURSOR,\n CaretCursor = CARET_CURSOR,\n DimCursor = DIM_CURSOR,\n BlockCursor = BLOCK_CURSOR,\n HeavyCursor = HEAVY_CURSOR,\n SimpleCursor = SIMPLE_CURSOR\n };\n enum PositionType {\n CursorPos = CURSOR_POS,\n CharacterPos = CHARACTER_POS\n };\n enum DragType {\n DragNone = DRAG_NONE,\n DragStartDnd = DRAG_START_DND,\n DragChar = DRAG_CHAR,\n DragWord = DRAG_WORD,\n DragLine = DRAG_LINE\n };\n enum WrapTypeFl {\n WrapNoneFl = WRAP_NONE,\n WrapAtColumnFl = WRAP_AT_COLUMN,\n WrapAtPixelFl = WRAP_AT_PIXEL,\n WrapAtBoundsFl = WRAP_AT_BOUNDS\n };\n enum PageFormat {\n A0 = 0,\n A1 = 1,\n A2 = 2,\n A3 = 3,\n A4 = 4,\n A5 = 5,\n A6 = 6,\n A7 = 7,\n A8 = 8,\n A9 = 9,\n B0 = 10,\n B1 = 11,\n B2 = 12,\n B3 = 13,\n B4 = 14,\n B5 = 15,\n B6 = 16,\n B7 = 17,\n B8 = 18,\n B9 = 19,\n B10 = 20,\n C5E = 21,\n DLE = 22,\n Executive = EXECUTIVE,\n Folio = FOLIO,\n Ledger = LEDGER,\n Legal = LEGAL,\n Letter = LETTER,\n Tabloid = TABLOID,\n Envelope = ENVELOPE,\n Media = MEDIA\n };\n enum PageLayout {\n Portrait = PORTRAIT,\n Landscape = LANDSCAPE,\n Reversed = REVERSED,\n Orientation = ORIENTATION\n };\n typedef struct KeyBinding {\n int key;\n int state;\n fl_Key_Func* function;\n } KeyBinding;\n enum TableRowSelectMode {\n SelectNone = SELECT_NONEC,\n SelectSingle = SELECT_SINGLEC,\n SelectMulti = SELECT_MULTIC\n };\n enum TableContext {\n ContextNone = CONTEXT_NONEC,\n ContextStartPage = CONTEXT_STARTPAGEC,\n ContextEndPage = CONTEXT_ENDPAGEC,\n ContextRowHeader = CONTEXT_ROW_HEADERC,\n ContextColHeader = CONTEXT_COL_HEADERC,\n ContextCell = CONTEXT_CELLC,\n ContextTable = CONTEXT_TABLEC,\n ContextRCResize = CONTEXT_RC_RESIZEC\n };\n enum LinePosition {\n LinePositionTop = TOP,\n LinePositionMiddle = MIDDLE,\n LinePositionBottom = BOTTOM\n };\n enum PackType {\n PackVertical = PACK_VERTICAL,\n PackHorizontal = PACK_HORIZONTAL\n };\n enum ColorChooserMode {\n RgbMode = 0,\n ByteMode = 1,\n HexMode = 2,\n HsvMode = 3\n };\n#endc\n{#enum SliderType {} deriving (Show, Eq, Ord) #}\n{#enum ScrollbarType {} deriving (Show, Eq, Ord) #}\n{#enum BrowserType {} deriving (Show, Eq, Ord) #}\n{#enum SortType {} deriving (Show, Eq, Ord) #}\n{#enum FileBrowserType {} deriving (Show, Eq, Ord) #}\n{#enum FileIconType {} deriving (Show, Eq, Ord) #}\n{#enum FileIconProps {} deriving (Show, Eq, Ord) #}\n{#enum FileChooserType {} deriving (Show, Eq, Ord) #}\n{#enum ButtonType {} deriving (Show, Eq, Ord) #}\n{#enum TreeReasonType {} deriving (Show, Eq, Ord) #}\n{#enum MenuItemFlag {} deriving (Show, Eq, Ord) #}\n{#enum ColorChooserMode {} deriving (Show, Eq, Ord) #}\nnewtype MenuItemFlags = MenuItemFlags [MenuItemFlag] deriving (Eq, Show, Ord)\nallMenuItemFlags :: [MenuItemFlag]\nallMenuItemFlags =\n [\n MenuItemInactive,\n MenuItemToggle,\n MenuItemValue,\n MenuItemRadio,\n MenuItemInvisible,\n SubmenuPointer,\n Submenu,\n MenuItemDivider,\n MenuItemHorizontal\n ]\n{#enum CursorType {} deriving (Show, Eq, Ord) #}\n{#enum PositionType {} deriving (Show, Eq, Ord) #}\n{#enum DragType {} deriving (Show, Eq, Ord) #}\n{#enum WrapTypeFl {} deriving (Show, Eq, Ord) #}\ndata WrapType = WrapNone | WrapAtColumn ColumnNumber | WrapAtPixel PixelPosition | WrapAtBounds deriving (Eq, Show, Ord)\n{#enum PageFormat {} deriving (Show, Eq, Ord) #}\n{#enum PageLayout {} deriving (Show, Eq, Ord) #}\n{#enum TableRowSelectMode {} deriving (Show, Eq, Ord) #}\n{#enum TableContext {} deriving (Show, Eq, Ord) #}\n{#enum LinePosition {} deriving (Show, Eq, Ord) #}\n{#enum ScrollbarMode {} deriving (Show, Eq, Ord) #}\ndata StyleTableEntry = StyleTableEntry (Maybe Color) (Maybe Font) (Maybe FontSize) deriving (Eq, Show, Ord)\n{#enum PackType{} deriving (Show, Eq, Ord) #}\ntype FlShortcut = {#type Fl_Shortcut #}\ntype FlColor = {#type Fl_Color #}\ntype FlFont = {#type Fl_Font #}\ntype FlAlign = {#type Fl_Align #}\ntype LineDelta = Maybe Int\ntype Delta = Maybe Int\ntype FlIntPtr = {#type fl_intptr_t #}\ntype FlUIntPtr = {#type fl_uintptr_t#}\ntype ID = {#type ID#}\ntype Fl_Offscreen = {#type Fl_Offscreen #}\ntype Fl_Socket = {#type FL_SOCKET #}\ntype Fl_Bitmask = {#type Fl_Bitmask #}\ntype Fl_Region = {#type Fl_Region #}\nnewtype WindowHandle = WindowHandle (Ptr ())\n\nnewtype NumInserted = NumInserted Int deriving (Show, Eq, Ord)\nnewtype NumDeleted = NumDeleted Int deriving (Show, Eq, Ord)\nnewtype NumRestyled = NumRestyled Int deriving (Show, Eq, Ord)\nnewtype DeletedText = DeletedText T.Text deriving (Show, Eq, Ord)\n\ntype role Ref nominal\ndata Ref a = Ref !(ForeignPtr (Ptr ())) deriving (Eq, Show, Ord)\ndata FunRef = FunRef !(FunPtr ())\n-- * The FLTK widget hierarchy\ndata CBase parent\ntype Base = CBase ()\n\ntype GlobalCallback = IO ()\ntype CallbackWithUserDataPrim = Ptr () -> Ptr () -> IO ()\ntype CallbackPrim = Ptr () -> IO ()\ntype CustomColorAveragePrim = Ptr () -> CUInt -> CFloat -> IO ()\ntype CustomImageDrawPrim = Ptr () -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()\ntype CustomImageCopyPrim = Ptr () -> CInt -> CInt -> IO (Ptr ())\ntype GlobalEventHandlerPrim = CInt -> IO CInt\ntype GlobalEventHandlerF = Event -> IO Int\ntype DrawCallback = T.Text -> Position -> IO ()\ntype DrawCallbackPrim = CString -> CInt -> CInt -> CInt -> IO ()\ntype TextBufferCallback = FunPtr (Ptr () -> IO ())\ntype FileChooserCallback = FunPtr (Ptr () -> Ptr () -> IO())\ntype SharedImageHandler = FunPtr (CString -> CUChar -> CInt -> Ptr ())\ntype BoxDrawF = Rectangle -> Color -> IO ()\ntype BoxDrawFPrim = CInt -> CInt -> CInt -> CInt -> FlColor -> IO ()\ntype FDHandlerPrim = Fl_Socket -> Ptr () -> IO ()\ntype FDHandler = FlSocket -> IO ()\ntype TextModifyCb = AtIndex -> NumInserted -> NumDeleted -> NumRestyled -> DeletedText -> IO ()\ntype TextModifyCbPrim = CInt -> CInt -> CInt -> CInt -> Ptr CChar -> Ptr () -> IO ()\ntype TextPredeleteCb = AtIndex -> NumDeleted -> IO ()\ntype TextPredeleteCbPrim = CInt -> CInt -> Ptr () -> IO ()\ntype UnfinishedStyleCb = AtIndex -> IO ()\ntype UnfinishedStyleCbPrim = CInt -> Ptr () -> IO ()\ntype MenuItemDrawF = Ptr () -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> IO ()\ntype TabPositionsPrim = Ptr () -> Ptr CInt -> Ptr CInt -> IO CInt\ntype TabHeightPrim = Ptr () -> IO CInt\ntype TabWhichPrim = Ptr () -> CInt -> CInt -> IO (Ptr ())\ntype TabClientAreaPrim = Ptr () -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> CInt -> IO ()\ntype GetDoublePrim = Ptr () -> IO (CDouble)\ntype GetIntPrim = Ptr () -> IO CInt\ntype SetIntPrim = Ptr () -> CInt -> IO ()\ntype ColorSetPrim = Ptr () -> CDouble -> CDouble -> CDouble -> IO CInt\ntype DestroyCallbacksPrim = Ptr () -> Ptr () -> IO ()\n\nnewtype Width = Width Int deriving (Eq, Show, Ord)\nnewtype Height = Height Int deriving (Eq, Show, Ord)\nnewtype PreciseWidth = PreciseWidth Double deriving (Eq, Show, Ord)\nnewtype PreciseHeight = PreciseHeight Double deriving (Eq, Show, Ord)\nnewtype Depth = Depth Int deriving (Eq, Show, Ord)\nnewtype LineSize = LineSize Int deriving (Eq, Show, Ord)\nnewtype X = X Int deriving (Eq, Show, Ord)\nnewtype PreciseX = PreciseX Double deriving (Eq, Show, Ord)\nnewtype Y = Y Int deriving (Eq, Show, Ord)\nnewtype PreciseY = PreciseY Double deriving (Eq, Show, Ord)\nnewtype ByX = ByX Double deriving (Eq, Show, Ord)\nnewtype ByY = ByY Double deriving (Eq, Show, Ord)\nnewtype Angle = Angle CShort deriving (Eq, Show, Ord)\nnewtype PreciseAngle = PreciseAngle Double deriving (Eq, Show, Ord)\ndata Position = Position X Y deriving (Eq, Show, Ord)\ndata PrecisePosition = PrecisePosition PreciseX PreciseY deriving (Eq, Show, Ord)\ndata CountDirection = CountUp | CountDown deriving (Eq, Show, Ord)\ndata DPI = DPI Float Float deriving (Eq, Show, Ord)\nnewtype TextDisplayStyle = TextDisplayStyle CInt deriving (Eq, Show, Ord)\ndata IndexRange = IndexRange AtIndex AtIndex deriving (Eq, Show, Ord)\nstatusToIndexRange :: (Ptr CInt -> Ptr CInt -> IO Int) -> IO (Maybe IndexRange)\nstatusToIndexRange f =\n alloca $ \\start' ->\n alloca $ \\end' ->\n f start' end' >>= \\status' ->\n case status' of\n 0 -> return Nothing\n _ -> do\n start'' <- peekIntConv start'\n end'' <- peekIntConv end'\n return (Just (IndexRange (AtIndex start'') (AtIndex end'')))\n\ndata ColorChooserRGB = Decimals (Between0And1, Between0And1, Between0And1) | Words RGB deriving (Eq, Show, Ord)\ndata Rectangle = Rectangle { rectanglePosition :: Position , rectangleSize :: Size } deriving (Eq, Show, Ord)\ndata ByXY = ByXY ByX ByY deriving (Eq, Show, Ord)\ndata Intersection = Contained | Partial deriving (Eq, Show, Ord)\ndata Size = Size Width Height deriving (Eq, Show, Ord)\ndata PreciseSize = PreciseSize PreciseWidth PreciseHeight deriving (Eq, Show, Ord)\nnewtype Lines = Lines Int deriving (Eq,Show,Ord)\nnewtype LineNumber = LineNumber Int deriving (Eq,Show,Ord)\nnewtype ColumnNumber = ColumnNumber Int deriving (Eq, Show, Ord)\nnewtype PixelPosition = PixelPosition Int deriving (Eq,Show,Ord)\nnewtype AtIndex = AtIndex Int deriving (Eq,Show,Ord)\nnewtype Rows = Rows Int deriving (Eq,Show,Ord)\nnewtype Columns = Columns Int deriving (Eq,Show,Ord)\ndata KeyType = SpecialKeyType SpecialKey | NormalKeyType Char deriving (Eq, Show, Ord)\ndata ShortcutKeySequence = ShortcutKeySequence [EventState] KeyType deriving (Eq, Show, Ord)\ndata Shortcut = KeySequence ShortcutKeySequence | KeyFormat T.Text deriving (Eq, Show, Ord)\ndata KeyBindingKeySequence = KeyBindingKeySequence (Maybe [EventState]) KeyType deriving (Eq, Show, Ord)\nnewtype Between0And1 = Between0And1 Double deriving (Eq, Show, Ord)\nnewtype Between0And6 = Between0And6 Double deriving (Eq, Show, Ord)\ndata ScreenLocation = Intersect Rectangle\n | ScreenNumber Int\n | ScreenPosition Position deriving (Eq, Show, Ord)\nnewtype FontSize = FontSize CInt deriving (Eq, Show, Ord)\nnewtype PixmapHs = PixmapHs [T.Text] deriving (Eq, Show, Ord)\ndata BitmapHs = BitmapHs B.ByteString Size deriving (Eq, Show, Ord)\ndata Clipboard = InternalClipboard | SharedClipboard deriving (Eq, Show, Ord)\ndata OutOfRangeOrNotSubmenu = OutOfRangeOrNotSubmenu deriving (Eq, Show, Ord)\n-- | The type of 'Fl_Offscreen' varies wildly from platform to platform. Feel free to examine the insides when debugging\n-- but any computation based on it will probably not be portable.\nnewtype FlOffscreen = FlOffscreen Fl_Offscreen\nnewtype FlBitmask = FlBitmask Fl_Bitmask\nnewtype FlRegion = FlRegion Fl_Region\nnewtype FlSocket = FlSocket Fl_Socket\n#if GLSUPPORT\ntype Fl_GlContext = {#type GLContext #}\nnewtype FlGlContext = FlGlContext Fl_GlContext\n#endif\nsuccessOrOutOfRangeOrNotSubmenu :: Int -> Either OutOfRangeOrNotSubmenu ()\nsuccessOrOutOfRangeOrNotSubmenu status = if (status == (-1)) then Left OutOfRangeOrNotSubmenu else Right ()\ndata AwakeRingFull = AwakeRingFull deriving (Eq, Show, Ord)\nsuccessOrAwakeRingFull :: Int -> Either AwakeRingFull ()\nsuccessOrAwakeRingFull status = if (status == (-1)) then Left AwakeRingFull else Right ()\ndata UnknownEvent = UnknownEvent deriving (Eq, Show, Ord)\nsuccessOrUnknownEvent :: Int -> Either UnknownEvent ()\nsuccessOrUnknownEvent status = if (status == 0) then Left UnknownEvent else Right ()\ndata UnknownError = UnknownError deriving (Eq, Show, Ord)\nsuccessOrUnknownError :: a -> Int -> Either UnknownError a\nsuccessOrUnknownError a result = if (result == 0) then (Left UnknownError) else (Right a)\ndata NotFound = NotFound deriving (Eq, Show, Ord)\ndata OutOfRange = OutOfRange deriving (Eq, Show, Ord)\nsuccessOrOutOfRange :: a -> Bool -> (a -> IO b) -> IO (Either OutOfRange b)\nsuccessOrOutOfRange a pred' tr = if pred' then return (Left OutOfRange) else tr a >>= return . Right\ndata NoChange = NoChange deriving (Eq, Show, Ord)\nsuccessOrNoChange :: Int -> Either NoChange ()\nsuccessOrNoChange status = if (status == 0) then Left NoChange else Right ()\ndata DataProcessingError = NoDataProcessedError | PartialDataProcessedError | UnknownDataError Int\nsuccessOrDataProcessingError :: Int -> Either DataProcessingError ()\nsuccessOrDataProcessingError status = case status of\n 0 -> Right ()\n 1 -> Left NoDataProcessedError\n 2 -> Left PartialDataProcessedError\n x -> Left $ UnknownDataError x\nnewtype PreferredSize = PreferredSize Int deriving (Eq, Show, Ord)\nnewtype GapSize = GapSize Int deriving (Eq, Show, Ord)\ndata DrawShortcut = NormalDrawShortcut | ElideAmpersandDrawShortcut deriving (Eq,Show,Ord)\ndata ResolveImageLabelConflict = ResolveImageLabelOverwrite | ResolveImageLabelDoNothing deriving (Show)\ndata MultiLabelShrinkError = MultiLabelShrinkError deriving Show\ntoRectangle :: (Int,Int,Int,Int) -> Rectangle\ntoRectangle (x_pos, y_pos, width, height) =\n Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))\n\nfromRectangle :: Rectangle -> (Int,Int,Int,Int)\nfromRectangle (Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n (x_pos, y_pos, width, height)\n\ntoSize :: (Int, Int) -> Size\ntoSize (width', height') = Size (Width width') (Height height')\n\ntoPosition :: (Int,Int) -> Position\ntoPosition (xPos', yPos') = Position (X xPos') (Y yPos')\n\ntoPrecisePosition :: Position -> PrecisePosition\ntoPrecisePosition (Position (X xPos') (Y yPos')) =\n PrecisePosition\n (PreciseX (fromIntegral xPos'))\n (PreciseY (fromIntegral yPos'))\n\ntoPreciseSize :: Size -> PreciseSize\ntoPreciseSize (Size (Width w) (Height h)) =\n PreciseSize\n (PreciseWidth (fromIntegral w))\n (PreciseHeight (fromIntegral h))\n\nthrowStackOnError :: IO a -> IO a\nthrowStackOnError f =\n f `catch` throwStack\n where\n throwStack :: SomeException -> IO b\n throwStack e = traceStack (show e) $ error \"\"\n\nwithForeignPtrs :: [ForeignPtr a] -> ([Ptr a] -> IO c) -> IO c\nwithForeignPtrs fptrs io = do\n let ptrs = map Unsafe.unsafeForeignPtrToPtr fptrs\n r <- io ptrs\n mapM_ touchForeignPtr fptrs\n return r\n\n#ifdef CALLSTACK_AVAILABLE\ntoRefPtr :: (?loc :: CallStack) => Ptr (Ptr a) -> IO (Ptr a)\n#elif defined(HASCALLSTACK_AVAILABLE)\ntoRefPtr :: HasCallStack => Ptr (Ptr a) -> IO (Ptr a)\n#else\ntoRefPtr :: Ptr (Ptr a) -> IO (Ptr a)\n#endif\ntoRefPtr ptrToRefPtr = do\n refPtr <- peek ptrToRefPtr\n if (refPtr == nullPtr)\n#ifdef CALLSTACK_AVAILABLE\n then error $ \"Ref does not exist. \" ++ (showCallStack ?loc)\n#elif defined(HASCALLSTACK_AVAILABLE)\n then error $ \"Ref does not exist. \" ++ (prettyCallStack callStack)\n#else\n then error \"Ref does not exist. \"\n#endif\n else return refPtr\n\n#ifdef CALLSTACK_AVAILABLE\nwithRef :: (?loc :: CallStack) => Ref a -> (Ptr b -> IO c) -> IO c\n#elif defined(HASCALLSTACK_AVAILABLE)\nwithRef :: HasCallStack => Ref a -> (Ptr b -> IO c) -> IO c\n#else\nwithRef :: Ref a -> (Ptr b -> IO c) -> IO c\n#endif\nwithRef (Ref fptr) f =\n throwStackOnError $\n withForeignPtr fptr\n (\\ptrToRefPtr -> do\n refPtr <- toRefPtr ptrToRefPtr\n f (castPtr refPtr)\n )\n\nisNull :: Ref a -> IO Bool\nisNull (Ref fptr) =\n withForeignPtr fptr\n (\\ptrToRefPtr -> do\n refPtr <- peek ptrToRefPtr\n return (refPtr == nullPtr)\n )\n\n#ifdef CALLSTACK_AVAILABLE\nunsafeRefToPtr :: (?loc :: CallStack) => Ref a -> IO (Ptr ())\n#elif defined(HASCALLSTACK_AVAILABLE)\nunsafeRefToPtr :: HasCallStack => Ref a -> IO (Ptr ())\n#else\nunsafeRefToPtr :: Ref a -> IO (Ptr ())\n#endif\nunsafeRefToPtr (Ref fptr) =\n throwStackOnError $ do\n refPtr <- toRefPtr $ Unsafe.unsafeForeignPtrToPtr fptr\n return $ castPtr refPtr\n\n#ifdef CALLSTACK_AVAILABLE\nwithRefs :: (?loc :: CallStack) => [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\n#elif HASCALLSTACK_AVAILABLE\nwithRefs :: HasCallStack => [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\n#else\nwithRefs :: [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\n#endif\nwithRefs refs f =\n throwStackOnError\n $ withForeignPtrs\n (map (\\(Ref fptr) -> fptr) refs)\n (\\ptrToRefPtrs -> do\n refPtrs <- mapM toRefPtr ptrToRefPtrs\n arrayPtr <- newArray refPtrs\n f (castPtr arrayPtr)\n )\n\nwithMaybeRef :: Maybe (Ref a) -> (Ptr () -> IO c) -> IO c\nwithMaybeRef (Just o) f = withRef o f\nwithMaybeRef Nothing f = f (castPtr nullPtr)\n\nswapRef :: Ref a -> (Ptr b -> IO (Ptr ())) -> IO ()\nswapRef ref@(Ref fptr) f = do\n result <- withRef ref f\n withForeignPtr fptr $ \\p -> poke p result\n\nwrapInRef :: ForeignPtr (Ptr ()) -> Ref a\nwrapInRef = Ref . castForeignPtr\n\ntoFunRef :: FunPtr a -> FunRef\ntoFunRef fptr = FunRef $ castFunPtr fptr\n\nfromFunRef :: FunRef -> (FunPtr ())\nfromFunRef (FunRef f) = castFunPtr f\n\nrefPtrEquals :: Ref a -> Ref b -> IO Bool\nrefPtrEquals w1 w2 = do\n w1Null <- isNull w1\n w2Null <- isNull w2\n if (w1Null || w2Null) then return False\n else withRef w1 (\\w1Ptr -> withRef w2 (\\w2Ptr -> return (w1Ptr == w2Ptr)))\n\nunpackFunctionPointerToFreeStruct :: Ptr () -> IO (CInt, Ptr (FunPtr (IO ())))\nunpackFunctionPointerToFreeStruct fpts = do\n numFps <- {#get Function_Pointers_To_Free->length #} fpts\n fpArray <- {#get Function_Pointers_To_Free->function_pointer_array #} fpts\n return (numFps, fpArray)\n","old_contents":"{-# LANGUAGE CPP, EmptyDataDecls, ExistentialQuantification #-}\n\n#ifdef CALLSTACK_AVAILABLE\n{-# LANGUAGE ImplicitParams #-}\n#endif\n\nmodule Graphics.UI.FLTK.LowLevel.Fl_Types where\n#include \"Fl_Types.h\"\n#include \"Fl_Text_EditorC.h\"\n#include \"FL\/platform_types.h\"\nimport Foreign\nimport Foreign.C hiding (CClock)\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport qualified Foreign.ForeignPtr.Unsafe as Unsafe\nimport Debug.Trace\nimport Control.Exception\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport qualified Data.Text as T\n#if defined(CALLSTACK_AVAILABLE) || defined(HASCALLSTACK_AVAILABLE)\nimport GHC.Stack\n#endif\nimport qualified Data.ByteString as B\n#c\n enum SliderType {\n VertSliderType = FL_VERT_SLIDER,\n HorSliderType = FL_HOR_SLIDER,\n VertFillSliderType = FL_VERT_FILL_SLIDER,\n HorFillSliderType = FL_HOR_FILL_SLIDER,\n VertNiceSliderType = FL_VERT_NICE_SLIDER,\n HorNiceSliderType = FL_HOR_NICE_SLIDER\n };\n enum ScrollbarType {\n VertScrollbar = FL_VERT_SLIDER,\n HorScrollbar = FL_HOR_SLIDER\n };\n enum BrowserType {\n NormalBrowserType = FL_NORMAL_BROWSER,\n SelectBrowserType = FL_SELECT_BROWSER,\n HoldBrowserType = FL_HOLD_BROWSER,\n MultiBrowserType = FL_MULTI_BROWSER\n };\n enum SortType {\n SortAscending = FL_SORT_ASCENDING,\n SortDescending = FL_SORT_DESCENDING\n };\n enum FileBrowserType {\n FileBrowserFiles = FL_FILE_BROWSER_FILES,\n FileBrowserDirectories = FL_FILE_BROWSER_DIRECTORIES,\n };\n enum FileIconType {\n FileIconAny = FL_FILE_ICON_ANY,\n FileIconPlain = FL_FILE_ICON_PLAIN,\n FileIconFifo = FL_FILE_ICON_FIFO,\n FileIconDevice = FL_FILE_ICON_DEVICE,\n FileIconLink = FL_FILE_ICON_LINK,\n FileIconDirectory = FL_FILE_ICON_DIRECTORY\n };\n enum FileIconProps {\n FileIconEnd = FL_FILE_ICON_END,\n FileIconColor = FL_FILE_ICON_COLOR,\n FileIconLine = FL_FILE_ICON_LINE,\n FileIconClosedline = FL_FILE_ICON_CLOSEDLINE,\n FileIconPolygon = FL_FILE_ICON_POLYGON,\n FileIconOutlinepolygon = FL_FILE_ICON_OUTLINEPOLYGON,\n FileIconVertex = FL_FILE_ICON_VERTEX\n };\n enum FileChooserType {\n FileChooserSingle = FL_FILE_CHOOSER_SINGLE,\n FileChooserMulti = FL_FILE_CHOOSER_MULTI,\n FileChooserCreate = FL_FILE_CHOOSER_CREATE,\n FileChooserDirectory = FL_FILE_CHOOSER_DIRECTORY\n };\n enum ButtonType{\n NormalButtonType = FL_NORMAL_BUTTON,\n ToggleButtonType = FL_TOGGLE_BUTTON,\n RadioButtonType = FL_RADIO_BUTTON,\n HiddenButtonType = FL_HIDDEN_BUTTON\n };\n enum TreeReasonType {\n TreeReasonNone = FL_TREE_REASON_NONE,\n TreeReasonSelected = FL_TREE_REASON_SELECTED,\n TreeReasonDeselected = FL_TREE_REASON_DESELECTED,\n TreeReasonReselected = FL_TREE_REASON_RESELECTED,\n TreeReasonOpened = FL_TREE_REASON_OPENED,\n TreeReasonClosed = FL_TREE_REASON_CLOSED,\n TreeReasonDragged = FL_TREE_REASON_DRAGGED\n };\n enum MenuItemFlag{\n MenuItemNormal = 0,\n MenuItemInactive = FL_MENU_INACTIVE,\n MenuItemToggle = FL_MENU_TOGGLE,\n MenuItemValue = FL_MENU_VALUE,\n MenuItemRadio = FL_MENU_RADIO,\n MenuItemInvisible = FL_MENU_INVISIBLE,\n SubmenuPointer = FL_SUBMENU_POINTER,\n Submenu = FL_SUBMENU,\n MenuItemDivider = FL_MENU_DIVIDER,\n MenuItemHorizontal = FL_MENU_HORIZONTAL\n };\n enum ScrollbarMode {\n HorizontalScrollBar = HORIZONTAL,\n VerticalScrollBar = VERTICAL,\n BothScrollBar = BOTH,\n AlwaysOnScrollBar = ALWAYS_ON,\n HorizontalAlwaysScrollBar = HORIZONTAL_ALWAYS,\n VerticalAlwaysScrollBar = VERTICAL_ALWAYS,\n BothAlwaysScrollBar = BOTH_ALWAYS\n };\n enum CursorType {\n NormalCursor = NORMAL_CURSOR,\n CaretCursor = CARET_CURSOR,\n DimCursor = DIM_CURSOR,\n BlockCursor = BLOCK_CURSOR,\n HeavyCursor = HEAVY_CURSOR,\n SimpleCursor = SIMPLE_CURSOR\n };\n enum PositionType {\n CursorPos = CURSOR_POS,\n CharacterPos = CHARACTER_POS\n };\n enum DragType {\n DragNone = DRAG_NONE,\n DragStartDnd = DRAG_START_DND,\n DragChar = DRAG_CHAR,\n DragWord = DRAG_WORD,\n DragLine = DRAG_LINE\n };\n enum WrapTypeFl {\n WrapNoneFl = WRAP_NONE,\n WrapAtColumnFl = WRAP_AT_COLUMN,\n WrapAtPixelFl = WRAP_AT_PIXEL,\n WrapAtBoundsFl = WRAP_AT_BOUNDS\n };\n enum PageFormat {\n A0 = 0,\n A1 = 1,\n A2 = 2,\n A3 = 3,\n A4 = 4,\n A5 = 5,\n A6 = 6,\n A7 = 7,\n A8 = 8,\n A9 = 9,\n B0 = 10,\n B1 = 11,\n B2 = 12,\n B3 = 13,\n B4 = 14,\n B5 = 15,\n B6 = 16,\n B7 = 17,\n B8 = 18,\n B9 = 19,\n B10 = 20,\n C5E = 21,\n DLE = 22,\n Executive = EXECUTIVE,\n Folio = FOLIO,\n Ledger = LEDGER,\n Legal = LEGAL,\n Letter = LETTER,\n Tabloid = TABLOID,\n Envelope = ENVELOPE,\n Media = MEDIA\n };\n enum PageLayout {\n Portrait = PORTRAIT,\n Landscape = LANDSCAPE,\n Reversed = REVERSED,\n Orientation = ORIENTATION\n };\n typedef struct KeyBinding {\n int key;\n int state;\n fl_Key_Func* function;\n } KeyBinding;\n enum TableRowSelectMode {\n SelectNone = SELECT_NONEC,\n SelectSingle = SELECT_SINGLEC,\n SelectMulti = SELECT_MULTIC\n };\n enum TableContext {\n ContextNone = CONTEXT_NONEC,\n ContextStartPage = CONTEXT_STARTPAGEC,\n ContextEndPage = CONTEXT_ENDPAGEC,\n ContextRowHeader = CONTEXT_ROW_HEADERC,\n ContextColHeader = CONTEXT_COL_HEADERC,\n ContextCell = CONTEXT_CELLC,\n ContextTable = CONTEXT_TABLEC,\n ContextRCResize = CONTEXT_RC_RESIZEC\n };\n enum LinePosition {\n LinePositionTop = TOP,\n LinePositionMiddle = MIDDLE,\n LinePositionBottom = BOTTOM\n };\n enum PackType {\n PackVertical = PACK_VERTICAL,\n PackHorizontal = PACK_HORIZONTAL\n };\n enum ColorChooserMode {\n RgbMode = 0,\n ByteMode = 1,\n HexMode = 2,\n HsvMode = 3\n };\n#endc\n{#enum SliderType {} deriving (Show, Eq, Ord) #}\n{#enum ScrollbarType {} deriving (Show, Eq, Ord) #}\n{#enum BrowserType {} deriving (Show, Eq, Ord) #}\n{#enum SortType {} deriving (Show, Eq, Ord) #}\n{#enum FileBrowserType {} deriving (Show, Eq, Ord) #}\n{#enum FileIconType {} deriving (Show, Eq, Ord) #}\n{#enum FileIconProps {} deriving (Show, Eq, Ord) #}\n{#enum FileChooserType {} deriving (Show, Eq, Ord) #}\n{#enum ButtonType {} deriving (Show, Eq, Ord) #}\n{#enum TreeReasonType {} deriving (Show, Eq, Ord) #}\n{#enum MenuItemFlag {} deriving (Show, Eq, Ord) #}\n{#enum ColorChooserMode {} deriving (Show, Eq, Ord) #}\nnewtype MenuItemFlags = MenuItemFlags [MenuItemFlag] deriving (Eq, Show, Ord)\nallMenuItemFlags :: [MenuItemFlag]\nallMenuItemFlags =\n [\n MenuItemInactive,\n MenuItemToggle,\n MenuItemValue,\n MenuItemRadio,\n MenuItemInvisible,\n SubmenuPointer,\n Submenu,\n MenuItemDivider,\n MenuItemHorizontal\n ]\n{#enum CursorType {} deriving (Show, Eq, Ord) #}\n{#enum PositionType {} deriving (Show, Eq, Ord) #}\n{#enum DragType {} deriving (Show, Eq, Ord) #}\n{#enum WrapTypeFl {} deriving (Show, Eq, Ord) #}\ndata WrapType = WrapNone | WrapAtColumn ColumnNumber | WrapAtPixel PixelPosition | WrapAtBounds deriving (Eq, Show, Ord)\n{#enum PageFormat {} deriving (Show, Eq, Ord) #}\n{#enum PageLayout {} deriving (Show, Eq, Ord) #}\n{#enum TableRowSelectMode {} deriving (Show, Eq, Ord) #}\n{#enum TableContext {} deriving (Show, Eq, Ord) #}\n{#enum LinePosition {} deriving (Show, Eq, Ord) #}\n{#enum ScrollbarMode {} deriving (Show, Eq, Ord) #}\ndata StyleTableEntry = StyleTableEntry (Maybe Color) (Maybe Font) (Maybe FontSize) deriving (Eq, Show, Ord)\n{#enum PackType{} deriving (Show, Eq, Ord) #}\ntype FlShortcut = {#type Fl_Shortcut #}\ntype FlColor = {#type Fl_Color #}\ntype FlFont = {#type Fl_Font #}\ntype FlAlign = {#type Fl_Align #}\ntype LineDelta = Maybe Int\ntype Delta = Maybe Int\ntype FlIntPtr = {#type fl_intptr_t #}\ntype FlUIntPtr = {#type fl_uintptr_t#}\ntype ID = {#type ID#}\ntype Fl_Offscreen = {#type Fl_Offscreen #}\ntype Fl_Socket = {#type FL_SOCKET #}\ntype Fl_Bitmask = {#type Fl_Bitmask #}\ntype Fl_Region = {#type Fl_Region #}\nnewtype WindowHandle = WindowHandle (Ptr ())\n\nnewtype NumInserted = NumInserted Int deriving (Show, Eq, Ord)\nnewtype NumDeleted = NumDeleted Int deriving (Show, Eq, Ord)\nnewtype NumRestyled = NumRestyled Int deriving (Show, Eq, Ord)\nnewtype DeletedText = DeletedText T.Text deriving (Show, Eq, Ord)\n\ndata Ref a = Ref !(ForeignPtr (Ptr ())) deriving (Eq, Show, Ord)\ndata FunRef = FunRef !(FunPtr ())\n-- * The FLTK widget hierarchy\ndata CBase parent\ntype Base = CBase ()\n\ntype GlobalCallback = IO ()\ntype CallbackWithUserDataPrim = Ptr () -> Ptr () -> IO ()\ntype CallbackPrim = Ptr () -> IO ()\ntype CustomColorAveragePrim = Ptr () -> CUInt -> CFloat -> IO ()\ntype CustomImageDrawPrim = Ptr () -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()\ntype CustomImageCopyPrim = Ptr () -> CInt -> CInt -> IO (Ptr ())\ntype GlobalEventHandlerPrim = CInt -> IO CInt\ntype GlobalEventHandlerF = Event -> IO Int\ntype DrawCallback = T.Text -> Position -> IO ()\ntype DrawCallbackPrim = CString -> CInt -> CInt -> CInt -> IO ()\ntype TextBufferCallback = FunPtr (Ptr () -> IO ())\ntype FileChooserCallback = FunPtr (Ptr () -> Ptr () -> IO())\ntype SharedImageHandler = FunPtr (CString -> CUChar -> CInt -> Ptr ())\ntype BoxDrawF = Rectangle -> Color -> IO ()\ntype BoxDrawFPrim = CInt -> CInt -> CInt -> CInt -> FlColor -> IO ()\ntype FDHandlerPrim = Fl_Socket -> Ptr () -> IO ()\ntype FDHandler = FlSocket -> IO ()\ntype TextModifyCb = AtIndex -> NumInserted -> NumDeleted -> NumRestyled -> DeletedText -> IO ()\ntype TextModifyCbPrim = CInt -> CInt -> CInt -> CInt -> Ptr CChar -> Ptr () -> IO ()\ntype TextPredeleteCb = AtIndex -> NumDeleted -> IO ()\ntype TextPredeleteCbPrim = CInt -> CInt -> Ptr () -> IO ()\ntype UnfinishedStyleCb = AtIndex -> IO ()\ntype UnfinishedStyleCbPrim = CInt -> Ptr () -> IO ()\ntype MenuItemDrawF = Ptr () -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> IO ()\ntype TabPositionsPrim = Ptr () -> Ptr CInt -> Ptr CInt -> IO CInt\ntype TabHeightPrim = Ptr () -> IO CInt\ntype TabWhichPrim = Ptr () -> CInt -> CInt -> IO (Ptr ())\ntype TabClientAreaPrim = Ptr () -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> CInt -> IO ()\ntype GetDoublePrim = Ptr () -> IO (CDouble)\ntype GetIntPrim = Ptr () -> IO CInt\ntype SetIntPrim = Ptr () -> CInt -> IO ()\ntype ColorSetPrim = Ptr () -> CDouble -> CDouble -> CDouble -> IO CInt\ntype DestroyCallbacksPrim = Ptr () -> Ptr () -> IO ()\n\nnewtype Width = Width Int deriving (Eq, Show, Ord)\nnewtype Height = Height Int deriving (Eq, Show, Ord)\nnewtype PreciseWidth = PreciseWidth Double deriving (Eq, Show, Ord)\nnewtype PreciseHeight = PreciseHeight Double deriving (Eq, Show, Ord)\nnewtype Depth = Depth Int deriving (Eq, Show, Ord)\nnewtype LineSize = LineSize Int deriving (Eq, Show, Ord)\nnewtype X = X Int deriving (Eq, Show, Ord)\nnewtype PreciseX = PreciseX Double deriving (Eq, Show, Ord)\nnewtype Y = Y Int deriving (Eq, Show, Ord)\nnewtype PreciseY = PreciseY Double deriving (Eq, Show, Ord)\nnewtype ByX = ByX Double deriving (Eq, Show, Ord)\nnewtype ByY = ByY Double deriving (Eq, Show, Ord)\nnewtype Angle = Angle CShort deriving (Eq, Show, Ord)\nnewtype PreciseAngle = PreciseAngle Double deriving (Eq, Show, Ord)\ndata Position = Position X Y deriving (Eq, Show, Ord)\ndata PrecisePosition = PrecisePosition PreciseX PreciseY deriving (Eq, Show, Ord)\ndata CountDirection = CountUp | CountDown deriving (Eq, Show, Ord)\ndata DPI = DPI Float Float deriving (Eq, Show, Ord)\nnewtype TextDisplayStyle = TextDisplayStyle CInt deriving (Eq, Show, Ord)\ndata IndexRange = IndexRange AtIndex AtIndex deriving (Eq, Show, Ord)\nstatusToIndexRange :: (Ptr CInt -> Ptr CInt -> IO Int) -> IO (Maybe IndexRange)\nstatusToIndexRange f =\n alloca $ \\start' ->\n alloca $ \\end' ->\n f start' end' >>= \\status' ->\n case status' of\n 0 -> return Nothing\n _ -> do\n start'' <- peekIntConv start'\n end'' <- peekIntConv end'\n return (Just (IndexRange (AtIndex start'') (AtIndex end'')))\n\ndata ColorChooserRGB = Decimals (Between0And1, Between0And1, Between0And1) | Words RGB deriving (Eq, Show, Ord)\ndata Rectangle = Rectangle { rectanglePosition :: Position , rectangleSize :: Size } deriving (Eq, Show, Ord)\ndata ByXY = ByXY ByX ByY deriving (Eq, Show, Ord)\ndata Intersection = Contained | Partial deriving (Eq, Show, Ord)\ndata Size = Size Width Height deriving (Eq, Show, Ord)\ndata PreciseSize = PreciseSize PreciseWidth PreciseHeight deriving (Eq, Show, Ord)\nnewtype Lines = Lines Int deriving (Eq,Show,Ord)\nnewtype LineNumber = LineNumber Int deriving (Eq,Show,Ord)\nnewtype ColumnNumber = ColumnNumber Int deriving (Eq, Show, Ord)\nnewtype PixelPosition = PixelPosition Int deriving (Eq,Show,Ord)\nnewtype AtIndex = AtIndex Int deriving (Eq,Show,Ord)\nnewtype Rows = Rows Int deriving (Eq,Show,Ord)\nnewtype Columns = Columns Int deriving (Eq,Show,Ord)\ndata KeyType = SpecialKeyType SpecialKey | NormalKeyType Char deriving (Eq, Show, Ord)\ndata ShortcutKeySequence = ShortcutKeySequence [EventState] KeyType deriving (Eq, Show, Ord)\ndata Shortcut = KeySequence ShortcutKeySequence | KeyFormat T.Text deriving (Eq, Show, Ord)\ndata KeyBindingKeySequence = KeyBindingKeySequence (Maybe [EventState]) KeyType deriving (Eq, Show, Ord)\nnewtype Between0And1 = Between0And1 Double deriving (Eq, Show, Ord)\nnewtype Between0And6 = Between0And6 Double deriving (Eq, Show, Ord)\ndata ScreenLocation = Intersect Rectangle\n | ScreenNumber Int\n | ScreenPosition Position deriving (Eq, Show, Ord)\nnewtype FontSize = FontSize CInt deriving (Eq, Show, Ord)\nnewtype PixmapHs = PixmapHs [T.Text] deriving (Eq, Show, Ord)\ndata BitmapHs = BitmapHs B.ByteString Size deriving (Eq, Show, Ord)\ndata Clipboard = InternalClipboard | SharedClipboard deriving (Eq, Show, Ord)\ndata OutOfRangeOrNotSubmenu = OutOfRangeOrNotSubmenu deriving (Eq, Show, Ord)\n-- | The type of 'Fl_Offscreen' varies wildly from platform to platform. Feel free to examine the insides when debugging\n-- but any computation based on it will probably not be portable.\nnewtype FlOffscreen = FlOffscreen Fl_Offscreen\nnewtype FlBitmask = FlBitmask Fl_Bitmask\nnewtype FlRegion = FlRegion Fl_Region\nnewtype FlSocket = FlSocket Fl_Socket\n#if GLSUPPORT\ntype Fl_GlContext = {#type GLContext #}\nnewtype FlGlContext = FlGlContext Fl_GlContext\n#endif\nsuccessOrOutOfRangeOrNotSubmenu :: Int -> Either OutOfRangeOrNotSubmenu ()\nsuccessOrOutOfRangeOrNotSubmenu status = if (status == (-1)) then Left OutOfRangeOrNotSubmenu else Right ()\ndata AwakeRingFull = AwakeRingFull deriving (Eq, Show, Ord)\nsuccessOrAwakeRingFull :: Int -> Either AwakeRingFull ()\nsuccessOrAwakeRingFull status = if (status == (-1)) then Left AwakeRingFull else Right ()\ndata UnknownEvent = UnknownEvent deriving (Eq, Show, Ord)\nsuccessOrUnknownEvent :: Int -> Either UnknownEvent ()\nsuccessOrUnknownEvent status = if (status == 0) then Left UnknownEvent else Right ()\ndata UnknownError = UnknownError deriving (Eq, Show, Ord)\nsuccessOrUnknownError :: a -> Int -> Either UnknownError a\nsuccessOrUnknownError a result = if (result == 0) then (Left UnknownError) else (Right a)\ndata NotFound = NotFound deriving (Eq, Show, Ord)\ndata OutOfRange = OutOfRange deriving (Eq, Show, Ord)\nsuccessOrOutOfRange :: a -> Bool -> (a -> IO b) -> IO (Either OutOfRange b)\nsuccessOrOutOfRange a pred' tr = if pred' then return (Left OutOfRange) else tr a >>= return . Right\ndata NoChange = NoChange deriving (Eq, Show, Ord)\nsuccessOrNoChange :: Int -> Either NoChange ()\nsuccessOrNoChange status = if (status == 0) then Left NoChange else Right ()\ndata DataProcessingError = NoDataProcessedError | PartialDataProcessedError | UnknownDataError Int\nsuccessOrDataProcessingError :: Int -> Either DataProcessingError ()\nsuccessOrDataProcessingError status = case status of\n 0 -> Right ()\n 1 -> Left NoDataProcessedError\n 2 -> Left PartialDataProcessedError\n x -> Left $ UnknownDataError x\nnewtype PreferredSize = PreferredSize Int deriving (Eq, Show, Ord)\nnewtype GapSize = GapSize Int deriving (Eq, Show, Ord)\ndata DrawShortcut = NormalDrawShortcut | ElideAmpersandDrawShortcut deriving (Eq,Show,Ord)\ndata ResolveImageLabelConflict = ResolveImageLabelOverwrite | ResolveImageLabelDoNothing deriving (Show)\ndata MultiLabelShrinkError = MultiLabelShrinkError deriving Show\ntoRectangle :: (Int,Int,Int,Int) -> Rectangle\ntoRectangle (x_pos, y_pos, width, height) =\n Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))\n\nfromRectangle :: Rectangle -> (Int,Int,Int,Int)\nfromRectangle (Rectangle (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n (x_pos, y_pos, width, height)\n\ntoSize :: (Int, Int) -> Size\ntoSize (width', height') = Size (Width width') (Height height')\n\ntoPosition :: (Int,Int) -> Position\ntoPosition (xPos', yPos') = Position (X xPos') (Y yPos')\n\ntoPrecisePosition :: Position -> PrecisePosition\ntoPrecisePosition (Position (X xPos') (Y yPos')) =\n PrecisePosition\n (PreciseX (fromIntegral xPos'))\n (PreciseY (fromIntegral yPos'))\n\ntoPreciseSize :: Size -> PreciseSize\ntoPreciseSize (Size (Width w) (Height h)) =\n PreciseSize\n (PreciseWidth (fromIntegral w))\n (PreciseHeight (fromIntegral h))\n\nthrowStackOnError :: IO a -> IO a\nthrowStackOnError f =\n f `catch` throwStack\n where\n throwStack :: SomeException -> IO b\n throwStack e = traceStack (show e) $ error \"\"\n\nwithForeignPtrs :: [ForeignPtr a] -> ([Ptr a] -> IO c) -> IO c\nwithForeignPtrs fptrs io = do\n let ptrs = map Unsafe.unsafeForeignPtrToPtr fptrs\n r <- io ptrs\n mapM_ touchForeignPtr fptrs\n return r\n\n#ifdef CALLSTACK_AVAILABLE\ntoRefPtr :: (?loc :: CallStack) => Ptr (Ptr a) -> IO (Ptr a)\n#elif defined(HASCALLSTACK_AVAILABLE)\ntoRefPtr :: HasCallStack => Ptr (Ptr a) -> IO (Ptr a)\n#else\ntoRefPtr :: Ptr (Ptr a) -> IO (Ptr a)\n#endif\ntoRefPtr ptrToRefPtr = do\n refPtr <- peek ptrToRefPtr\n if (refPtr == nullPtr)\n#ifdef CALLSTACK_AVAILABLE\n then error $ \"Ref does not exist. \" ++ (showCallStack ?loc)\n#elif defined(HASCALLSTACK_AVAILABLE)\n then error $ \"Ref does not exist. \" ++ (prettyCallStack callStack)\n#else\n then error \"Ref does not exist. \"\n#endif\n else return refPtr\n\n#ifdef CALLSTACK_AVAILABLE\nwithRef :: (?loc :: CallStack) => Ref a -> (Ptr b -> IO c) -> IO c\n#elif defined(HASCALLSTACK_AVAILABLE)\nwithRef :: HasCallStack => Ref a -> (Ptr b -> IO c) -> IO c\n#else\nwithRef :: Ref a -> (Ptr b -> IO c) -> IO c\n#endif\nwithRef (Ref fptr) f =\n throwStackOnError $\n withForeignPtr fptr\n (\\ptrToRefPtr -> do\n refPtr <- toRefPtr ptrToRefPtr\n f (castPtr refPtr)\n )\n\nisNull :: Ref a -> IO Bool\nisNull (Ref fptr) =\n withForeignPtr fptr\n (\\ptrToRefPtr -> do\n refPtr <- peek ptrToRefPtr\n return (refPtr == nullPtr)\n )\n\n#ifdef CALLSTACK_AVAILABLE\nunsafeRefToPtr :: (?loc :: CallStack) => Ref a -> IO (Ptr ())\n#elif defined(HASCALLSTACK_AVAILABLE)\nunsafeRefToPtr :: HasCallStack => Ref a -> IO (Ptr ())\n#else\nunsafeRefToPtr :: Ref a -> IO (Ptr ())\n#endif\nunsafeRefToPtr (Ref fptr) =\n throwStackOnError $ do\n refPtr <- toRefPtr $ Unsafe.unsafeForeignPtrToPtr fptr\n return $ castPtr refPtr\n\n#ifdef CALLSTACK_AVAILABLE\nwithRefs :: (?loc :: CallStack) => [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\n#elif HASCALLSTACK_AVAILABLE\nwithRefs :: HasCallStack => [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\n#else\nwithRefs :: [Ref a] -> (Ptr (Ptr b) -> IO c) -> IO c\n#endif\nwithRefs refs f =\n throwStackOnError\n $ withForeignPtrs\n (map (\\(Ref fptr) -> fptr) refs)\n (\\ptrToRefPtrs -> do\n refPtrs <- mapM toRefPtr ptrToRefPtrs\n arrayPtr <- newArray refPtrs\n f (castPtr arrayPtr)\n )\n\nwithMaybeRef :: Maybe (Ref a) -> (Ptr () -> IO c) -> IO c\nwithMaybeRef (Just o) f = withRef o f\nwithMaybeRef Nothing f = f (castPtr nullPtr)\n\nswapRef :: Ref a -> (Ptr b -> IO (Ptr ())) -> IO ()\nswapRef ref@(Ref fptr) f = do\n result <- withRef ref f\n withForeignPtr fptr $ \\p -> poke p result\n\nwrapInRef :: ForeignPtr (Ptr ()) -> Ref a\nwrapInRef = Ref . castForeignPtr\n\ntoFunRef :: FunPtr a -> FunRef\ntoFunRef fptr = FunRef $ castFunPtr fptr\n\nfromFunRef :: FunRef -> (FunPtr ())\nfromFunRef (FunRef f) = castFunPtr f\n\nrefPtrEquals :: Ref a -> Ref b -> IO Bool\nrefPtrEquals w1 w2 = do\n w1Null <- isNull w1\n w2Null <- isNull w2\n if (w1Null || w2Null) then return False\n else withRef w1 (\\w1Ptr -> withRef w2 (\\w2Ptr -> return (w1Ptr == w2Ptr)))\n\nunpackFunctionPointerToFreeStruct :: Ptr () -> IO (CInt, Ptr (FunPtr (IO ())))\nunpackFunctionPointerToFreeStruct fpts = do\n numFps <- {#get Function_Pointers_To_Free->length #} fpts\n fpArray <- {#get Function_Pointers_To_Free->function_pointer_array #} fpts\n return (numFps, fpArray)\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"d740bc41bdfcea9ff215952cbea8b2461e6c2546","subject":"More types added.","message":"More types added.\n","repos":"joelburget\/assimp,haraldsteinlechner\/assimp,joelburget\/assimp,haraldsteinlechner\/assimp","old_file":"Graphics\/Formats\/Assimp.chs","new_file":"Graphics\/Formats\/Assimp.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Graphics.Formats.Assimp where\n\nimport C2HS\n--import Foreign.Ptr\n--import System.IO.Unsafe\nimport Control.Monad\nimport Control.Applicative ((<$>), (<*>))\n\n#include \"..\/..\/assimp\/include\/assimp.h\" \/\/ Plain-C interface\n#include \"..\/..\/assimp\/include\/aiScene.h\" \/\/ Output data structure\n#include \"..\/..\/assimp\/include\/aiPostProcess.h\" \/\/ Post processing flags\n\n{#context lib=\"assimp\"#}\n\n{#enum define SceneFlags {AI_SCENE_FLAGS_INCOMPLETE as FlagsIncomplete\n , AI_SCENE_FLAGS_VALIDATED as FlagsValidated\n , AI_SCENE_FLAGS_VALIDATION_WARNING as FlagsValidationWarning\n , AI_SCENE_FLAGS_NON_VERBOSE_FORMAT as FlagsNonVerboseFormat\n , AI_SCENE_FLAGS_TERRAIN as FlagsTerrain\n }#}\n\n{#enum aiPostProcessSteps as AiPostProcessSteps {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiReturn as AiReturn {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiOrigin as AiOrigin {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiDefaultLogStream as AiDefaultLogStream {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiPrimitiveType as AiPrimitiveType {underscoreToCase} deriving (Show, Eq)#}\n\n-- This seems to be necessary for #sizeof to work\n#c\ntypedef struct aiScene aiScene;\ntypedef struct aiString aiString;\ntypedef struct aiNode aiNode;\ntypedef struct aiFace aiFace;\ntypedef struct aiVertexWeight aiVertexWeight;\ntypedef struct aiBone aiBone;\ntypedef struct aiMesh aiMesh;\ntypedef struct aiMatrix4x4 aiMatrix4x4;\n#endc\n\n--{#pointer *aiNode as AiNode #}\n--{#pointer *aiScene as AiScene #}\n{#pointer *aiPlane as AiPlane #}\n{#pointer *aiRay as AiRay #}\n{#pointer *aiColor3D as AiColor3D #}\n{#pointer *aiColor4D as AiColor4D #}\n--{#pointer *aiString as AiString #}\n{#pointer *aiMemoryInfo as AiMemoryInfo #}\n{#pointer *aiLogStream as AiLogStream #}\n{#pointer *aiQuaternion as AiQuaternion #}\n{#pointer *aiMatrix3x3 as AiMatrix3x3 #}\n{#pointer *aiMatrix4x4 as AiMatrix4x4 #}\n{#pointer *aiVector3D as AiVector3D #}\n--{#pointer *aiFace as AiFace #}\n--{#pointer *aiVertexWeight as AiVertexWeight #}\n--{#pointer *aiBone as AiBone #}\n--{#pointer *aiMesh as AiMesh #}\n\ndata AiString = AiString\n { length'AiString :: Int\n , data'AiString :: String -- Maximum length MAXLEN\n }\naiStringToString = data'AiString\nstringToAiString x = AiString (length x) x\ninstance Storable AiString where\n sizeOf _ = {#sizeof aiString#}\n alignment _ = 4 -- http:\/\/web.archiveorange.com\/archive\/v\/V6skIGuT4JclKSXDM7Xj\n peek p = liftM2 AiString\n (liftM cIntConv ({#get aiString.length#} p))\n ({#get aiString.data#} p >>= peekCString)\n poke p x = do\n {#set aiString.length#} p (cIntConv $ length'AiString x)\n str <- newCString $ data'AiString x\n {#set aiString.data#} p str\n\n{- From the Assimp source:\n -\n - Nodes are little named entities in the scene that have a place and\n - orientation relative to their parents. Starting from the scene's root node\n - all nodes can have 0 to x child nodes, thus forming a hierarchy. They form\n - the base on which the scene is built on: a node can refer to 0..x meshes,\n - can be referred to by a bone of a mesh or can be animated by a key sequence\n - of an animation. DirectX calls them \"frames\", others call them \"objects\", we\n - call them aiNode.\n -\n - A node can potentially refer to single or multiple meshes. The meshes are\n - not stored inside the node, but instead in an array of aiMesh inside the\n - aiScene. A node only refers to them by their array index. This also means\n - that multiple nodes can refer to the same mesh, which provides a simple form\n - of instancing. A mesh referred to by this way lives in the node's local\n - coordinate system. If you want the mesh's orientation in global space, you'd\n - have to concatenate the transformations from the referring node and all of\n - its parents.\n-}\ndata AiNode = AiNode\n { mName'AiNode :: String\n , mTransformation'AiNode :: AiMatrix4x4\n , mParent'AiNode :: AiNode\n --, mNumChildren'AiNode :: CUInt\n , mChildren'AiNode :: [AiNode]\n --, mNumMeshes'AiNode :: CUInt\n , mMeshes :: [CUInt]\n }\ninstance Storable AiNode where\n sizeOf _ = {#sizeof aiNode#}\n alignment _ = 4\n peek = undefined\n poke = undefined\n --peek p = do\n -- mName <- liftM aiStringToString $ {#get aiNode.mName#} p\n -- mTransformation <- {#get aiNode.mTransformation#} p\n -- mParent <- {#get aiNode.mParent#} p\n -- mNumChildren <- {#get aiNode.mNumChildren#} p\n -- mChildren <- peekArray mNumChildren ({#get aiNode.mChildren#} p) -- TODO\n -- mMeshes <- peekArray ({#get aiNode.mNumMeshes#} p) ({#get aiNode.mMeshes#})\n -- return $ AiNode mName mTransformation mParent mChildren mMeshes\n --poke p (AiNode name trans par chil mes) = do\n -- {#set aiNode.mName#} $ stringToAiString $ mName'AiNode p\n -- {#set aiNode.mTransformation#} $ mTransformation'AiNode p\n -- {#set aiNode.mParent#} $ mParent'AiNode p \n -- {#set aiNode.mChildren#} $ mChildren'AiNode p\n -- {#set aiNode.mMeshes#} $ mMeshes'AiNode p\n\ndata AiFace = AiFace\n { --mNumIndices :: CUInt\n mIndices'AiFace :: [CUInt]\n }\ninstance Storable AiFace where\n sizeOf _ = {#sizeof aiFace#}\n alignment _ = 4\n peek p = do\n mNumIndices <- {#get aiFace.mNumIndices#}\n mIndices <- {#get aiFace.mIndices#}\n lst <- peekArray mNumIndices mIndices\n return $ AiFace lst\n poke p (AiFace mIndices) = do\n {#set aiFace.mNumIndices#} p $ cIntConv $ length mIndices\n newArray mIndices >>= ({#set aiFace.mIndices#} p)\n\ndata AiVertexWeight = AiVertexWeight\n { mVertexId'AiVertexWeight :: CUInt\n , mWeight'AiVertexWeight :: CFloat\n }\ninstance Storable AiVertexWeight where\n sizeOf _ = {#sizeof aiVertexWeight#}\n alignment _ = 4\n peek p = do\n mV <- {#get aiVertexWeight.mVertexId#}\n mW <- {#get aiVertexWeight.mWeight#}\n return $ AiVertexWeight mV mW\n poke p (AiVertexWeight mV mW) = do\n {#set aiVertexWeight.mVertexId#} p mV\n {#set aiVertexWeight.mWeight#} p mW\n\ndata AiBone = AiBone\n { mName'AiBone :: String\n --, mNumWeights :: CUInt\n , mWeights'AiBone :: [AiVertexWeight]\n , mOffsetMatrix'AiBone :: AiMatrix4x4\n }\ninstance Storable AiBone where\n sizeOf _ = {#sizeof aiBone#}\n alignment _ = 4\n peek = undefined\n poke = undefined\n --peek p = do\n -- mN <- liftM peek $ {#get aiBone.mName#} p\n -- mW <- {#get aiBone.mWeights#} p\n -- mO <- {#get aiBone.mOffsetMatrix#} p >>= peek\n -- return $ AiBone mN mW mO\n --poke p (AiBone mN mW mO) = do\n -- {#set aiBone.mName#} p mN\n -- {#set aiBone.mWeights#} p mW\n -- {#set aiBone.mOffsetMatrix#} p mO\n\ndata AiMesh = AiMesh\n { mPrimitiveTypes'AiMesh :: AiPrimitiveType\n --, mNumVertices :: CUInt\n , mVertices'AiMesh :: [AiVector3D]\n , mNormals'AiMesh :: [AiVector3D]\n , mTangents'AiMesh :: [AiVector3D]\n , mBitangents'AiMesh :: [AiVector3D]\n , mColors'AiMesh :: [AiColor4D]\n , mTextureCoords'AiMesh :: [AiVector3D]\n , mNumUVComponents'AiMesh :: CUInt\n --, mNumFaces :: CUInt\n , mFaces'AiMesh :: [AiFace]\n --, mNumBones :: CUInt\n , mBones'AiMesh :: [AiBone]\n , mMaterialIndex'AiMesh :: CUInt\n , mName'AiMesh :: String\n --, mNumAnimMeshes :: CUInt\n --, mAnimMeshes :: [AiAnimMesh]\n }\n\n{#pointer *aiMaterial as AiMaterial#}\n{#pointer *aiAnimation as AiAnimation#}\n{#pointer *aiTexture as AiTexture#}\n{#pointer *aiLight as AiLight#}\n{#pointer *aiCamera as AiCamera#}\n\ndata AiScene = AiScene\n { mFlags'AiScene :: SceneFlags\n\n --, mNumMeshes :: CUInt\n , mMeshes'AiScene :: [AiMesh]\n\n --, mNumMaterials :: CUInt\n , mMaterials'AiScene :: [AiMaterial]\n\n --, mNumAnimations :: CUInt\n , mAnimations'AiScene :: [AiAnimation]\n\n --, mNumTextures :: CUInt\n , mTextures'AiScene :: [AiTexture]\n\n --, mNumLights :: CUInt\n , mLights'AiScene :: [AiLight]\n\n --, mNumCameras :: CUInt\n , mCameras'AiScene :: [AiCamera]\n }\ninstance Storable AiScene where\n sizeOf _ = {#sizeof aiScene#}\n alignment _ = 4\n peek = undefined\n --peek p = do\n -- let mFlags = \n poke p x = undefined--do\n -- {#set aiString.length#} p (cIntConv $ length'AiString x)\n -- str <- newCString $ data'AiString x\n -- {#set aiString.data#} p str\n\n{#fun aiImportFile as ^\n {`String', cFromEnum `SceneFlags'} -> `AiScene' peek#}\n\n-- aiImportFileEx\n-- aiImportFileFromMemory\n\n{#fun aiApplyPostProcessing as ^\n {id `AiScene', cFromEnum `AiPostProcessSteps'} -> `AiScene' id#}\n\n--{#fun aiGetPredefinedLogStream as ^\n-- {cFromEnum `AiDefaultLogStream', `String'} -> `AiLogStream' id#}\n\n-- aiAttachLogStream\n-- aiEnableVerboseLogging\n-- aiDetachLogStream\n-- aiDetachAllLogStreams\n\n{#fun aiReleaseImport as ^\n {id `AiScene'} -> `()'#}\n\n{#fun aiGetErrorString as ^\n {} -> `String'#}\n\n{#fun aiIsExtensionSupported as ^\n {`String'} -> `Bool'#}\n\n-- aiGetExtensionList\n-- aiGetMemoryRequirements\n\n{# fun aiSetImportPropertyInteger as ^\n {`String', `Int'} -> `()'#}\n\n{# fun aiSetImportPropertyFloat as ^\n {`String', `Float'} -> `()'#}\n\n--{# fun aiSetImportPropertyString as ^\n-- {`String', `AiString'} -> `()'#}\n\n-- aiCreateQuaternionFromMatrix\n-- aiDecomposeMatrix\n-- aiTransposematrix4\n-- aiTransposematrix3\n-- aiTransformVecByMatrix3\n-- aiTransformVecByMatrix4\n-- aiMultiplyMatrix3\n-- aiMultiplyMatrix4\n-- aiIdentityMatrix3\n-- aiIdentityMatrix4\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Graphics.Formats.Assimp where\n\nimport C2HS\n--import Foreign.Ptr\n--import System.IO.Unsafe\n--import Foreign.C\n\n#include \"..\/..\/assimp\/include\/assimp.h\" \/\/ Plain-C interface\n#include \"..\/..\/assimp\/include\/aiScene.h\" \/\/ Output data structure\n#include \"..\/..\/assimp\/include\/aiPostProcess.h\" \/\/ Post processing flags\n\n{#context lib=\"assimp\"#}\n\n{#enum define SceneFlags {AI_SCENE_FLAGS_INCOMPLETE as FlagsIncomplete\n , AI_SCENE_FLAGS_VALIDATED as FlagsValidated\n , AI_SCENE_FLAGS_VALIDATION_WARNING as FlagsValidationWarning\n , AI_SCENE_FLAGS_NON_VERBOSE_FORMAT as FlagsNonVerboseFormat\n , AI_SCENE_FLAGS_TERRAIN as FlagsTerrain\n }#}\n\n{#enum aiPostProcessSteps as AiPostProcessSteps {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiReturn as AiReturn {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiOrigin as AiOrigin {underscoreToCase} deriving (Show, Eq)#}\n{#enum aiDefaultLogStream as AiDefaultLogStream {underscoreToCase} deriving (Show, Eq)#}\n\n{#pointer *aiNode as AiNode #}\n{#pointer *aiScene as AiScene#}\n{#pointer *aiPlane as AiPlane#}\n{#pointer *aiRay as AiRay #}\n{#pointer *aiColor3D as AiColor3D#}\n{#pointer *aiString as AiString#}\n{#pointer *aiMemoryInfo as AiMemoryInfo#}\n{#pointer *aiLogStream as AiLogStream#}\n{#pointer *aiQuaternion as AiQuaternion#}\n{#pointer *aiMatrix3x3 as AiMatrix3x3#}\n{#pointer *aiMatrix4x4 as AiMatrix4x4#}\n{#pointer *aiVector3D as AiVector3D#}\n\n{#fun aiImportFile as ^\n {`String', cFromEnum `SceneFlags'} -> `AiScene' id#}\n\n-- aiImportFileEx\n-- aiImportFileFromMemory\n\n{#fun aiApplyPostProcessing as ^\n {id `AiScene', cFromEnum `AiPostProcessSteps'} -> `AiScene' id#}\n\n--{#fun aiGetPredefinedLogStream as ^\n-- {cFromEnum `AiDefaultLogStream', `String'} -> `AiLogStream' id#}\n\n-- aiAttachLogStream\n-- aiEnableVerboseLogging\n-- aiDetachLogStream\n-- aiDetachAllLogStreams\n\n{#fun aiReleaseImport as ^\n {id `AiScene'} -> `()'#}\n\n{#fun aiGetErrorString as ^\n {} -> `String'#}\n\n{#fun aiIsExtensionSupported as ^\n {`String'} -> `Bool'#}\n\n-- aiGetExtensionList\n-- aiGetMemoryRequirements\n\n{# fun aiSetImportPropertyInteger as ^\n {`String', `Int'} -> `()'#}\n\n{# fun aiSetImportPropertyFloat as ^\n {`String', `Float'} -> `()'#}\n\n--{# fun aiSetImportPropertyString as ^\n-- {`String', `AiString'} -> `()'#}\n\n-- aiCreateQuaternionFromMatrix\n-- aiDecomposeMatrix\n-- aiTransposematrix4\n-- aiTransposematrix3\n-- aiTransformVecByMatrix3\n-- aiTransformVecByMatrix4\n-- aiMultiplyMatrix3\n-- aiMultiplyMatrix4\n-- aiIdentityMatrix3\n-- aiIdentityMatrix4\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"825031fed39c7da79e4bd32b99b14aee740d59dd","subject":"gstreamer: M.S.G.Core.Format: document everything; remove formatsContains as it's pretty redundant","message":"gstreamer: M.S.G.Core.Format: document everything; remove formatsContains as it's pretty redundant\n\ndarcs-hash:20080824020113-21862-925211a4c90e91395cc9fad4f433ae6092a6624d.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Format.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Format.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.Format (\n \n -- * Types\n Format(..),\n FormatDefinition(..),\n FormatId,\n \n -- * Format Operations\n formatPercentMax,\n formatPercentScale,\n formatGetName,\n formatToQuark,\n formatRegister,\n formatGetByNick,\n formatGetDetails,\n formatIterateDefinitions\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.GObject#}\n\n-- | Get a printable name for the given format.\nformatGetName :: Format -- ^ @format@ - a format\n -> IO String -- ^ the name of the format\nformatGetName format =\n peekUTFString $\n ({# call fun format_get_name #} $\n fromIntegral $ fromFormat format)\n\n-- | Get the unique quark for the given format.\nformatToQuark :: Format -- ^ @format@ - a format\n -> IO Quark -- ^ the unique quark for the format\nformatToQuark =\n {# call format_to_quark #} . fromIntegral . fromFormat\n\n-- | Create a new format based on the given nickname, or register a new format with that nickname.\nformatRegister :: String -- ^ @nick@ - the nickname for the format\n -> String -- ^ @description@ - the description for the format\n -> IO Format -- ^ the format with the given nickname\nformatRegister nick description =\n liftM (toFormat . fromIntegral) $\n withUTFString nick $ \\cNick ->\n (withUTFString description $\n {# call format_register #} cNick)\n\n-- | Get the format with the given nickname, or 'FormatUndefined' if\n-- no format by that nickname was found.\nformatGetByNick :: String -- ^ @nick@ - the nickname for the format\n -> IO Format -- ^ the format with the given nickname,\n -- or 'FormatUndefined' if it was not found\nformatGetByNick nick =\n liftM (toFormat . fromIntegral) $\n withUTFString nick {# call format_get_by_nick #}\n\n-- | Get the given format's definition.\nformatGetDetails :: Format -- ^ @format@ - a format\n -> IO (Maybe FormatDefinition) -- ^ the definition for the given format, or \n -- 'Nothing' if the format was not found\nformatGetDetails format =\n ({# call format_get_details #} $ fromIntegral $ fromFormat format) >>=\n maybePeek peek . castPtr\n\n-- | Get an Iterator over all registered formats.\nformatIterateDefinitions :: IO (Iterator FormatDefinition)\nformatIterateDefinitions =\n {# call format_iterate_definitions #} >>= takeIterator\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.Format (\n \n -- * Types\n Format(..),\n FormatDefinition(..),\n FormatId,\n \n -- * Format Operations\n formatPercentMax,\n formatPercentScale,\n formatGetName,\n formatToQuark,\n formatRegister,\n formatGetByNick,\n formatsContains,\n formatGetDetails,\n formatIterateDefinitions\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.GObject#}\n\nformatGetName :: Format\n -> IO String\nformatGetName format =\n peekUTFString $\n ({# call fun format_get_name #} $\n fromIntegral $ fromFormat format)\n\nformatToQuark :: Format\n -> IO Quark\nformatToQuark =\n {# call format_to_quark #} . fromIntegral . fromFormat\n\nformatRegister :: String\n -> String\n -> IO Format\nformatRegister nick description =\n liftM (toFormat . fromIntegral) $\n withUTFString nick $ \\cNick ->\n (withUTFString description $\n {# call format_register #} cNick)\n\nformatGetByNick :: String\n -> IO Format\nformatGetByNick nick =\n liftM (toFormat . fromIntegral) $\n withUTFString nick {# call format_get_by_nick #}\n\nformatsContains :: [Format]\n -> Format\n -> IO Bool\nformatsContains formats format =\n liftM toBool $ \n withArray0 0 (map cFromEnum formats) $ \\cFormats ->\n {# call formats_contains #} cFormats $ cFromEnum format\n\nformatGetDetails :: Format\n -> IO FormatDefinition\nformatGetDetails format =\n ({# call format_get_details #} $ fromIntegral $ fromFormat format) >>=\n maybePeek peek . castPtr\n\nformatIterateDefinitions :: IO (Iterator FormatDefinition)\nformatIterateDefinitions =\n {# call format_iterate_definitions #} >>= takeIterator\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"514a8c78c7768b91cc3ef269d119b7a344eabf70","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\ndarcs-hash:20060204171730-b4c10-501a227ce76d651ee417850338be14ac39709d40.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"6a7ab154f035a5b86892c8e7a4e28091f49a1762","subject":"glib: make module name for GDateTime the same as the filename :)","message":"glib: make module name for GDateTime the same as the filename :)","repos":"vincenthz\/webkit","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":"6c2e0711048a7a6d58580cfa3c7469829d4c90f4","subject":"Used checkError in all #fun bindings","message":"Used checkError in all #fun bindings\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{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\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,\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare,\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,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\nimport Control.Parallel.MPI.Utils (enumFromCInt, enumToCInt)\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 {enumToCInt `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError* #}\n\nqueryThread = {# call unsafe Query_thread as queryThread_ #}\nisThreadMain = {# call unsafe Is_thread_main as isThreadMain_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ngetProcessorName = {# call unsafe Get_processor_name as getProcessorName_ #}\ngetVersion = {# call unsafe Get_version as getVersion_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #} <$> fromComm\ncommRank = {# call unsafe Comm_rank as commRank_ #} <$> fromComm\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #} <$> fromComm\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #} <$> fromComm\ncommCompare c1 c2 = {# call unsafe Comm_compare as commCompare_ #} (fromComm c1) (fromComm c2)\nprobe = {# fun Probe as probe_\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError* #}\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 b cnt d r t c = {# call unsafe Recv as recv_ #} b cnt (fromDatatype d) r t (fromComm c)\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 b cnt d r c = {# call unsafe Bcast as bcast_ #} b cnt (fromDatatype d) r (fromComm c)\nbarrier = {# call unsafe Barrier as barrier_ #} <$> fromComm\nwait = {# call unsafe Wait as wait_ #}\nwaitall = {# fun unsafe Waitall as waitall_ \n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError* #}\ntest = {# call unsafe Test as test_ #}\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 sb se st rb re rt r c = {# call unsafe Scatter as scatter_ #} sb se (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\ngather sb se st rb re rt r c = {# call unsafe Gather as gather_ #} sb se (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\nscatterv sb sc sd st rb re rt r c = {# call unsafe Scatterv as scatterv_ #} sb sc sd (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\ngatherv sb se st rb rc rd rt r c = {# call unsafe Gatherv as gatherv_ #} sb se (fromDatatype st) rb rc rd (fromDatatype rt) r (fromComm c)\nallgather sb se st rb re rt c = {# call unsafe Allgather as allgather_ #} sb se (fromDatatype st) rb re (fromDatatype rt) (fromComm c)\nallgatherv sb se st rb rc rd rt c = {# call unsafe Allgatherv as allgatherv_ #} sb se (fromDatatype st) rb rc rd (fromDatatype rt) (fromComm c)\nalltoall sb sc st rb rc rt c = {# call unsafe Alltoall as alltoall_ #} sb sc (fromDatatype st) rb rc (fromDatatype rt) (fromComm c)\nalltoallv sb sc sd st rb rc rd rt c = {# call unsafe Alltoallv as alltoallv_ #} sb sc sd (fromDatatype st) rb rc rd (fromDatatype rt) (fromComm c)\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce sb rb se st o r c = {# call Reduce as reduce_ #} sb rb se (fromDatatype st) (fromOperation o) r (fromComm c)\nallreduce sb rb se st o c = {# call Allreduce as allreduce_ #} sb rb se (fromDatatype st) (fromOperation o) (fromComm c)\nreduceScatter sb rb cnt t o c = {# call Reduce_scatter as reduceScatter_ #} sb rb cnt (fromDatatype t) (fromOperation o) (fromComm c)\nopCreate = {# call unsafe Op_create as opCreate_ #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\ncommGroup = {# call unsafe Comm_group as commGroup_ #} <$> fromComm\ngroupRank = {# call unsafe Group_rank as groupRank_ #} <$> fromGroup\ngroupSize = {# call unsafe Group_size as groupSize_ #} <$> fromGroup\ngroupUnion g1 g2 = {# call unsafe Group_union as groupUnion_ #} (fromGroup g1) (fromGroup g2)\ngroupIntersection g1 g2 = {# call unsafe Group_intersection as groupIntersection_ #} (fromGroup g1) (fromGroup g2)\ngroupDifference g1 g2 = {# call unsafe Group_difference as groupDifference_ #} (fromGroup g1) (fromGroup g2)\ngroupCompare g1 g2 = {# call unsafe Group_compare as groupCompare_ #} (fromGroup g1) (fromGroup g2)\ngroupExcl g = {# call unsafe Group_excl as groupExcl_ #} (fromGroup g)\ngroupIncl g = {# call unsafe Group_incl as groupIncl_ #} (fromGroup g)\ngroupTranslateRanks g1 s r g2 = {# call unsafe Group_translate_ranks as groupTranslateRanks_ #} (fromGroup g1) s r (fromGroup g2)\ntypeSize = {# call unsafe Type_size as typeSize_ #} <$> fromDatatype\nerrorClass = {# fun unsafe Error_class as errorClass_ \n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\nerrorString = {# call unsafe Error_string as errorString_ #}\ncommSetErrhandler c h = {# call unsafe Comm_set_errhandler as commSetErrhandler_ #} (fromComm c) (fromErrhandler h)\ncommGetErrhandler = {# call unsafe Comm_get_errhandler as commGetErrhandler_ #} <$> fromComm\nabort = {# call unsafe Abort as abort_ #} <$> fromComm\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\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 #}\n\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\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 #}\n\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\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\n-- TODO: actually, this should be 32-bit int\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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\n-- TODO: actually, this is a 32-bit int, and even less than that.\n-- See section 8 of MPI report about extracting MPI_TAG_UB\n-- and using it here\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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 = enumFromCInt 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{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\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,\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare,\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,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\nimport Control.Parallel.MPI.Utils (enumFromCInt, enumToCInt)\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 {enumToCInt `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError* #}\n\nqueryThread = {# call unsafe Query_thread as queryThread_ #}\nisThreadMain = {# call unsafe Is_thread_main as isThreadMain_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ngetProcessorName = {# call unsafe Get_processor_name as getProcessorName_ #}\ngetVersion = {# call unsafe Get_version as getVersion_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #} <$> fromComm\ncommRank = {# call unsafe Comm_rank as commRank_ #} <$> fromComm\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #} <$> fromComm\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #} <$> fromComm\ncommCompare c1 c2 = {# call unsafe Comm_compare as commCompare_ #} (fromComm c1) (fromComm c2)\n-- probe s t c = {# call Probe as probe_ #} s t (fromComm c)\nprobe = {# fun Probe as probe_\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `ErrCode' cIntConv #}\nsend = {# fun unsafe Send as send_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `ErrCode' cIntConv #}\nbsend = {# fun unsafe Bsend as bsend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `ErrCode' cIntConv #}\nssend = {# fun unsafe Ssend as ssend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `ErrCode' cIntConv #}\nrsend = {# fun unsafe Rsend as rsend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `ErrCode' cIntConv #}\nrecv b cnt d r t c = {# call unsafe Recv as recv_ #} b cnt (fromDatatype d) r t (fromComm c)\nisend = {# fun unsafe Isend as isend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `ErrCode' cIntConv #}\nibsend = {# fun unsafe Ibsend as ibsend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `ErrCode' cIntConv #}\nissend = {# fun unsafe Issend as issend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `ErrCode' cIntConv #}\nisendPtr = {# fun unsafe Isend as isendPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `ErrCode' cIntConv #}\nibsendPtr = {# fun unsafe Ibsend as ibsendPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `ErrCode' cIntConv #}\nissendPtr = {# fun unsafe Issend as issendPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `ErrCode' cIntConv #}\nirecv = {# fun Irecv as irecv_ \n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `ErrCode' cIntConv #}\nirecvPtr = {# fun Irecv as irecvPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `ErrCode' cIntConv #}\nbcast b cnt d r c = {# call unsafe Bcast as bcast_ #} b cnt (fromDatatype d) r (fromComm c)\nbarrier = {# call unsafe Barrier as barrier_ #} <$> fromComm\nwait = {# call unsafe Wait as wait_ #}\nwaitall = {# fun unsafe Waitall as waitall_ \n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `ErrCode' cIntConv #}\ntest = {# call unsafe Test as test_ #}\ncancel = {# fun unsafe Cancel as cancel_ \n {withRequest* `Request'} -> `ErrCode' cIntConv #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\nscatter sb se st rb re rt r c = {# call unsafe Scatter as scatter_ #} sb se (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\ngather sb se st rb re rt r c = {# call unsafe Gather as gather_ #} sb se (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\nscatterv sb sc sd st rb re rt r c = {# call unsafe Scatterv as scatterv_ #} sb sc sd (fromDatatype st) rb re (fromDatatype rt) r (fromComm c)\ngatherv sb se st rb rc rd rt r c = {# call unsafe Gatherv as gatherv_ #} sb se (fromDatatype st) rb rc rd (fromDatatype rt) r (fromComm c)\nallgather sb se st rb re rt c = {# call unsafe Allgather as allgather_ #} sb se (fromDatatype st) rb re (fromDatatype rt) (fromComm c)\nallgatherv sb se st rb rc rd rt c = {# call unsafe Allgatherv as allgatherv_ #} sb se (fromDatatype st) rb rc rd (fromDatatype rt) (fromComm c)\nalltoall sb sc st rb rc rt c = {# call unsafe Alltoall as alltoall_ #} sb sc (fromDatatype st) rb rc (fromDatatype rt) (fromComm c)\nalltoallv sb sc sd st rb rc rd rt c = {# call unsafe Alltoallv as alltoallv_ #} sb sc sd (fromDatatype st) rb rc rd (fromDatatype rt) (fromComm c)\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce sb rb se st o r c = {# call Reduce as reduce_ #} sb rb se (fromDatatype st) (fromOperation o) r (fromComm c)\nallreduce sb rb se st o c = {# call Allreduce as allreduce_ #} sb rb se (fromDatatype st) (fromOperation o) (fromComm c)\nreduceScatter sb rb cnt t o c = {# call Reduce_scatter as reduceScatter_ #} sb rb cnt (fromDatatype t) (fromOperation o) (fromComm c)\nopCreate = {# call unsafe Op_create as opCreate_ #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\ncommGroup = {# call unsafe Comm_group as commGroup_ #} <$> fromComm\ngroupRank = {# call unsafe Group_rank as groupRank_ #} <$> fromGroup\ngroupSize = {# call unsafe Group_size as groupSize_ #} <$> fromGroup\ngroupUnion g1 g2 = {# call unsafe Group_union as groupUnion_ #} (fromGroup g1) (fromGroup g2)\ngroupIntersection g1 g2 = {# call unsafe Group_intersection as groupIntersection_ #} (fromGroup g1) (fromGroup g2)\ngroupDifference g1 g2 = {# call unsafe Group_difference as groupDifference_ #} (fromGroup g1) (fromGroup g2)\ngroupCompare g1 g2 = {# call unsafe Group_compare as groupCompare_ #} (fromGroup g1) (fromGroup g2)\ngroupExcl g = {# call unsafe Group_excl as groupExcl_ #} (fromGroup g)\ngroupIncl g = {# call unsafe Group_incl as groupIncl_ #} (fromGroup g)\ngroupTranslateRanks g1 s r g2 = {# call unsafe Group_translate_ranks as groupTranslateRanks_ #} (fromGroup g1) s r (fromGroup g2)\ntypeSize = {# call unsafe Type_size as typeSize_ #} <$> fromDatatype\nerrorClass = {# fun unsafe Error_class as errorClass_ \n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\nerrorString = {# call unsafe Error_string as errorString_ #}\ncommSetErrhandler c h = {# call unsafe Comm_set_errhandler as commSetErrhandler_ #} (fromComm c) (fromErrhandler h)\ncommGetErrhandler = {# call unsafe Comm_get_errhandler as commGetErrhandler_ #} <$> fromComm\nabort = {# call unsafe Abort as abort_ #} <$> fromComm\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\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 #}\n\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\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 #}\n\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\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\n-- TODO: actually, this should be 32-bit int\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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\n-- TODO: actually, this is a 32-bit int, and even less than that.\n-- See section 8 of MPI report about extracting MPI_TAG_UB\n-- and using it here\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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 = enumFromCInt 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":"2010649820abcab5296c095030b4c3d6b895a761","subject":"warning police: shadowing","message":"warning police: shadowing\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Exec.chs","new_file":"Foreign\/CUDA\/Runtime\/Exec.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Exec\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for C-for-CUDA runtime interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Exec (\n\n -- * Kernel Execution\n Fun, FunAttributes(..), FunParam(..), CacheConfig(..),\n attributes, setConfig, setParams, setCacheConfig, launch, launchKernel,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#c\ntypedef struct cudaFuncAttributes cudaFuncAttributes;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function.\n--\n-- Note that the use of a string naming a function was deprecated in CUDA 4.1\n-- and removed in CUDA 5.0.\n--\n#if CUDART_VERSION >= 5000\ntype Fun = FunPtr ()\n#else\ntype Fun = String\n#endif\n\n\n--\n-- Function Attributes\n--\n{# pointer *cudaFuncAttributes as ^ foreign -> FunAttributes nocode #}\n\ndata FunAttributes = FunAttributes\n {\n constSizeBytes :: !Int64,\n localSizeBytes :: !Int64,\n sharedSizeBytes :: !Int64,\n maxKernelThreadsPerBlock :: !Int, -- ^ maximum block size that can be successively launched (based on register usage)\n numRegs :: !Int -- ^ number of registers required for each thread\n }\n deriving (Show)\n\ninstance Storable FunAttributes where\n sizeOf _ = {# sizeof cudaFuncAttributes #}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"Can not poke Foreign.CUDA.Runtime.FunAttributes\"\n peek p = do\n cs <- cIntConv `fmap` {#get cudaFuncAttributes.constSizeBytes#} p\n ls <- cIntConv `fmap` {#get cudaFuncAttributes.localSizeBytes#} p\n ss <- cIntConv `fmap` {#get cudaFuncAttributes.sharedSizeBytes#} p\n tb <- cIntConv `fmap` {#get cudaFuncAttributes.maxThreadsPerBlock#} p\n nr <- cIntConv `fmap` {#get cudaFuncAttributes.numRegs#} p\n\n return FunAttributes\n {\n constSizeBytes = cs,\n localSizeBytes = ls,\n sharedSizeBytes = ss,\n maxKernelThreadsPerBlock = tb,\n numRegs = nr\n }\n\n#if CUDART_VERSION < 3000\ndata CacheConfig\n#else\n-- |\n-- Cache configuration preference\n--\n{# enum cudaFuncCache as CacheConfig\n { }\n with prefix=\"cudaFuncCachePrefer\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters. Doubles will be converted to an internal float\n-- representation on devices that do not support doubles natively.\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n DArg :: !Double -> FunParam\n VArg :: Storable a => !a -> FunParam\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Obtain the attributes of the named @__global__@ device function. This\n-- itemises the requirements to successfully launch the given kernel.\n--\n{-# INLINEABLE attributes #-}\nattributes :: Fun -> IO FunAttributes\nattributes !fn = resultIfOk =<< cudaFuncGetAttributes fn\n\n{-# INLINE cudaFuncGetAttributes #-}\n{# fun unsafe cudaFuncGetAttributes\n { alloca- `FunAttributes' peek*\n , withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the grid and block dimensions for a device call. Used in conjunction\n-- with 'setParams', this pushes data onto the execution stack that will be\n-- popped when a function is 'launch'ed.\n--\n{-# INLINEABLE setConfig #-}\nsetConfig :: (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ block dimensions\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ associated processing stream\n -> IO ()\nsetConfig (!gx,!gy) (!bx,!by,!bz) !sharedMem !mst =\n nothingIfOk =<<\n cudaConfigureCallSimple gx gy bx by bz sharedMem (maybe defaultStream id mst)\n\n\n--\n-- The FFI does not support passing deferenced structures to C functions, as\n-- this is highly platform\/compiler dependent. Wrap our own function stub\n-- accepting plain integers.\n--\n{-# INLINE cudaConfigureCallSimple #-}\n{# fun unsafe cudaConfigureCallSimple\n { `Int', `Int'\n , `Int', `Int', `Int'\n , cIntConv `Int64'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the argument parameters that will be passed to the next kernel\n-- invocation. This is used in conjunction with 'setConfig' to control kernel\n-- execution.\n--\n{-# INLINEABLE setParams #-}\nsetParams :: [FunParam] -> IO ()\nsetParams = foldM_ k 0\n where\n k !offset !arg = do\n let s = size arg\n set arg s offset >>= nothingIfOk\n return (offset + s)\n\n size (IArg _) = sizeOf (undefined :: Int)\n size (FArg _) = sizeOf (undefined :: Float)\n size (DArg _) = sizeOf (undefined :: Double)\n size (VArg a) = sizeOf a\n\n set (IArg v) s o = cudaSetupArgument v s o\n set (FArg v) s o = cudaSetupArgument v s o\n set (VArg v) s o = cudaSetupArgument v s o\n set (DArg v) s o =\n cudaSetDoubleForDevice v >>= resultIfOk >>= \\d ->\n cudaSetupArgument d s o\n\n\n{-# INLINE cudaSetupArgument #-}\n{# fun unsafe cudaSetupArgument\n `Storable a' =>\n { with'* `a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n\n{-# INLINE cudaSetDoubleForDevice #-}\n{# fun unsafe cudaSetDoubleForDevice\n { with'* `Double' peek'* } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n peek' = peek . castPtr\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 setCacheConfig #-}\nsetCacheConfig :: Fun -> CacheConfig -> IO ()\n#if CUDART_VERSION < 3000\nsetCacheConfig _ _ = requireSDK 3.0 \"setCacheConfig\"\n#else\nsetCacheConfig !fn !pref = nothingIfOk =<< cudaFuncSetCacheConfig fn pref\n\n{-# INLINE cudaFuncSetCacheConfig #-}\n{# fun unsafe cudaFuncSetCacheConfig\n { withFun* `Fun'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Invoke the @__global__@ kernel function on the device. This must be preceded\n-- by a call to 'setConfig' and (if appropriate) 'setParams'.\n--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> IO ()\nlaunch !fn = nothingIfOk =<< cudaLaunch fn\n\n{-# INLINE cudaLaunch #-}\n{# fun unsafe cudaLaunch\n { withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy)@ grid of blocks, where each block contains\n-- @(tx * ty * tz)@ threads and has access to a given number of bytes of shared\n-- memory. The launch may also be associated with a specific 'Stream'.\n--\n{-# INLINEABLE launchKernel #-}\nlaunchKernel\n :: Fun -- ^ Device function symbol\n -> (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ (optional) execution stream\n -> [FunParam]\n -> IO ()\nlaunchKernel !fn !grid !block !sm !mst !args = do\n setConfig grid block sm mst\n setParams args\n launch fn\n\n--------------------------------------------------------------------------------\n-- Internals\n--------------------------------------------------------------------------------\n\n-- CUDA 5.0 changed the type of a kernel function from char* to void*\n--\nwithFun :: Fun -> (Ptr a -> IO b) -> IO b\n#if CUDART_VERSION >= 5000\nwithFun fn action = action (castFunPtrToPtr fn)\n#else\nwithFun = withCString\n#endif\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Exec\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for C-for-CUDA runtime interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Exec (\n\n -- * Kernel Execution\n Fun, FunAttributes(..), FunParam(..), CacheConfig(..),\n attributes, setConfig, setParams, setCacheConfig, launch, launchKernel,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#c\ntypedef struct cudaFuncAttributes cudaFuncAttributes;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function.\n--\n-- Note that the use of a string naming a function was deprecated in CUDA 4.1\n-- and removed in CUDA 5.0.\n--\n#if CUDART_VERSION >= 5000\ntype Fun = FunPtr ()\n#else\ntype Fun = String\n#endif\n\n\n--\n-- Function Attributes\n--\n{# pointer *cudaFuncAttributes as ^ foreign -> FunAttributes nocode #}\n\ndata FunAttributes = FunAttributes\n {\n constSizeBytes :: !Int64,\n localSizeBytes :: !Int64,\n sharedSizeBytes :: !Int64,\n maxKernelThreadsPerBlock :: !Int, -- ^ maximum block size that can be successively launched (based on register usage)\n numRegs :: !Int -- ^ number of registers required for each thread\n }\n deriving (Show)\n\ninstance Storable FunAttributes where\n sizeOf _ = {# sizeof cudaFuncAttributes #}\n alignment _ = alignment (undefined :: Ptr ())\n\n poke _ _ = error \"Can not poke Foreign.CUDA.Runtime.FunAttributes\"\n peek p = do\n cs <- cIntConv `fmap` {#get cudaFuncAttributes.constSizeBytes#} p\n ls <- cIntConv `fmap` {#get cudaFuncAttributes.localSizeBytes#} p\n ss <- cIntConv `fmap` {#get cudaFuncAttributes.sharedSizeBytes#} p\n tb <- cIntConv `fmap` {#get cudaFuncAttributes.maxThreadsPerBlock#} p\n nr <- cIntConv `fmap` {#get cudaFuncAttributes.numRegs#} p\n\n return FunAttributes\n {\n constSizeBytes = cs,\n localSizeBytes = ls,\n sharedSizeBytes = ss,\n maxKernelThreadsPerBlock = tb,\n numRegs = nr\n }\n\n#if CUDART_VERSION < 3000\ndata CacheConfig\n#else\n-- |\n-- Cache configuration preference\n--\n{# enum cudaFuncCache as CacheConfig\n { }\n with prefix=\"cudaFuncCachePrefer\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters. Doubles will be converted to an internal float\n-- representation on devices that do not support doubles natively.\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n DArg :: !Double -> FunParam\n VArg :: Storable a => !a -> FunParam\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Obtain the attributes of the named @__global__@ device function. This\n-- itemises the requirements to successfully launch the given kernel.\n--\n{-# INLINEABLE attributes #-}\nattributes :: Fun -> IO FunAttributes\nattributes !fn = resultIfOk =<< cudaFuncGetAttributes fn\n\n{-# INLINE cudaFuncGetAttributes #-}\n{# fun unsafe cudaFuncGetAttributes\n { alloca- `FunAttributes' peek*\n , withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the grid and block dimensions for a device call. Used in conjunction\n-- with 'setParams', this pushes data onto the execution stack that will be\n-- popped when a function is 'launch'ed.\n--\n{-# INLINEABLE setConfig #-}\nsetConfig :: (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ block dimensions\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ associated processing stream\n -> IO ()\nsetConfig (!gx,!gy) (!bx,!by,!bz) !sharedMem !mst =\n nothingIfOk =<<\n cudaConfigureCallSimple gx gy bx by bz sharedMem (maybe defaultStream id mst)\n\n\n--\n-- The FFI does not support passing deferenced structures to C functions, as\n-- this is highly platform\/compiler dependent. Wrap our own function stub\n-- accepting plain integers.\n--\n{-# INLINE cudaConfigureCallSimple #-}\n{# fun unsafe cudaConfigureCallSimple\n { `Int', `Int'\n , `Int', `Int', `Int'\n , cIntConv `Int64'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the argument parameters that will be passed to the next kernel\n-- invocation. This is used in conjunction with 'setConfig' to control kernel\n-- execution.\n--\n{-# INLINEABLE setParams #-}\nsetParams :: [FunParam] -> IO ()\nsetParams = foldM_ k 0\n where\n k !offset !arg = do\n let s = size arg\n set arg s offset >>= nothingIfOk\n return (offset + s)\n\n size (IArg _) = sizeOf (undefined :: Int)\n size (FArg _) = sizeOf (undefined :: Float)\n size (DArg _) = sizeOf (undefined :: Double)\n size (VArg a) = sizeOf a\n\n set (IArg v) s o = cudaSetupArgument v s o\n set (FArg v) s o = cudaSetupArgument v s o\n set (VArg v) s o = cudaSetupArgument v s o\n set (DArg v) s o =\n cudaSetDoubleForDevice v >>= resultIfOk >>= \\d ->\n cudaSetupArgument d s o\n\n\n{-# INLINE cudaSetupArgument #-}\n{# fun unsafe cudaSetupArgument\n `Storable a' =>\n { with'* `a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n\n{-# INLINE cudaSetDoubleForDevice #-}\n{# fun unsafe cudaSetDoubleForDevice\n { with'* `Double' peek'* } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n peek' = peek . castPtr\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 setCacheConfig #-}\nsetCacheConfig :: Fun -> CacheConfig -> IO ()\n#if CUDART_VERSION < 3000\nsetCacheConfig _ _ = requireSDK 3.0 \"setCacheConfig\"\n#else\nsetCacheConfig !fn !pref = nothingIfOk =<< cudaFuncSetCacheConfig fn pref\n\n{-# INLINE cudaFuncSetCacheConfig #-}\n{# fun unsafe cudaFuncSetCacheConfig\n { withFun* `Fun'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Invoke the @__global__@ kernel function on the device. This must be preceded\n-- by a call to 'setConfig' and (if appropriate) 'setParams'.\n--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> IO ()\nlaunch !fn = nothingIfOk =<< cudaLaunch fn\n\n{-# INLINE cudaLaunch #-}\n{# fun unsafe cudaLaunch\n { withFun* `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy)@ grid of blocks, where each block contains\n-- @(tx * ty * tz)@ threads and has access to a given number of bytes of shared\n-- memory. The launch may also be associated with a specific 'Stream'.\n--\n{-# INLINEABLE launchKernel #-}\nlaunchKernel\n :: Fun -- ^ Device function symbol\n -> (Int,Int) -- ^ grid dimensions\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int64 -- ^ shared memory per block (bytes)\n -> Maybe Stream -- ^ (optional) execution stream\n -> [FunParam]\n -> IO ()\nlaunchKernel !fn !grid !block !sm !mst !args = do\n setConfig grid block sm mst\n setParams args\n launch fn\n\n--------------------------------------------------------------------------------\n-- Internals\n--------------------------------------------------------------------------------\n\n-- CUDA 5.0 changed the type of a kernel function from char* to void*\n--\nwithFun :: Fun -> (Ptr a -> IO b) -> IO b\n#if CUDART_VERSION >= 5000\nwithFun fn action = action (castFunPtrToPtr fn)\n#else\nwithFun = withCString\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"07047a4eec52de9afe7f19edf3f0c0e66c7902d1","subject":"Remove unnecessary castPtr.","message":"Remove unnecessary castPtr.\n\nIgnore-this: 991ba4935cf8ae60c11800a1397b7750\n\ndarcs-hash:20120612194838-4d2ae-8b15d252d61d6bae4779f81a28e2f57818c211b3\n","repos":"johntyree\/HsQML,johntyree\/HsQML","old_file":"src\/Graphics\/QML\/Internal\/Objects.chs","new_file":"src\/Graphics\/QML\/Internal\/Objects.chs","new_contents":"{-# LANGUAGE\n ForeignFunctionInterface\n #-}\n\nmodule Graphics.QML.Internal.Objects where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.StablePtr\n\n#include \"hsqml.h\"\n\n{#fun unsafe hsqml_get_next_class_id as ^\n {} ->\n `CInt' id #}\n\ntype UniformFunc = Ptr () -> Ptr (Ptr ()) -> IO ()\n\nforeign import ccall \"wrapper\" \n marshalFunc :: UniformFunc -> IO (FunPtr UniformFunc)\n\n{#pointer *HsQMLClassHandle as ^ foreign newtype #}\n\nforeign import ccall \"hsqml.h &hsqml_finalise_class_handle\"\n hsqmlFinaliseClassHandlePtr :: FunPtr (Ptr (HsQMLClassHandle) -> IO ())\n\nnewClassHandle :: Ptr HsQMLClassHandle -> IO (Maybe HsQMLClassHandle)\nnewClassHandle p =\n if nullPtr == p\n then return Nothing\n else do\n fp <- newForeignPtr hsqmlFinaliseClassHandlePtr p\n return $ Just $ HsQMLClassHandle fp\n\n{#fun unsafe hsqml_create_class as ^\n {id `Ptr CUInt',\n id `Ptr CChar',\n id `Ptr (FunPtr UniformFunc)',\n id `Ptr (FunPtr UniformFunc)'} ->\n `Maybe HsQMLClassHandle' newClassHandle* #}\n\n{#pointer *HsQMLObjectHandle as ^ foreign newtype #}\n\nforeign import ccall \"hsqml.h &hsqml_finalise_object_handle\"\n hsqmlFinaliseObjectHandlePtr :: FunPtr (Ptr (HsQMLObjectHandle) -> IO ())\n\nnewObjectHandle :: Ptr HsQMLObjectHandle -> IO HsQMLObjectHandle\nnewObjectHandle p = do\n fp <- newForeignPtr hsqmlFinaliseObjectHandlePtr p\n return $ HsQMLObjectHandle fp\n\nisNullObjectHandle :: HsQMLObjectHandle -> Bool\nisNullObjectHandle (HsQMLObjectHandle fp) =\n nullPtr == unsafeForeignPtrToPtr fp\n\n-- | Represents an instance of the QML class which wraps the type @tt@.\ndata ObjRef tt = ObjRef {\n objHndl :: HsQMLObjectHandle\n}\n\nobjToPtr :: a -> (Ptr () -> IO b) -> IO b\nobjToPtr obj f = do\n sPtr <- newStablePtr obj\n res <- f $ castStablePtrToPtr sPtr\n return res\n\n{#fun unsafe hsqml_create_object as ^\n {objToPtr* `a',\n withHsQMLClassHandle* `HsQMLClassHandle'} ->\n `HsQMLObjectHandle' newObjectHandle* #}\n\nptrToObj :: Ptr () -> IO a\nptrToObj =\n deRefStablePtr . castPtrToStablePtr\n\n{#fun unsafe hsqml_object_get_haskell as ^\n {withHsQMLObjectHandle* `HsQMLObjectHandle'} ->\n `a' ptrToObj* #}\n\n{#fun unsafe hsqml_object_get_pointer as ^\n {withHsQMLObjectHandle* `HsQMLObjectHandle'} ->\n `Ptr ()' id #}\n\nwithMaybeHsQMLClassHandle ::\n Maybe HsQMLClassHandle -> (Ptr HsQMLClassHandle -> IO b) -> IO b\nwithMaybeHsQMLClassHandle (Just (HsQMLClassHandle fptr)) = withForeignPtr fptr\nwithMaybeHsQMLClassHandle Nothing = \\f -> f nullPtr\n\n{#fun unsafe hsqml_get_object_handle as ^\n {id `Ptr ()',\n withMaybeHsQMLClassHandle* `Maybe HsQMLClassHandle'} ->\n `HsQMLObjectHandle' newObjectHandle* #}\n\nofDynamicMetaObject :: CUInt\nofDynamicMetaObject = 0x01\n\nmfAccessPrivate, mfAccessProtected, mfAccessPublic, mfAccessMask,\n mfMethodMethod, mfMethodSignal, mfMethodSlot, mfMethodConstructor,\n mfMethodTypeMask, mfMethodCompatibility, mfMethodCloned, mfMethodScriptable\n :: CUInt\nmfAccessPrivate = 0x00\nmfAccessProtected = 0x01\nmfAccessPublic = 0x02\nmfAccessMask = 0x03\nmfMethodMethod = 0x00\nmfMethodSignal = 0x04\nmfMethodSlot = 0x08\nmfMethodConstructor = 0x0c\nmfMethodTypeMask = 0x0c\nmfMethodCompatibility = 0x10\nmfMethodCloned = 0x20\nmfMethodScriptable = 0x40\n\npfInvalid, pfReadable, pfWritable, pfResettable, pfEnumOrFlag, pfStdCppSet,\n pfConstant, pfFinal, pfDesignable, pfResolveDesignable, pfScriptable,\n pfResolveScriptable, pfStored, pfResolveStored, pfEditable,\n pfResolveEditable, pfUser, pfResolveUser, pfNotify :: CUInt\npfInvalid = 0x00000000\npfReadable = 0x00000001\npfWritable = 0x00000002\npfResettable = 0x00000004\npfEnumOrFlag = 0x00000008\npfStdCppSet = 0x00000100\npfConstant = 0x00000400\npfFinal = 0x00000800\npfDesignable = 0x00001000\npfResolveDesignable = 0x00002000\npfScriptable = 0x00004000\npfResolveScriptable = 0x00008000\npfStored = 0x00010000\npfResolveStored = 0x00020000\npfEditable = 0x00040000\npfResolveEditable = 0x00080000\npfUser = 0x00100000\npfResolveUser = 0x00200000\npfNotify = 0x00400000\n","old_contents":"{-# LANGUAGE\n ForeignFunctionInterface\n #-}\n\nmodule Graphics.QML.Internal.Objects where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.StablePtr\n\n#include \"hsqml.h\"\n\n{#fun unsafe hsqml_get_next_class_id as ^\n {} ->\n `CInt' id #}\n\ntype UniformFunc = Ptr () -> Ptr (Ptr ()) -> IO ()\n\nforeign import ccall \"wrapper\" \n marshalFunc :: UniformFunc -> IO (FunPtr UniformFunc)\n\n{#pointer *HsQMLClassHandle as ^ foreign newtype #}\n\nforeign import ccall \"hsqml.h &hsqml_finalise_class_handle\"\n hsqmlFinaliseClassHandlePtr :: FunPtr (Ptr (HsQMLClassHandle) -> IO ())\n\nnewClassHandle :: Ptr HsQMLClassHandle -> IO (Maybe HsQMLClassHandle)\nnewClassHandle p =\n if nullPtr == p\n then return Nothing\n else do\n fp <- newForeignPtr hsqmlFinaliseClassHandlePtr p\n return $ Just $ HsQMLClassHandle fp\n\n{#fun unsafe hsqml_create_class as ^\n {id `Ptr CUInt',\n id `Ptr CChar',\n id `Ptr (FunPtr UniformFunc)',\n id `Ptr (FunPtr UniformFunc)'} ->\n `Maybe HsQMLClassHandle' newClassHandle* #}\n\n{#pointer *HsQMLObjectHandle as ^ foreign newtype #}\n\nforeign import ccall \"hsqml.h &hsqml_finalise_object_handle\"\n hsqmlFinaliseObjectHandlePtr :: FunPtr (Ptr (HsQMLObjectHandle) -> IO ())\n\nnewObjectHandle :: Ptr HsQMLObjectHandle -> IO HsQMLObjectHandle\nnewObjectHandle p = do\n fp <- newForeignPtr hsqmlFinaliseObjectHandlePtr p\n return $ HsQMLObjectHandle fp\n\nisNullObjectHandle :: HsQMLObjectHandle -> Bool\nisNullObjectHandle (HsQMLObjectHandle fp) =\n let p = unsafeForeignPtrToPtr fp\n in castPtr p == nullPtr\n\n-- | Represents an instance of the QML class which wraps the type @tt@.\ndata ObjRef tt = ObjRef {\n objHndl :: HsQMLObjectHandle\n}\n\nobjToPtr :: a -> (Ptr () -> IO b) -> IO b\nobjToPtr obj f = do\n sPtr <- newStablePtr obj\n res <- f $ castStablePtrToPtr sPtr\n return res\n\n{#fun unsafe hsqml_create_object as ^\n {objToPtr* `a',\n withHsQMLClassHandle* `HsQMLClassHandle'} ->\n `HsQMLObjectHandle' newObjectHandle* #}\n\nptrToObj :: Ptr () -> IO a\nptrToObj =\n deRefStablePtr . castPtrToStablePtr\n\n{#fun unsafe hsqml_object_get_haskell as ^\n {withHsQMLObjectHandle* `HsQMLObjectHandle'} ->\n `a' ptrToObj* #}\n\n{#fun unsafe hsqml_object_get_pointer as ^\n {withHsQMLObjectHandle* `HsQMLObjectHandle'} ->\n `Ptr ()' id #}\n\nwithMaybeHsQMLClassHandle ::\n Maybe HsQMLClassHandle -> (Ptr HsQMLClassHandle -> IO b) -> IO b\nwithMaybeHsQMLClassHandle (Just (HsQMLClassHandle fptr)) = withForeignPtr fptr\nwithMaybeHsQMLClassHandle Nothing = \\f -> f nullPtr\n\n{#fun unsafe hsqml_get_object_handle as ^\n {id `Ptr ()',\n withMaybeHsQMLClassHandle* `Maybe HsQMLClassHandle'} ->\n `HsQMLObjectHandle' newObjectHandle* #}\n\nofDynamicMetaObject :: CUInt\nofDynamicMetaObject = 0x01\n\nmfAccessPrivate, mfAccessProtected, mfAccessPublic, mfAccessMask,\n mfMethodMethod, mfMethodSignal, mfMethodSlot, mfMethodConstructor,\n mfMethodTypeMask, mfMethodCompatibility, mfMethodCloned, mfMethodScriptable\n :: CUInt\nmfAccessPrivate = 0x00\nmfAccessProtected = 0x01\nmfAccessPublic = 0x02\nmfAccessMask = 0x03\nmfMethodMethod = 0x00\nmfMethodSignal = 0x04\nmfMethodSlot = 0x08\nmfMethodConstructor = 0x0c\nmfMethodTypeMask = 0x0c\nmfMethodCompatibility = 0x10\nmfMethodCloned = 0x20\nmfMethodScriptable = 0x40\n\npfInvalid, pfReadable, pfWritable, pfResettable, pfEnumOrFlag, pfStdCppSet,\n pfConstant, pfFinal, pfDesignable, pfResolveDesignable, pfScriptable,\n pfResolveScriptable, pfStored, pfResolveStored, pfEditable,\n pfResolveEditable, pfUser, pfResolveUser, pfNotify :: CUInt\npfInvalid = 0x00000000\npfReadable = 0x00000001\npfWritable = 0x00000002\npfResettable = 0x00000004\npfEnumOrFlag = 0x00000008\npfStdCppSet = 0x00000100\npfConstant = 0x00000400\npfFinal = 0x00000800\npfDesignable = 0x00001000\npfResolveDesignable = 0x00002000\npfScriptable = 0x00004000\npfResolveScriptable = 0x00008000\npfStored = 0x00010000\npfResolveStored = 0x00020000\npfEditable = 0x00040000\npfResolveEditable = 0x00080000\npfUser = 0x00100000\npfResolveUser = 0x00200000\npfNotify = 0x00400000\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6508182a5ff1c40480667ec2fffdddc7ba5209aa","subject":"Naming change.","message":"Naming change.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Data.Maybe (fromMaybe)\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input_with_deflt as flInput' { `CString',`CString' } -> `CString' #}\nflInput :: T.Text -> Maybe T.Text -> IO (Maybe T.Text)\nflInput msg defaultMsg = do\n msgC <- copyTextToCString msg\n let def = fromMaybe T.empty defaultMsg\n defaultC <- copyTextToCString def\n r <- flInput' msgC defaultC\n cStringToMaybeText r\n\n{# fun flc_password as flPassword' { `CString' } -> `CString' #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- copyTextToCString msg >>= flPassword'\n cStringToMaybeText r\n\n{# fun flc_message as flMessage' { `CString' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage t = copyTextToCString t >>= flMessage'\n\n{# fun flc_alert as flAlert' { `CString' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert t = copyTextToCString t >>= flAlert'\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Data.Maybe (fromMaybe)\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input_with_deflt as flInput' { `CString',`CString' } -> `CString' #}\nflInput :: T.Text -> Maybe T.Text -> IO (Maybe T.Text)\nflInput msg maybeDefault = do\n msgC <- copyTextToCString msg\n let def = fromMaybe T.empty maybeDefault\n defaultC <- copyTextToCString def\n r <- flInput' msgC defaultC\n cStringToMaybeText r\n\n{# fun flc_password as flPassword' { `CString' } -> `CString' #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- copyTextToCString msg >>= flPassword'\n cStringToMaybeText r\n\n{# fun flc_message as flMessage' { `CString' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage t = copyTextToCString t >>= flMessage'\n\n{# fun flc_alert as flAlert' { `CString' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert t = copyTextToCString t >>= flAlert'\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"c7877f81ee524c8bbe7312019a32a71eac64c055","subject":"gstreamer: fix marshaling on Structure where GValues weren't initialized properly","message":"gstreamer: fix marshaling on Structure where GValues weren't initialized properly\n\nreported\/fixed by Oleg Belozeorov \n\ndarcs-hash:20090112044035-21862-398d7782fb1c6a0905290a285c9dfcbe05f9a966.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"e3176efd34856074505bbde58c471e82d67782d8","subject":"Adjust webResourceGetMimeType.","message":"Adjust webResourceGetMimeType.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"4a88029076fc531e3a4e9e701b1f06dbeb4fa27d","subject":"Rename signal.","message":"Rename signal.\n\nThe onValueChanged signal in Range was not exported since it clashed with\na different signal of the same name. Since it cannot be used anyway (since\nit wasn't exported), I renamed it to onRangeValueChanged and exported it.\n\ndarcs-hash:20061202190149-91c87-330932442cafed83db0dbea0c9cb0e6538d145e4.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Range.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Range.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Range\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.11 $ from $Date: 2005\/10\/19 12:57:36 $\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-- Base class for widgets which visualize an adjustment\n--\nmodule Graphics.UI.Gtk.Abstract.Range (\n-- * Description\n--\n-- | For signals regarding a change in the range or increments, refer to\n-- 'Adjustment' which is contained in the 'Range' object.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----Range\n-- | +----'Scale'\n-- | +----'Scrollbar'\n-- @\n\n-- * Types\n Range,\n RangeClass,\n castToRange,\n toRange,\n\n-- * Methods\n rangeGetAdjustment,\n rangeSetAdjustment,\n UpdateType(..),\n rangeGetUpdatePolicy,\n rangeSetUpdatePolicy,\n rangeGetInverted,\n rangeSetInverted,\n rangeGetValue,\n rangeSetValue,\n rangeSetIncrements,\n rangeSetRange,\n ScrollType(..),\n\n-- * Attributes\n rangeUpdatePolicy,\n rangeAdjustment,\n rangeInverted,\n rangeValue,\n\n-- * Signals\n onMoveSlider,\n afterMoveSlider,\n onAdjustBounds,\n afterAdjustBounds,\n onRangeValueChanged,\n afterRangeValueChanged\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\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.Enums\t(UpdateType(..), ScrollType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Get the 'Adjustment' which is the \\\"model\\\" object for 'Range'. See\n-- 'rangeSetAdjustment' for details.\n--\nrangeGetAdjustment :: RangeClass self => self\n -> IO Adjustment -- ^ returns a 'Adjustment'\nrangeGetAdjustment self =\n makeNewObject mkAdjustment $\n {# call unsafe range_get_adjustment #}\n (toRange self)\n\n-- | Sets the adjustment to be used as the \\\"model\\\" object for this range\n-- widget. The adjustment indicates the current range value, the minimum and\n-- maximum range values, the step\\\/page increments used for keybindings and\n-- scrolling, and the page size. The page size is normally 0 for 'Scale' and\n-- nonzero for 'Scrollbar', and indicates the size of the visible area of the\n-- widget being scrolled. The page size affects the size of the scrollbar\n-- slider.\n--\nrangeSetAdjustment :: RangeClass self => self\n -> Adjustment -- ^ @adjustment@ - a 'Adjustment'\n -> IO ()\nrangeSetAdjustment self adjustment =\n {# call range_set_adjustment #}\n (toRange self)\n adjustment\n\n-- | Gets the update policy of @range@. See 'rangeSetUpdatePolicy'.\n--\nrangeGetUpdatePolicy :: RangeClass self => self\n -> IO UpdateType -- ^ returns the current update policy\nrangeGetUpdatePolicy self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe range_get_update_policy #}\n (toRange self)\n\n-- | Sets the update policy for the range. 'UpdateContinuous' means that\n-- anytime the range slider is moved, the range value will change and the\n-- value_changed signal will be emitted. 'UpdateDelayed' means that the value\n-- will be updated after a brief timeout where no slider motion occurs, so\n-- updates are spaced by a short time rather than continuous.\n-- 'UpdateDiscontinuous' means that the value will only be updated when the\n-- user releases the button and ends the slider drag operation.\n--\nrangeSetUpdatePolicy :: RangeClass self => self\n -> UpdateType -- ^ @policy@ - update policy\n -> IO ()\nrangeSetUpdatePolicy self policy =\n {# call range_set_update_policy #}\n (toRange self)\n ((fromIntegral . fromEnum) policy)\n\n-- | Gets the value set by 'rangeSetInverted'.\n--\nrangeGetInverted :: RangeClass self => self\n -> IO Bool -- ^ returns @True@ if the range is inverted\nrangeGetInverted self =\n liftM toBool $\n {# call unsafe range_get_inverted #}\n (toRange self)\n\n-- | Ranges normally move from lower to higher values as the slider moves from\n-- top to bottom or left to right. Inverted ranges have higher values at the\n-- top or on the right rather than on the bottom or left.\n--\nrangeSetInverted :: RangeClass self => self\n -> Bool -- ^ @setting@ - @True@ to invert the range\n -> IO ()\nrangeSetInverted self setting =\n {# call range_set_inverted #}\n (toRange self)\n (fromBool setting)\n\n-- | Gets the current value of the range.\n--\nrangeGetValue :: RangeClass self => self\n -> IO Double -- ^ returns current value of the range.\nrangeGetValue self =\n liftM realToFrac $\n {# call unsafe range_get_value #}\n (toRange self)\n\n-- | Sets the current value of the range; if the value is outside the minimum\n-- or maximum range values, it will be clamped to fit inside them. The range\n-- emits the \\\"value_changed\\\" signal if the value changes.\n--\nrangeSetValue :: RangeClass self => self\n -> Double -- ^ @value@ - new value of the range\n -> IO ()\nrangeSetValue self value =\n {# call range_set_value #}\n (toRange self)\n (realToFrac value)\n\n-- | Sets the step and page sizes for the range. The step size is used when\n-- the user clicks the 'Scrollbar' arrows or moves 'Scale' via arrow keys. The\n-- page size is used for example when moving via Page Up or Page Down keys.\n--\nrangeSetIncrements :: RangeClass self => self\n -> Double -- ^ @step@ - step size\n -> Double -- ^ @page@ - page size\n -> IO ()\nrangeSetIncrements self step page =\n {# call range_set_increments #}\n (toRange self)\n (realToFrac step)\n (realToFrac page)\n\n-- | Sets the allowable values in the 'Range', and clamps the range value to\n-- be between @min@ and @max@. (If the range has a non-zero page size, it is\n-- clamped between @min@ and @max@ - page-size.)\n--\nrangeSetRange :: RangeClass self => self\n -> Double -- ^ @min@ - minimum range value\n -> Double -- ^ @max@ - maximum range value\n -> IO ()\nrangeSetRange self min max =\n {# call range_set_range #}\n (toRange self)\n (realToFrac min)\n (realToFrac max)\n\n--------------------\n-- Attributes\n\n-- | How the range should be updated on the screen.\n--\n-- Default value: 'UpdateContinuous'\n--\nrangeUpdatePolicy :: RangeClass self => Attr self UpdateType\nrangeUpdatePolicy = newAttr\n rangeGetUpdatePolicy\n rangeSetUpdatePolicy\n\n-- | The 'Adjustment' that contains the current value of this range object.\n--\nrangeAdjustment :: RangeClass self => Attr self Adjustment\nrangeAdjustment = newAttr\n rangeGetAdjustment\n rangeSetAdjustment\n\n-- | Invert direction slider moves to increase range value.\n--\n-- Default value: @False@\n--\nrangeInverted :: RangeClass self => Attr self Bool\nrangeInverted = newAttr\n rangeGetInverted\n rangeSetInverted\n\n-- | \\'value\\' property. See 'rangeGetValue' and 'rangeSetValue'\n--\nrangeValue :: RangeClass self => Attr self Double\nrangeValue = newAttr\n rangeGetValue\n rangeSetValue\n\n--------------------\n-- Signals\n\n-- | Emitted when the range value is changed either programmatically or by\n-- user action.\n--\nonRangeValueChanged, afterRangeValueChanged :: RangeClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonRangeValueChanged = connect_NONE__NONE \"value_changed\" False\nafterRangeValueChanged = connect_NONE__NONE \"value_changed\" True\n\n-- | Emitted when the range is adjusted by user action. Note the value can be\n-- outside the bounds of the range since it depends on the mouse position.\n--\n-- Usually you should use 'onRangeValueChanged' \\\/ 'afterRangeValueChanged'\n-- instead.\n--\nonAdjustBounds, afterAdjustBounds :: RangeClass self => self\n -> (Double -> IO ())\n -> IO (ConnectId self)\nonAdjustBounds = connect_DOUBLE__NONE \"adjust_bounds\" False\nafterAdjustBounds = connect_DOUBLE__NONE \"adjust_bounds\" True\n\n-- | Emitted when the user presses a key (e.g. Page Up, Home, Right Arrow) to\n-- move the slider. The 'ScrollType' parameter gives the key that was pressed.\n--\n-- Usually you should use 'onRangeValueChanged' \\\/\n-- 'afterRangeValueChanged' instead.\n--\nonMoveSlider, afterMoveSlider :: RangeClass self => self\n -> (ScrollType -> IO ())\n -> IO (ConnectId self)\nonMoveSlider = connect_ENUM__NONE \"move_slider\" False\nafterMoveSlider = connect_ENUM__NONE \"move_slider\" True\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Range\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.11 $ from $Date: 2005\/10\/19 12:57:36 $\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-- Base class for widgets which visualize an adjustment\n--\nmodule Graphics.UI.Gtk.Abstract.Range (\n-- * Description\n--\n-- | For signals regarding a change in the range or increments, refer to\n-- 'Adjustment' which is contained in the 'Range' object.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----Range\n-- | +----'Scale'\n-- | +----'Scrollbar'\n-- @\n\n-- * Types\n Range,\n RangeClass,\n castToRange,\n toRange,\n\n-- * Methods\n rangeGetAdjustment,\n rangeSetAdjustment,\n UpdateType(..),\n rangeGetUpdatePolicy,\n rangeSetUpdatePolicy,\n rangeGetInverted,\n rangeSetInverted,\n rangeGetValue,\n rangeSetValue,\n rangeSetIncrements,\n rangeSetRange,\n ScrollType(..),\n\n-- * Attributes\n rangeUpdatePolicy,\n rangeAdjustment,\n rangeInverted,\n rangeValue,\n\n-- * Signals\n onMoveSlider,\n afterMoveSlider,\n onAdjustBounds,\n afterAdjustBounds,\n-- onValueChanged,\n-- afterValueChanged,\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\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.Enums\t(UpdateType(..), ScrollType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Methods\n\n-- | Get the 'Adjustment' which is the \\\"model\\\" object for 'Range'. See\n-- 'rangeSetAdjustment' for details.\n--\nrangeGetAdjustment :: RangeClass self => self\n -> IO Adjustment -- ^ returns a 'Adjustment'\nrangeGetAdjustment self =\n makeNewObject mkAdjustment $\n {# call unsafe range_get_adjustment #}\n (toRange self)\n\n-- | Sets the adjustment to be used as the \\\"model\\\" object for this range\n-- widget. The adjustment indicates the current range value, the minimum and\n-- maximum range values, the step\\\/page increments used for keybindings and\n-- scrolling, and the page size. The page size is normally 0 for 'Scale' and\n-- nonzero for 'Scrollbar', and indicates the size of the visible area of the\n-- widget being scrolled. The page size affects the size of the scrollbar\n-- slider.\n--\nrangeSetAdjustment :: RangeClass self => self\n -> Adjustment -- ^ @adjustment@ - a 'Adjustment'\n -> IO ()\nrangeSetAdjustment self adjustment =\n {# call range_set_adjustment #}\n (toRange self)\n adjustment\n\n-- | Gets the update policy of @range@. See 'rangeSetUpdatePolicy'.\n--\nrangeGetUpdatePolicy :: RangeClass self => self\n -> IO UpdateType -- ^ returns the current update policy\nrangeGetUpdatePolicy self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe range_get_update_policy #}\n (toRange self)\n\n-- | Sets the update policy for the range. 'UpdateContinuous' means that\n-- anytime the range slider is moved, the range value will change and the\n-- value_changed signal will be emitted. 'UpdateDelayed' means that the value\n-- will be updated after a brief timeout where no slider motion occurs, so\n-- updates are spaced by a short time rather than continuous.\n-- 'UpdateDiscontinuous' means that the value will only be updated when the\n-- user releases the button and ends the slider drag operation.\n--\nrangeSetUpdatePolicy :: RangeClass self => self\n -> UpdateType -- ^ @policy@ - update policy\n -> IO ()\nrangeSetUpdatePolicy self policy =\n {# call range_set_update_policy #}\n (toRange self)\n ((fromIntegral . fromEnum) policy)\n\n-- | Gets the value set by 'rangeSetInverted'.\n--\nrangeGetInverted :: RangeClass self => self\n -> IO Bool -- ^ returns @True@ if the range is inverted\nrangeGetInverted self =\n liftM toBool $\n {# call unsafe range_get_inverted #}\n (toRange self)\n\n-- | Ranges normally move from lower to higher values as the slider moves from\n-- top to bottom or left to right. Inverted ranges have higher values at the\n-- top or on the right rather than on the bottom or left.\n--\nrangeSetInverted :: RangeClass self => self\n -> Bool -- ^ @setting@ - @True@ to invert the range\n -> IO ()\nrangeSetInverted self setting =\n {# call range_set_inverted #}\n (toRange self)\n (fromBool setting)\n\n-- | Gets the current value of the range.\n--\nrangeGetValue :: RangeClass self => self\n -> IO Double -- ^ returns current value of the range.\nrangeGetValue self =\n liftM realToFrac $\n {# call unsafe range_get_value #}\n (toRange self)\n\n-- | Sets the current value of the range; if the value is outside the minimum\n-- or maximum range values, it will be clamped to fit inside them. The range\n-- emits the \\\"value_changed\\\" signal if the value changes.\n--\nrangeSetValue :: RangeClass self => self\n -> Double -- ^ @value@ - new value of the range\n -> IO ()\nrangeSetValue self value =\n {# call range_set_value #}\n (toRange self)\n (realToFrac value)\n\n-- | Sets the step and page sizes for the range. The step size is used when\n-- the user clicks the 'Scrollbar' arrows or moves 'Scale' via arrow keys. The\n-- page size is used for example when moving via Page Up or Page Down keys.\n--\nrangeSetIncrements :: RangeClass self => self\n -> Double -- ^ @step@ - step size\n -> Double -- ^ @page@ - page size\n -> IO ()\nrangeSetIncrements self step page =\n {# call range_set_increments #}\n (toRange self)\n (realToFrac step)\n (realToFrac page)\n\n-- | Sets the allowable values in the 'Range', and clamps the range value to\n-- be between @min@ and @max@. (If the range has a non-zero page size, it is\n-- clamped between @min@ and @max@ - page-size.)\n--\nrangeSetRange :: RangeClass self => self\n -> Double -- ^ @min@ - minimum range value\n -> Double -- ^ @max@ - maximum range value\n -> IO ()\nrangeSetRange self min max =\n {# call range_set_range #}\n (toRange self)\n (realToFrac min)\n (realToFrac max)\n\n--------------------\n-- Attributes\n\n-- | How the range should be updated on the screen.\n--\n-- Default value: 'UpdateContinuous'\n--\nrangeUpdatePolicy :: RangeClass self => Attr self UpdateType\nrangeUpdatePolicy = newAttr\n rangeGetUpdatePolicy\n rangeSetUpdatePolicy\n\n-- | The 'Adjustment' that contains the current value of this range object.\n--\nrangeAdjustment :: RangeClass self => Attr self Adjustment\nrangeAdjustment = newAttr\n rangeGetAdjustment\n rangeSetAdjustment\n\n-- | Invert direction slider moves to increase range value.\n--\n-- Default value: @False@\n--\nrangeInverted :: RangeClass self => Attr self Bool\nrangeInverted = newAttr\n rangeGetInverted\n rangeSetInverted\n\n-- | \\'value\\' property. See 'rangeGetValue' and 'rangeSetValue'\n--\nrangeValue :: RangeClass self => Attr self Double\nrangeValue = newAttr\n rangeGetValue\n rangeSetValue\n\n--------------------\n-- Signals\n\n-- | Emitted when the range value is changed either programmatically or by\n-- user action.\n--\nonValueChanged, afterValueChanged :: RangeClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonValueChanged = connect_NONE__NONE \"value_changed\" False\nafterValueChanged = connect_NONE__NONE \"value_changed\" True\n\n-- | Emitted when the range is adjusted by user action. Note the value can be\n-- outside the bounds of the range since it depends on the mouse position.\n--\n-- Usually you should use 'onValueChanged' \\\/ 'afterValueChanged' instead.\n--\nonAdjustBounds, afterAdjustBounds :: RangeClass self => self\n -> (Double -> IO ())\n -> IO (ConnectId self)\nonAdjustBounds = connect_DOUBLE__NONE \"adjust_bounds\" False\nafterAdjustBounds = connect_DOUBLE__NONE \"adjust_bounds\" True\n\n-- | Emitted when the user presses a key (e.g. Page Up, Home, Right Arrow) to\n-- move the slider. The 'ScrollType' parameter gives the key that was pressed.\n--\n-- Usually you should use 'onValueChanged' \\\/ 'afterValueChanged' instead.\n--\nonMoveSlider, afterMoveSlider :: RangeClass self => self\n -> (ScrollType -> IO ())\n -> IO (ConnectId self)\nonMoveSlider = connect_ENUM__NONE \"move_slider\" False\nafterMoveSlider = connect_ENUM__NONE \"move_slider\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"eb3b94d41cdd9ef0c0119567e464c1abb2aa82d2","subject":"Correct arguments of a finally statement. This code has obviously never been tested. Thanks to Bertram Felgenhauer to spot this.","message":"Correct arguments of a finally statement.\nThis code has obviously never been tested. Thanks to Bertram Felgenhauer to spot this.\n","repos":"vincenthz\/webkit","old_file":"gnomevfs\/System\/Gnome\/VFS\/Marshal.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Marshal.chs","new_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- 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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Marshal (\n \n cToEnum,\n cFromEnum,\n cToBool,\n cFromBool,\n cToFlags,\n cFromFlags,\n genericResultMarshal,\n voidResultMarshal,\n newObjectResultMarshal,\n volumeOpCallbackMarshal\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport Data.Dynamic\nimport System.Glib.FFI\nimport System.Glib.Flags (Flags, toFlags, fromFlags)\nimport System.Glib.UTFString (peekUTFString)\n{#import System.Gnome.VFS.Types#}\nimport System.Gnome.VFS.Error\nimport Prelude hiding (error)\n\ncToEnum :: (Integral a, Enum b) => a -> b\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum a, Integral b) => a -> b\ncFromEnum = fromIntegral . fromEnum\n\ncToBool :: Integral a => a -> Bool\ncToBool = toBool . fromIntegral\n\ncFromBool :: Integral a => Bool -> a\ncFromBool = fromIntegral . fromBool\n\ncToFlags :: (Integral a, Flags b) => a -> [b]\ncToFlags = toFlags . fromIntegral\n\ncFromFlags :: (Flags a, Integral b) => [a] -> b\ncFromFlags = fromIntegral . fromFlags\n\ngenericResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO a\n -> IO b\n -> IO a\ngenericResultMarshal cAction cSuccessAction cFailureAction =\n do result <- liftM cToEnum $ cAction\n case result of\n Ok -> cSuccessAction\n errorCode -> do cFailureAction\n error result\n\nvoidResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO ()\nvoidResultMarshal cAction =\n genericResultMarshal cAction (return ()) (return ())\n\nnewObjectResultMarshal :: (ForeignPtr obj -> obj)\n -> (Ptr (Ptr obj) -> IO {# type GnomeVFSResult #})\n -> IO obj\nnewObjectResultMarshal objConstructor cNewObj =\n alloca $ \\cObjPtr ->\n do poke cObjPtr nullPtr\n genericResultMarshal (cNewObj cObjPtr)\n (do cObj <- peek cObjPtr\n assert (cObj \/= nullPtr) $ return ()\n newObj <- newForeignPtr_ cObj\n return $ objConstructor newObj)\n (do cObj <- peek cObjPtr\n assert (cObj == nullPtr) $ return ())\n\nvolumeOpCallbackMarshal :: VolumeOpSuccessCallback\n -> VolumeOpFailureCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\nvolumeOpCallbackMarshal successCallback failureCallback =\n let cCallback :: CVolumeOpCallback\n cCallback cSucceeded cError cDetailedError cUserData =\n let succeeded = cToBool cSucceeded\n cCallbackFunPtr = castPtrToFunPtr cUserData\n in (flip finally) (freeHaskellFunPtr cCallbackFunPtr) $\n if succeeded\n then assert (and [cError == nullPtr, cDetailedError == nullPtr]) $\n successCallback\n else assert (and [cError \/= nullPtr, cDetailedError \/= nullPtr]) $\n do error <- peekUTFString cError\n detailedError <- peekUTFString cDetailedError\n failureCallback error detailedError\n in makeVolumeOpCallback cCallback\nforeign import ccall safe \"wrapper\"\n makeVolumeOpCallback :: CVolumeOpCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\n","old_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- 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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Marshal (\n \n cToEnum,\n cFromEnum,\n cToBool,\n cFromBool,\n cToFlags,\n cFromFlags,\n genericResultMarshal,\n voidResultMarshal,\n newObjectResultMarshal,\n volumeOpCallbackMarshal\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport Data.Dynamic\nimport System.Glib.FFI\nimport System.Glib.Flags (Flags, toFlags, fromFlags)\nimport System.Glib.UTFString (peekUTFString)\n{#import System.Gnome.VFS.Types#}\nimport System.Gnome.VFS.Error\nimport Prelude hiding (error)\n\ncToEnum :: (Integral a, Enum b) => a -> b\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum a, Integral b) => a -> b\ncFromEnum = fromIntegral . fromEnum\n\ncToBool :: Integral a => a -> Bool\ncToBool = toBool . fromIntegral\n\ncFromBool :: Integral a => Bool -> a\ncFromBool = fromIntegral . fromBool\n\ncToFlags :: (Integral a, Flags b) => a -> [b]\ncToFlags = toFlags . fromIntegral\n\ncFromFlags :: (Flags a, Integral b) => [a] -> b\ncFromFlags = fromIntegral . fromFlags\n\ngenericResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO a\n -> IO b\n -> IO a\ngenericResultMarshal cAction cSuccessAction cFailureAction =\n do result <- liftM cToEnum $ cAction\n case result of\n Ok -> cSuccessAction\n errorCode -> do cFailureAction\n error result\n\nvoidResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO ()\nvoidResultMarshal cAction =\n genericResultMarshal cAction (return ()) (return ())\n\nnewObjectResultMarshal :: (ForeignPtr obj -> obj)\n -> (Ptr (Ptr obj) -> IO {# type GnomeVFSResult #})\n -> IO obj\nnewObjectResultMarshal objConstructor cNewObj =\n alloca $ \\cObjPtr ->\n do poke cObjPtr nullPtr\n genericResultMarshal (cNewObj cObjPtr)\n (do cObj <- peek cObjPtr\n assert (cObj \/= nullPtr) $ return ()\n newObj <- newForeignPtr_ cObj\n return $ objConstructor newObj)\n (do cObj <- peek cObjPtr\n assert (cObj == nullPtr) $ return ())\n\nvolumeOpCallbackMarshal :: VolumeOpSuccessCallback\n -> VolumeOpFailureCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\nvolumeOpCallbackMarshal successCallback failureCallback =\n let cCallback :: CVolumeOpCallback\n cCallback cSucceeded cError cDetailedError cUserData =\n let succeeded = cToBool cSucceeded\n cCallbackFunPtr = castPtrToFunPtr cUserData\n in finally (freeHaskellFunPtr cCallbackFunPtr) $\n if succeeded\n then assert (and [cError == nullPtr, cDetailedError == nullPtr]) $\n successCallback\n else assert (and [cError \/= nullPtr, cDetailedError \/= nullPtr]) $\n do error <- peekUTFString cError\n detailedError <- peekUTFString cDetailedError\n failureCallback error detailedError\n in makeVolumeOpCallback cCallback\nforeign import ccall safe \"wrapper\"\n makeVolumeOpCallback :: CVolumeOpCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"ecb2ea911c09b859708d6ed938f696928fbf9499","subject":"Use 'SourceGutterClass sg => sg' replace SourceGutter as function argument.","message":"Use 'SourceGutterClass sg => sg' replace SourceGutter as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceGutter.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceGutter.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceGutter\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceGutter (\n-- * Description\n-- | The 'SourceGutter' object represents the left and right gutters of the text view. It is used by\n-- 'SourceView' to draw the line numbers and category marks that might be present on a line. By\n-- packing additional 'CellRenderer' objects in the gutter, you can extend the gutter with your own\n-- custom drawings.\n-- \n-- The gutter works very much the same way as cells rendered in a 'TreeView'. The concept is similar,\n-- with the exception that the gutter does not have an underlying 'TreeModel'. Instead, you should use\n-- 'sourceGutterSetCellDataFunc' to set a callback to fill in any of the cell renderers\n-- properties, given the line for which the cell is to be rendered. Renderers are inserted into the\n-- gutter at a certain position. \n-- The builtin line number renderer is at position\n-- 'SourceViewGutterPositionLines (-30)' and the marks renderer is at\n-- 'SourceViewGutterPositionMarks (-20)'. You can use these values to position custom renderers\n-- accordingly. The width of a cell renderer can be specified as either fixed (using\n-- 'cellRendererSetFixedSize') or dynamic, in which case you must set\n-- 'sourceGutterSetCellSizeFunc'. This callback is used to set the properties of the renderer\n-- such that @gtkCellRendererGetSize@ yields the maximum width of the cell.\n\n-- * Types\n SourceGutter,\n SourceGutterClass,\n\n-- * Methods\n sourceGutterGetWindow,\n sourceGutterInsert,\n sourceGutterReorder,\n sourceGutterRemove,\n sourceGutterQueueDraw,\n\n-- * Attributes\n sourceGutterView,\n sourceGutterWindowType,\n\n-- * Signals\n sourceGutterCellActivated,\n sourceGutterQueryTooltip,\n) where\n\nimport Control.Monad\t(liftM)\nimport Control.Monad.Reader ( runReaderT )\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.GtkInternals ( TextIter, mkTextIterCopy )\nimport Graphics.UI.Gtk.Gdk.EventM (EventM, EAny)\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the 'Window' of the gutter. The window will only be available when the gutter has at least one,\n-- non-zero width, cell renderer packed.\nsourceGutterGetWindow :: SourceGutterClass sg => sg -> IO (Maybe DrawWindow)\nsourceGutterGetWindow sb =\n maybeNull (makeNewGObject mkDrawWindow) $\n {#call gtk_source_gutter_get_window #} (toSourceGutter sb)\n\n-- | Inserts renderer into gutter at position.\nsourceGutterInsert :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the renderers position \n -> IO ()\nsourceGutterInsert gutter renderer position =\n {#call gtk_source_gutter_insert #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Reorders renderer in gutter to new position.\nsourceGutterReorder :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the new renderer position \n -> IO ()\nsourceGutterReorder gutter renderer position =\n {#call gtk_source_gutter_reorder #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Removes renderer from gutter.\nsourceGutterRemove :: (CellRendererClass cell, SourceGutterClass sg) => sg\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> IO ()\nsourceGutterRemove gutter renderer =\n {#call gtk_source_gutter_remove #}\n (toSourceGutter gutter)\n (toCellRenderer renderer)\n\n-- | Invalidates the drawable area of the gutter. You can use this to force a redraw of the gutter if\n-- something has changed and needs to be redrawn.\nsourceGutterQueueDraw :: SourceGutterClass sg => sg -> IO ()\nsourceGutterQueueDraw sb =\n {#call gtk_source_gutter_queue_draw #} (toSourceGutter sb)\n\n-- | The 'SourceView' of the gutter\nsourceGutterView :: SourceGutterClass sg => Attr sg SourceView\nsourceGutterView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The text window type on which the window is placed\n-- \n-- Default value: 'TextWindowPrivate'\nsourceGutterWindowType :: SourceGutterClass sg => Attr sg TextWindowType\nsourceGutterWindowType = newAttrFromEnumProperty \"window-type\"\n {#call pure unsafe gtk_text_window_type_get_type #}\n \n-- | Emitted when a cell has been activated (for instance when there was a button press on the cell). The\n-- signal is only emitted for cells that have the activatable property set to 'True'.\nsourceGutterCellActivated :: SourceGutterClass sg => Signal sg (CellRenderer -> TextIter -> EventM EAny ()) \nsourceGutterCellActivated =\n Signal (\\after obj fun -> \n connect_OBJECT_PTR_BOXED__NONE \"cell-activated\" mkTextIterCopy after obj\n (\\cr eventPtr iter -> runReaderT (fun cr iter) eventPtr)\n )\n\n-- | Emitted when a tooltip is requested for a specific cell. Signal handlers can return 'True' to notify\n-- the tooltip has been handled.\nsourceGutterQueryTooltip :: SourceGutterClass sg => Signal sg (CellRenderer -> TextIter -> Tooltip -> IO Bool)\nsourceGutterQueryTooltip = \n Signal $ connect_OBJECT_BOXED_OBJECT__BOOL \"query-tooltip\" mkTextIterCopy\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceGutter\n--\n-- Author : Andy Stewart\n--\n-- Created: 08 Aug 2010\n--\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.SourceGutter (\n-- * Description\n-- | The 'SourceGutter' object represents the left and right gutters of the text view. It is used by\n-- 'SourceView' to draw the line numbers and category marks that might be present on a line. By\n-- packing additional 'CellRenderer' objects in the gutter, you can extend the gutter with your own\n-- custom drawings.\n-- \n-- The gutter works very much the same way as cells rendered in a 'TreeView'. The concept is similar,\n-- with the exception that the gutter does not have an underlying 'TreeModel'. Instead, you should use\n-- 'sourceGutterSetCellDataFunc' to set a callback to fill in any of the cell renderers\n-- properties, given the line for which the cell is to be rendered. Renderers are inserted into the\n-- gutter at a certain position. \n-- The builtin line number renderer is at position\n-- 'SourceViewGutterPositionLines (-30)' and the marks renderer is at\n-- 'SourceViewGutterPositionMarks (-20)'. You can use these values to position custom renderers\n-- accordingly. The width of a cell renderer can be specified as either fixed (using\n-- 'cellRendererSetFixedSize') or dynamic, in which case you must set\n-- 'sourceGutterSetCellSizeFunc'. This callback is used to set the properties of the renderer\n-- such that @gtkCellRendererGetSize@ yields the maximum width of the cell.\n\n-- * Types\n SourceGutter,\n\n-- * Methods\n sourceGutterGetWindow,\n sourceGutterInsert,\n sourceGutterReorder,\n sourceGutterRemove,\n sourceGutterQueueDraw,\n\n-- * Attributes\n sourceGutterView,\n sourceGutterWindowType,\n\n-- * Signals\n sourceGutterCellActivated,\n sourceGutterQueryTooltip,\n) where\n\nimport Control.Monad\t(liftM)\nimport Control.Monad.Reader ( runReaderT )\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Multiline.TextView (TextWindowType (..))\nimport Graphics.UI.GtkInternals ( TextIter, mkTextIterCopy )\nimport Graphics.UI.Gtk.Gdk.EventM (EventM, EAny)\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- | Get the 'Window' of the gutter. The window will only be available when the gutter has at least one,\n-- non-zero width, cell renderer packed.\nsourceGutterGetWindow :: SourceGutter -> IO (Maybe DrawWindow)\nsourceGutterGetWindow sb =\n maybeNull (makeNewGObject mkDrawWindow) $\n {#call gtk_source_gutter_get_window #} sb\n\n-- | Inserts renderer into gutter at position.\nsourceGutterInsert :: CellRendererClass cell => SourceGutter \n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the renderers position \n -> IO ()\nsourceGutterInsert gutter renderer position =\n {#call gtk_source_gutter_insert #}\n gutter\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Reorders renderer in gutter to new position.\nsourceGutterReorder :: CellRendererClass cell => SourceGutter \n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> Int -- ^ @position@ the new renderer position \n -> IO ()\nsourceGutterReorder gutter renderer position =\n {#call gtk_source_gutter_reorder #}\n gutter\n (toCellRenderer renderer)\n (fromIntegral position)\n\n-- | Removes renderer from gutter.\nsourceGutterRemove :: CellRendererClass cell => SourceGutter\n -> cell -- ^ @renderer@ a 'CellRenderer' \n -> IO ()\nsourceGutterRemove gutter renderer =\n {#call gtk_source_gutter_remove #}\n gutter\n (toCellRenderer renderer)\n\n-- | Invalidates the drawable area of the gutter. You can use this to force a redraw of the gutter if\n-- something has changed and needs to be redrawn.\nsourceGutterQueueDraw :: SourceGutter -> IO ()\nsourceGutterQueueDraw sb =\n {#call gtk_source_gutter_queue_draw #} sb\n\n-- | The 'SourceView' of the gutter\nsourceGutterView :: Attr SourceGutter SourceView\nsourceGutterView = newAttrFromObjectProperty \"view\"\n {#call pure unsafe gtk_source_view_get_type #}\n\n-- | The text window type on which the window is placed\n-- \n-- Default value: 'TextWindowPrivate'\nsourceGutterWindowType :: Attr SourceGutter TextWindowType\nsourceGutterWindowType = newAttrFromEnumProperty \"window-type\"\n {#call pure unsafe gtk_text_window_type_get_type #}\n \n-- | Emitted when a cell has been activated (for instance when there was a button press on the cell). The\n-- signal is only emitted for cells that have the activatable property set to 'True'.\nsourceGutterCellActivated :: Signal SourceGutter (CellRenderer -> TextIter -> EventM EAny ()) \nsourceGutterCellActivated =\n Signal (\\after obj fun -> \n connect_OBJECT_PTR_BOXED__NONE \"cell-activated\" mkTextIterCopy after obj\n (\\cr eventPtr iter -> runReaderT (fun cr iter) eventPtr)\n )\n\n-- | Emitted when a tooltip is requested for a specific cell. Signal handlers can return 'True' to notify\n-- the tooltip has been handled.\nsourceGutterQueryTooltip :: Signal SourceGutter (CellRenderer -> TextIter -> Tooltip -> IO Bool)\nsourceGutterQueryTooltip = \n Signal $ connect_OBJECT_BOXED_OBJECT__BOOL \"query-tooltip\" mkTextIterCopy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"90f7230a811ef6a553d4b4549e2154979558b25a","subject":"First stab at Internal.chs haddock ToC","message":"First stab at Internal.chs haddock ToC\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 ( \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, tagVal, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, isendPtr, ibsendPtr, issendPtr, irecv,\n 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\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*- #}\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{- 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 , mpiErrorCode :: CInt\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 code\n\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 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*- #}\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{- 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 , mpiErrorCode :: CInt\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 code\n\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":"6fe5985167d09d281a324c29ec05c8d3c2de732b","subject":"[project @ 2002-07-12 13:09:23 by dg22]","message":"[project @ 2002-07-12 13:09:23 by dg22]\n\nFixed references that used the old names for packing widgets.\n\ndarcs-hash:20020712130923-18bf1-3b992b25f0ac7dc810b7992244436a98548ba4a6.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"6ae46e8d8ec974c83e999e8d65d0413cc3082285","subject":"add launchKernel', which passes kernel arguments directly","message":"add launchKernel', which passes kernel arguments directly\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/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\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\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\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--\nlaunchKernel\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\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#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":"790dc1f9ca17a15f177b8f332d2ff4fc24a67c58","subject":"sourceMarkNext\/Prev should use 'Maybe'","message":"sourceMarkNext\/Prev should use 'Maybe'\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n\n-- * Methods\n castToSourceMark,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMark \n -> Maybe String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO (Maybe SourceMark) -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = \n maybeNull (makeNewGObject mkSourceMark) $\n maybeWith withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n\n-- * Methods\n castToSourceMark,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMark \n -> String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO SourceMark -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = makeNewGObject mkSourceMark $\n withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMark \n -> String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO SourceMark -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = makeNewGObject mkSourceMark $\n withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f1b45fd61b7fb21799555380b9af7f78a5e0acf9","subject":"Fix hierarchy docs for 'DoubleWindow'.","message":"Fix hierarchy docs for 'DoubleWindow'.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/DoubleWindow.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/DoubleWindow.chs","new_contents":"{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.DoubleWindow\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_Double_WindowC.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 Graphics.UI.FLTK.LowLevel.Hierarchy\n\n{# fun Fl_DerivedDouble_Window_Destroy as windowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) DoubleWindow orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n\n{# fun Fl_DerivedDouble_Window_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) DoubleWindow orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hide' windowPtr\n\n{# fun Fl_DerivedDouble_Window_show as windowShow' {id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) DoubleWindow orig impl where\n runOp _ _ window = withRef window (\\p -> windowShow' p)\n\n{#fun Fl_DerivedDouble_Window_handle as windowHandle'\n { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) DoubleWindow orig impl where\n runOp _ _ window event = withRef window (\\p -> windowHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n{# fun Fl_DerivedDouble_Window_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) DoubleWindow 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_DerivedDouble_Window_flush as flush' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) DoubleWindow orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> flush' windowPtr\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.DoubleWindow\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.DoubleWindow\"\n-- @\n\n-- $functions\n-- @\n-- destroy :: 'Ref' 'DoubleWindow' -> 'IO' ()\n--\n-- flush :: 'Ref' 'DoubleWindow' -> 'IO' ()\n--\n-- handle :: 'Ref' 'DoubleWindow' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n--\n-- hide :: 'Ref' 'DoubleWindow' -> 'IO' ()\n--\n-- resize :: 'Ref' 'DoubleWindow' -> 'Rectangle' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'DoubleWindow' -> 'IO' ()\n-- @\n","old_contents":"{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.DoubleWindow\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_Double_WindowC.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 Graphics.UI.FLTK.LowLevel.Hierarchy\n\n{# fun Fl_DerivedDouble_Window_Destroy as windowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) DoubleWindow orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n\n{# fun Fl_DerivedDouble_Window_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) DoubleWindow orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hide' windowPtr\n\n{# fun Fl_DerivedDouble_Window_show as windowShow' {id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) DoubleWindow orig impl where\n runOp _ _ window = withRef window (\\p -> windowShow' p)\n\n{#fun Fl_DerivedDouble_Window_handle as windowHandle'\n { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) DoubleWindow orig impl where\n runOp _ _ window event = withRef window (\\p -> windowHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n\n{# fun Fl_DerivedDouble_Window_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) DoubleWindow 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_DerivedDouble_Window_flush as flush' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) DoubleWindow orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> flush' windowPtr\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.DoubleWindow\"\n-- @\n\n-- $functions\n-- @\n-- destroy :: 'Ref' 'DoubleWindow' -> 'IO' ()\n--\n-- flush :: 'Ref' 'DoubleWindow' -> 'IO' ()\n--\n-- handle :: 'Ref' 'DoubleWindow' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n--\n-- hide :: 'Ref' 'DoubleWindow' -> 'IO' ()\n--\n-- resize :: 'Ref' 'DoubleWindow' -> 'Rectangle' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'DoubleWindow' -> 'IO' ()\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"35c1df766772aaaaaeb64a2f12ebda6754b45d44","subject":"[project @ 2003-11-02 23:57:07 by as49]","message":"[project @ 2003-11-02 23:57:07 by as49]\n\nAdded marshalling functions to create GLists and GSLists.\n\ndarcs-hash:20031102235707-d90cf-a474609cf76d924c74e02aa158d9d652ed3f6a03.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/glib\/GList.chs","new_file":"gtk\/glib\/GList.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n-- \n-- Created: 19 March 2002\n--\n-- Version $Revision: 1.8 $ from $Date: 2003\/11\/02 23:57:07 $\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-- * Defines functions to extract data from a GList and to produce a GList from\n-- a list of pointers.\n--\n-- * The same for GSList.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n--\nmodule GList(\n ptrToInt,\n GList,\n fromGList,\n toGList,\n GSList,\n readGSList,\n fromGSList,\n fromGSListRev,\n toGSList\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n\n{# context lib=\"g\" prefix=\"g\" #}\n\n{#pointer * GList#}\n{#pointer * GSList#}\n\n-- methods\n\n-- Convert a pointer to an Int.\n--\nptrToInt :: Ptr a -> Int\nptrToInt ptr = minusPtr ptr nullPtr \n\n-- Turn a GList into a list of pointers.\n--\nfromGList :: GList -> IO [Ptr a]\nfromGList glist = do\n glist' <- {#call unsafe list_reverse#} glist\n extractList glist' []\n where\n extractList gl xs\n | gl==nullPtr = return xs\n | otherwise = do\n\tx <- {#get GList.data#} gl\n\tgl' <- {#call unsafe list_delete_link#} gl gl\n\textractList gl' (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers but don't destroy the list.\n--\nreadGSList :: GSList -> IO [Ptr a]\nreadGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#get GSList->next#} gslist\n xs <- readGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers.\n--\nfromGSList :: GSList -> IO [Ptr a]\nfromGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#call unsafe slist_delete_link#} gslist gslist\n xs <- fromGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers and reverse it.\n--\nfromGSListRev :: GSList -> IO [Ptr a]\nfromGSListRev gslist =\n extractList gslist []\n where\n extractList gslist xs\n | gslist==nullPtr = return xs\n | otherwise\t= do\n\tx <- {#get GSList->data#} gslist\n\tgslist' <- {#call unsafe slist_delete_link#} gslist gslist\n\textractList gslist' (castPtr x:xs)\n\n-- Convert an Int into a pointer.\n--\nintToPtr :: Int -> Ptr a\nintToPtr int = plusPtr nullPtr int\n\n\n-- Turn a list of something into a GList.\n--\ntoGList :: [Ptr a] -> IO GList\ntoGList xs = makeList nullPtr xs\n where\n -- makeList :: GList -> [Ptr a] -> IO GList\n makeList current (x:xs) = do\n newHead <- {#call unsafe list_prepend#} current (castPtr x)\n makeList newHead xs\n makeList current [] = return current\n\n-- Turn a list of something into a GSList.\n--\ntoGSList :: [Ptr a] -> IO GSList\ntoGSList xs = makeList nullPtr xs\n where\n -- makeList :: GSList -> [Ptr a] -> IO GSList\n makeList current (x:xs) = do\n newHead <- {#call unsafe slist_prepend#} current (castPtr x)\n makeList newHead xs\n makeList current [] = return current\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n-- \n-- Created: 19 March 2002\n--\n-- Version $Revision: 1.7 $ from $Date: 2003\/07\/09 22:42:44 $\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-- * Define functions to extract data from a GList and to produce a GList from\n-- a list of pointers.\n--\n-- * Define functions to extract data from a GSList.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Figure out if we ever need to generate a GList.\n--\nmodule GList(\n ptrToInt,\n GList,\n fromGList,\n -- toGList,\n GSList,\n readGSList,\n fromGSList,\n fromGSListRev\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n\n{# context lib=\"g\" prefix=\"g\" #}\n\n{#pointer * GList#}\n{#pointer * GSList#}\n\n-- methods\n\n-- Convert a pointer to an Int.\n--\nptrToInt :: Ptr a -> Int\nptrToInt ptr = minusPtr ptr nullPtr \n\n-- Turn a GList into a list of pointers.\n--\nfromGList :: GList -> IO [Ptr a]\nfromGList glist = do\n glist' <- {#call unsafe list_reverse#} glist\n extractList glist' []\n where\n extractList gl xs\n | gl==nullPtr = return xs\n | otherwise = do\n\tx <- {#get GList.data#} gl\n\tgl' <- {#call unsafe list_delete_link#} gl gl\n\textractList gl' (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers but don't destroy the list.\n--\nreadGSList :: GSList -> IO [Ptr a]\nreadGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#get GSList->next#} gslist\n xs <- readGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers.\n--\nfromGSList :: GSList -> IO [Ptr a]\nfromGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#call unsafe slist_delete_link#} gslist gslist\n xs <- fromGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers and reverse it.\n--\nfromGSListRev :: GSList -> IO [Ptr a]\nfromGSListRev gslist =\n extractList gslist []\n where\n extractList gslist xs\n | gslist==nullPtr = return xs\n | otherwise\t= do\n\tx <- {#get GSList->data#} gslist\n\tgslist' <- {#call unsafe slist_delete_link#} gslist gslist\n\textractList gslist' (castPtr x:xs)\n\n-- Convert an Int into a pointer.\n--\nintToPtr :: Int -> Ptr a\nintToPtr int = plusPtr nullPtr int\n\n\n-- Turn a list of something into a GList.\n--\ntoGList :: [a] -> (a -> Ptr b) -> IO GList\ntoGList xs conv = makeList nullPtr xs\n where\n -- makeList :: GList -> [a] -> IO GList\n makeList current (x:xs) = do\n newHead <- {#call unsafe list_prepend#} current ((castPtr.conv) x)\n makeList newHead xs\n makeList current [] = return current\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"308e832b052b223bd18ea68a80dd37e31da41bea","subject":"Cleaned up description of the Matrix datatype.","message":"Cleaned up description of the Matrix datatype.","repos":"vincenthz\/webkit","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation.\n--\n-- The Matrix type represents a 2x2 transformation matrix along with a\n-- translation vector. @Matrix a1 a2 b1 b2 c1 c2@ describes the\n-- transformation of a point with coordinates x,y that is defined by\n--\n-- > \/ x' \\ = \/ a1 b1 \\ \/ x \\ + \/ c1 \\\n-- > \\ y' \/ \\ a2 b2 \/ \\ y \/ \\ c2 \/\n--\n-- or\n--\n-- > x' = a1 * x + b1 * y + c1\n-- > y' = a2 * x + b2 * y + c2\n\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"66536012d4d8162cfb03c358a4620c0a8f63cf6d","subject":"Fix a conflict in DrawWindow.","message":"Fix a conflict in DrawWindow.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer","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":"eb5431b82368747c14f1be3e9f9199382c0146f9","subject":"[project @ 2002-07-08 09:13:09 by as49]","message":"[project @ 2002-07-08 09:13:09 by as49]\n\nChanged the type of eventsPending to the propper one.\n\ndarcs-hash:20020708091309-d90cf-180324906f19bf6658d2a171040802166e80bfd1.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/general\/General.chs","new_file":"gtk\/general\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:13:09 $\n--\n-- Copyright (c) [2000..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--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n-- \n-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry General initialization@\n--\n-- Author : Manuel M. T. Chakravarty\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/05\/24 09:43:24 $\n--\n-- Copyright (c) [1998..2001] Manuel M. T. Chakravarty\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-- * quitAddDestroy, quitAdd, quitRemove, timeoutAdd, timeoutRemove, idleAdd,\n-- idleRemove, inputAdd, inputRemove\n--\n{-# OPTIONS -optc-include gtk\/gtk.h #-}\nmodule General(\n setLocale,\n-- getDefaultLanguage,\n init,\n eventsPending,\n main,\n mainLevel,\n mainQuit,\n mainIteration,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n mkDestructor,\n DestroyNotify\n ) where\n\nimport Prelude\n hiding (init)\nimport System (getProgName, getArgs, ExitCode(ExitSuccess, ExitFailure))\nimport Monad\t(liftM, mapM)\nimport Foreign\nimport UTFCForeign\nimport IOExts\t(newIORef, readIORef, writeIORef)\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\t \n{#import Signal#}\nimport Enums (InputCondition(..))\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n-- @method setLocale@ Ensure that the current locale is read.\n--\nsetLocale :: IO String\nsetLocale = do\n strPtr <- {#call unsafe set_locale#}\n str <- peekCString strPtr\n destruct strPtr\n return str\n\n\n-- @dunno@Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n-- * @literal@\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekCString strPtr\n-- destruct strPtr\n-- return str\n\n\n-- @method init@ initialize GTK+\n--\n-- * extracts all GTK+ specific arguments from the given options list\n--\ninit :: Maybe (String, [String]) -> IO (String, [String])\ninit Nothing = do\n prog <- getProgName\n args <- getArgs\n init $ Just (prog, args)\ninit (Just (prog, args)) = do\n let allArgs = (prog:args)\n argc = length allArgs\n withMany withCString allArgs $ \\addrs ->\n withArray\t addrs $ \\argv ->\n withObject\t argv $ \\argvp ->\n withObject\t argc $ \\argcp ->\n do \n-- {#call unsafe init#} argcp argvp\n {#call unsafe init#} (castPtr argcp) (castPtr argvp)\n argc' <- peek argcp\n argv' <- peek argvp\n addrs' <- peekArray argc' argv'\n _:args' <- mapM peekCString addrs' -- drop the program name\n return (prog, args')\n\n-- @method eventsPending@ Inquire the number of events pending on the event\n-- queue\n--\neventsPending :: IO Bool\neventsPending = liftM toBool {#call unsafe events_pending#}\n\n-- @method main@ GTK+'s main event loop\n--\nmain :: IO ()\nmain = {#call main#}\n\n-- @method mainLevel@ Inquire the main level\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- @method mainQuit@ Exit the main event loop\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- @method mainIteration@ process events\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- @method mainIterationDo@ process events\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- @method grabAdd@ add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- @method grabGetCurrent@ 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-- @method grabRemove@ remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n\n{#pointer Function#}\n\nforeign export dynamic mkHandler :: IO {#type gint#} -> IO Function\n\n{#pointer DestroyNotify#}\n\nforeign export dynamic mkDestructor :: IO () -> IO DestroyNotify\n\ntype HandlerId = {#type guint#}\n\n-- Turn a function into a function pointer and a destructor pointer.\n--\nmakeCallback :: IO {#type gint#} -> IO (Function, DestroyNotify)\nmakeCallback fun = do\n funPtr <- mkHandler fun\n dRef <- newIORef nullFunPtr\n dPtr <- mkDestructor $ do\n freeHaskellFunPtr funPtr\n dPtr <- readIORef dRef\n freeHaskellFunPtr dPtr\n writeIORef dRef dPtr\n return (funPtr, dPtr)\n\n-- @method timeoutAdd@ Register a function that is to be called after\n-- @ref arg interval@ ms have been elapsed.\n--\n-- * If the function returns False it will be removed.\n--\ntimeoutAdd :: IO Bool -> Int -> IO HandlerId\ntimeoutAdd fun msec = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe timeout_add_full#} (fromIntegral msec) funPtr nullFunPtr \n nullPtr dPtr\n\n-- @method timeoutRemove@ Remove a previously added timeout handler by its\n-- @ref type TimeoutId@.\n--\ntimeoutRemove :: HandlerId -> IO ()\ntimeoutRemove = {#call unsafe timeout_remove#}\n\n-- @method idleAdd@ Add a callback that is called whenever the system is idle.\n--\n-- * A priority can be specified.\n--\nidleAdd :: IO Bool -> Int -> IO HandlerId\nidleAdd fun pri = do\n (funPtr, dPtr) <- makeCallback (liftM fromBool fun)\n {#call unsafe idle_add_full#} (fromIntegral pri) funPtr nullFunPtr\n nullPtr dPtr\n\n-- @method idleRemove@ Remove a previously added idle handler by its\n-- @ref arg TimeoutId@.\n--\nidleRemove :: HandlerId -> IO ()\nidleRemove = {#call unsafe idle_remove#}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f0c6b86fa3fe9feae27a889dc2d9622c32e9785b","subject":"gstreamer: hopefully fix takeObject & peekObject for real this time","message":"gstreamer: hopefully fix takeObject & peekObject for real this time\n\ntakeObject: to be used when a function returns an object that must be unreffed at GC.\n If the object has a floating reference, the float flag is removed.\n\npeekObject: to be used when an object must not be unreffed. A ref is added, and is\n removed at GC. The floating flag is not touched.\n\ndarcs-hash:20071020195000-21862-84542b2cde523652238158a6854f327cf4bbe7c2.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n cObjectRef cObject\n takeObject cObject\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat\n newForeignPtr (castPtr cObject) objectFinalizer\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a450171c8906ac84a1bdf1bc11c425ea4e8a8c8e","subject":"[project @ 2002-07-17 16:09:05 by juhp]","message":"[project @ 2002-07-17 16:09:05 by juhp]\n\nBind entryGetText.\n\ndarcs-hash:20020717160905-f332a-4a1345807c1b19c42916f32326fb2c8714e855f7.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/entry\/Entry.chs","new_file":"gtk\/entry\/Entry.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Entry@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 16:09:05 $\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 lets the user enter a single line of text.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * A couple of signals are not bound because I could not figure out what\n-- they mean. Some of them do not seem to be emitted at all.\n--\nmodule Entry(\n Entry,\n EntryClass,\n castToEntry,\n entrySelectRegion,\n entryGetSelectionBounds,\n entryInsertText,\n entryDeleteText,\n entryGetChars,\n entryCutClipboard,\n entryCopyClipboard,\n entryPasteClipboard,\n entryDeleteSelection,\n entrySetEditable,\n entryNew,\n entrySetText,\n entryGetText,\n entryAppendText,\n entryPrependText,\n entrySetVisibility,\n entrySetInvisibleChar,\n entrySetMaxLength,\n entryGetActivatesDefault,\n entrySetActivatesDefault,\n entryGetHasFrame,\n entrySetHasFrame,\n entryGetWidthChars,\n entrySetWidthChars,\n onEntryActivate,\n afterEntryActivate,\n onEntryChanged,\n afterEntryChanged,\n onCopyClipboard,\n afterCopyClipboard,\n onCutClipboard,\n afterCutClipboard,\n onPasteClipboard,\n afterPasteClipboard,\n onDeleteText,\n afterDeleteText,\n onInsertAtCursor,\n afterInsertAtCursor,\n onToggleOverwrite,\n afterToggleOverwrite\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Char\t(ord)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods originating in the Editable base class which is not really a base\n-- class of in the Gtk Hierarchy (it is non-existant). I renamed\n{#pointer *Editable foreign#}\n\ntoEditable :: EntryClass ed => ed -> Editable\ntoEditable = castForeignPtr.unEntry.toEntry\n\n-- @method entrySelectRegion@ Select a span of text.\n--\n-- * A negative @ref arg end@ position will make the selection extend to the\n-- end of the buffer.\n--\n-- * Calling this function with @ref arg start@=1 and @ref arg end@=4 it will\n-- mark \"ask\" in the string \"Haskell\". (FIXME: verify)\n--\nentrySelectRegion :: EntryClass ed => ed -> Int -> Int -> IO ()\nentrySelectRegion ed start end = {#call editable_select_region#}\n (toEditable ed) (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetSelectionBounds@ Get the span of the current selection.\n--\n-- * The returned tuple is not ordered. The second index represents the\n-- position of the cursor. The first index is the other end of the\n-- selection. If both numbers are equal there is in fact no selection.\n--\nentryGetSelectionBounds :: EntryClass ed => ed -> IO (Int,Int)\nentryGetSelectionBounds ed = alloca $ \\startPtr -> alloca $ \\endPtr -> do\n {#call unsafe editable_get_selection_bounds#} (toEditable ed) startPtr endPtr\n start <- liftM fromIntegral $ peek startPtr\n end\t<- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- @method entryInsertText@ Insert new text at the specified position.\n--\n-- * If the position is invalid the text will be inserted at the end of the\n-- buffer. The returned value reflects the actual insertion point.\n--\nentryInsertText :: EntryClass ed => ed -> String -> Int -> IO Int\nentryInsertText ed str pos = withObject (fromIntegral pos) $ \\posPtr ->\n withCStringLen str $ \\(strPtr,len) -> do\n {#call editable_insert_text#} (toEditable ed) strPtr (fromIntegral len) \n posPtr\n liftM fromIntegral $ peek posPtr\n\n-- @method entryDeleteText@ Delete a given range of text.\n--\n-- * If the @ref arg end@ position is invalid, it is set to the lenght of the\n-- buffer.\n--\n-- * @ref arg start@ is restricted to 0..@end.\n--\nentryDeleteText :: EntryClass ed => ed -> Int -> Int -> IO ()\nentryDeleteText ed start end = {#call editable_delete_text#} (toEditable ed)\n (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetChars@ Retrieve a range of characters.\n--\n-- * Set @ref arg end@ to a negative value to reach the end of the buffer.\n--\nentryGetChars :: EntryClass ed => ed -> Int -> Int -> IO String\nentryGetChars ed start end = do\n strPtr <- {#call unsafe editable_get_chars#} (toEditable ed) \n (fromIntegral start) (fromIntegral end)\n str <- peekCString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n-- @method entryCutClipboard@ Cut the selected characters to the Clipboard.\n--\nentryCutClipboard :: EntryClass ed => ed -> IO ()\nentryCutClipboard = {#call editable_cut_clipboard#}.toEditable\n\n-- @method entryCopyClipboard@ Copy the selected characters to the Clipboard.\n--\nentryCopyClipboard :: EntryClass ed => ed -> IO ()\nentryCopyClipboard = {#call editable_copy_clipboard#}.toEditable\n\n-- @method entryPasteClipboard@ Paste the selected characters to the\n-- Clipboard.\n--\nentryPasteClipboard :: EntryClass ed => ed -> IO ()\nentryPasteClipboard = {#call editable_paste_clipboard#}.toEditable\n\n-- @method entryDeleteSelection@ Delete the current selection.\n--\nentryDeleteSelection :: EntryClass ed => ed -> IO ()\nentryDeleteSelection = {#call editable_delete_selection#}.toEditable\n\n-- @method entrySetPosition@ Set the cursor to a specific position.\n--\nentrySetPosition :: EntryClass ed => ed -> Int -> IO ()\nentrySetPosition ed pos = \n {#call editable_set_position#} (toEditable ed) (fromIntegral pos)\n\n-- @method entryGetPosition@ Get the current cursor position.\n--\nentryGetPosition :: EntryClass ed => ed -> IO Int\nentryGetPosition ed = liftM fromIntegral $\n {#call unsafe editable_get_position#} (toEditable ed)\n\n-- @method entrySetEditable@ Make an @ref type Entry@ insensitive.\n--\n-- * Called with False will make the text uneditable.\n--\nentrySetEditable :: EntryClass ed => ed -> Bool -> IO ()\nentrySetEditable ed isEditable = {#call editable_set_editable#}\n (toEditable ed) (fromBool isEditable)\n\n\n-- methods\n\n-- @constructor entryNew@ Create a new @ref type Entry@ widget.\n--\nentryNew :: IO Entry\nentryNew = makeNewObject mkEntry $ liftM castPtr $ {#call unsafe entry_new#}\n\n-- @method entrySetText@ Set the text of the @ref type Entry@ widget.\n--\nentrySetText :: EntryClass ec => ec -> String -> IO ()\nentrySetText ec str = withCString str $ {#call entry_set_text#} (toEntry ec)\n\n-- @method entryGetText@ Get the text of the @ref type Entry@ widget.\n--\nentryGetText :: EntryClass ec => ec -> IO String\nentryGetText ec = {#call entry_get_text#} (toEntry ec) >>= peekCString\n\n-- @method entryAppendText@ Append to the text of the @ref type Entry@ widget.\n--\nentryAppendText :: EntryClass ec => ec -> String -> IO ()\nentryAppendText ec str = \n withCString str $ {#call entry_append_text#} (toEntry ec)\n\n-- @method entryPrependText@ Prepend the text of the @ref type Entry@ widget.\n--\nentryPrependText :: EntryClass ec => ec -> String -> IO ()\nentryPrependText ec str = \n withCString str $ {#call entry_prepend_text#} (toEntry ec)\n\n-- @method entrySetVisibility@ Set whether to use password mode (display stars\n-- instead of the text).\n--\n-- * The replacement character can be changed with\n-- @ref method entrySetInvisibleChar@.\n--\nentrySetVisibility :: EntryClass ec => ec -> Bool -> IO ()\nentrySetVisibility ec visible =\n {#call entry_set_visibility#} (toEntry ec) (fromBool visible)\n\n-- @method entrySetInvisibleChar@ Set the replacement character for invisible\n-- text.\n--\nentrySetInvisibleChar :: EntryClass ec => ec -> Char -> IO ()\nentrySetInvisibleChar ec ch =\n {#call unsafe entry_set_invisible_char#} (toEntry ec) ((fromIntegral.ord) ch)\n\n-- @method entrySetMaxLength@ Sets a maximum length the text may grow to.\n--\n-- * A negative number resets the restriction.\n--\nentrySetMaxLength :: EntryClass ec => ec -> Int -> IO ()\nentrySetMaxLength ec max = \n {#call entry_set_max_length#} (toEntry ec) (fromIntegral max)\n\n-- @method entryGetActivatesDefault@ Query whether pressing return will\n-- activate the default widget.\n--\nentryGetActivatesDefault :: EntryClass ec => ec -> IO Bool\nentryGetActivatesDefault ec = liftM toBool $\n {#call unsafe entry_get_activates_default#} (toEntry ec)\n\n-- @method entrySetActivatesDefault@ Specify if pressing return will activate\n-- the default widget.\n--\n-- * This setting is useful in @ref arg Dialog@ boxes where enter should press\n-- the default button.\n--\nentrySetActivatesDefault :: EntryClass ec => ec -> Bool -> IO ()\nentrySetActivatesDefault ec setting = {#call entry_set_activates_default#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetHasFrame@ Query if the text @ref type Entry@ is displayed\n-- with a frame around it.\n--\nentryGetHasFrame :: EntryClass ec => ec -> IO Bool\nentryGetHasFrame ec = liftM toBool $\n {#call unsafe entry_get_has_frame#} (toEntry ec)\n\n-- @method entrySetHasFrame@ Specifies whehter the @ref type Entry@ should be\n-- in an etched-in frame.\n--\nentrySetHasFrame :: EntryClass ec => ec -> Bool -> IO ()\nentrySetHasFrame ec setting = {#call entry_set_has_frame#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetWidthChars@ Retrieve the number of characters the widget\n-- should ask for.\n--\nentryGetWidthChars :: EntryClass ec => ec -> IO Int\nentryGetWidthChars ec = liftM fromIntegral $ \n {#call unsafe entry_get_width_chars#} (toEntry ec)\n\n-- @method entrySetWidthChars@ Specifies how large the @ref type Entry@ should\n-- be in characters.\n--\n-- * This setting is only considered when the widget formulates its size\n-- request. Make sure that it is not mapped (shown) before you change this\n-- value.\n--\nentrySetWidthChars :: EntryClass ec => ec -> Int -> IO ()\nentrySetWidthChars ec setting = {#call entry_set_width_chars#}\n (toEntry ec) (fromIntegral setting)\n\n\n-- signals\n\n-- @signal connectToEntryActivate@ Emitted when the user presses return within\n-- the @ref arg Entry@ field.\n--\nonEntryActivate, afterEntryActivate :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryActivate = connect_NONE__NONE \"activate\" False\nafterEntryActivate = connect_NONE__NONE \"activate\" True\n\n-- @signal connectToEntryChanged@ Emitted when the settings of the\n-- @ref arg Entry@ widget changes.\n--\nonEntryChanged, afterEntryChanged :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryChanged = connect_NONE__NONE \"changed\" False\nafterEntryChanged = connect_NONE__NONE \"changed\" True\n\n-- @signal connectToCopyClipboard@ Emitted when the current selection has been\n-- copied to the clipboard.\n--\nonCopyClipboard, afterCopyClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCopyClipboard = connect_NONE__NONE \"copy_clipboard\" False\nafterCopyClipboard = connect_NONE__NONE \"copy_clipboard\" True\n\n-- @signal connectToCutClipboard@ Emitted when the current selection has been\n-- cut to the clipboard.\n--\nonCutClipboard, afterCutClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCutClipboard = connect_NONE__NONE \"cut_clipboard\" False\nafterCutClipboard = connect_NONE__NONE \"cut_clipboard\" True\n\n-- @signal connectToPasteClipboard@ Emitted when the current selection has\n-- been pasted from the clipboard.\n--\nonPasteClipboard, afterPasteClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonPasteClipboard = connect_NONE__NONE \"paste_clipboard\" False\nafterPasteClipboard = connect_NONE__NONE \"paste_clipboard\" True\n\n-- @signal connectToDeleteText@ Emitted when a piece of text is deleted from\n-- the @ref arg Entry@.\n--\nonDeleteText, afterDeleteText :: EntryClass ec => ec ->\n (Int -> Int -> IO ()) -> IO (ConnectId ec)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- @signal connectToInsertAtCursor@ Emitted when a piece of text is inserted\n-- at the cursor position.\n--\nonInsertAtCursor, afterInsertAtCursor :: EntryClass ec => ec ->\n (String -> IO ()) ->\n IO (ConnectId ec)\nonInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" False\nafterInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" True\n\n-- @signal connectToToggleOverwrite@ Emitted when the user changes from\n-- overwriting to inserting.\n--\nonToggleOverwrite, afterToggleOverwrite :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" False\nafterToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" True\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Entry@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/05\/24 09:43:24 $\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 lets the user enter a single line of text.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * A couple of signals are not bound because I could not figure out what\n-- they mean. Some of them do not seem to be emitted at all.\n--\nmodule Entry(\n Entry,\n EntryClass,\n castToEntry,\n entrySelectRegion,\n entryGetSelectionBounds,\n entryInsertText,\n entryDeleteText,\n entryGetChars,\n entryCutClipboard,\n entryCopyClipboard,\n entryPasteClipboard,\n entryDeleteSelection,\n entrySetEditable,\n entryNew,\n entrySetText,\n entryAppendText,\n entryPrependText,\n entrySetVisibility,\n entrySetInvisibleChar,\n entrySetMaxLength,\n entryGetActivatesDefault,\n entrySetActivatesDefault,\n entryGetHasFrame,\n entrySetHasFrame,\n entryGetWidthChars,\n entrySetWidthChars,\n onEntryActivate,\n afterEntryActivate,\n onEntryChanged,\n afterEntryChanged,\n onCopyClipboard,\n afterCopyClipboard,\n onCutClipboard,\n afterCutClipboard,\n onPasteClipboard,\n afterPasteClipboard,\n onDeleteText,\n afterDeleteText,\n onInsertAtCursor,\n afterInsertAtCursor,\n onToggleOverwrite,\n afterToggleOverwrite\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Char\t(ord)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods originating in the Editable base class which is not really a base\n-- class of in the Gtk Hierarchy (it is non-existant). I renamed\n{#pointer *Editable foreign#}\n\ntoEditable :: EntryClass ed => ed -> Editable\ntoEditable = castForeignPtr.unEntry.toEntry\n\n-- @method entrySelectRegion@ Select a span of text.\n--\n-- * A negative @ref arg end@ position will make the selection extend to the\n-- end of the buffer.\n--\n-- * Calling this function with @ref arg start@=1 and @ref arg end@=4 it will\n-- mark \"ask\" in the string \"Haskell\". (FIXME: verify)\n--\nentrySelectRegion :: EntryClass ed => ed -> Int -> Int -> IO ()\nentrySelectRegion ed start end = {#call editable_select_region#}\n (toEditable ed) (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetSelectionBounds@ Get the span of the current selection.\n--\n-- * The returned tuple is not ordered. The second index represents the\n-- position of the cursor. The first index is the other end of the\n-- selection. If both numbers are equal there is in fact no selection.\n--\nentryGetSelectionBounds :: EntryClass ed => ed -> IO (Int,Int)\nentryGetSelectionBounds ed = alloca $ \\startPtr -> alloca $ \\endPtr -> do\n {#call unsafe editable_get_selection_bounds#} (toEditable ed) startPtr endPtr\n start <- liftM fromIntegral $ peek startPtr\n end\t<- liftM fromIntegral $ peek endPtr\n return (start,end)\n\n-- @method entryInsertText@ Insert new text at the specified position.\n--\n-- * If the position is invalid the text will be inserted at the end of the\n-- buffer. The returned value reflects the actual insertion point.\n--\nentryInsertText :: EntryClass ed => ed -> String -> Int -> IO Int\nentryInsertText ed str pos = withObject (fromIntegral pos) $ \\posPtr ->\n withCStringLen str $ \\(strPtr,len) -> do\n {#call editable_insert_text#} (toEditable ed) strPtr (fromIntegral len) \n posPtr\n liftM fromIntegral $ peek posPtr\n\n-- @method entryDeleteText@ Delete a given range of text.\n--\n-- * If the @ref arg end@ position is invalid, it is set to the lenght of the\n-- buffer.\n--\n-- * @ref arg start@ is restricted to 0..@end.\n--\nentryDeleteText :: EntryClass ed => ed -> Int -> Int -> IO ()\nentryDeleteText ed start end = {#call editable_delete_text#} (toEditable ed)\n (fromIntegral start) (fromIntegral end)\n\n-- @method entryGetChars@ Retrieve a range of characters.\n--\n-- * Set @ref arg end@ to a negative value to reach the end of the buffer.\n--\nentryGetChars :: EntryClass ed => ed -> Int -> Int -> IO String\nentryGetChars ed start end = do\n strPtr <- {#call unsafe editable_get_chars#} (toEditable ed) \n (fromIntegral start) (fromIntegral end)\n str <- peekCString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n-- @method entryCutClipboard@ Cut the selected characters to the Clipboard.\n--\nentryCutClipboard :: EntryClass ed => ed -> IO ()\nentryCutClipboard = {#call editable_cut_clipboard#}.toEditable\n\n-- @method entryCopyClipboard@ Copy the selected characters to the Clipboard.\n--\nentryCopyClipboard :: EntryClass ed => ed -> IO ()\nentryCopyClipboard = {#call editable_copy_clipboard#}.toEditable\n\n-- @method entryPasteClipboard@ Paste the selected characters to the\n-- Clipboard.\n--\nentryPasteClipboard :: EntryClass ed => ed -> IO ()\nentryPasteClipboard = {#call editable_paste_clipboard#}.toEditable\n\n-- @method entryDeleteSelection@ Delete the current selection.\n--\nentryDeleteSelection :: EntryClass ed => ed -> IO ()\nentryDeleteSelection = {#call editable_delete_selection#}.toEditable\n\n-- @method entrySetPosition@ Set the cursor to a specific position.\n--\nentrySetPosition :: EntryClass ed => ed -> Int -> IO ()\nentrySetPosition ed pos = \n {#call editable_set_position#} (toEditable ed) (fromIntegral pos)\n\n-- @method entryGetPosition@ Get the current cursor position.\n--\nentryGetPosition :: EntryClass ed => ed -> IO Int\nentryGetPosition ed = liftM fromIntegral $\n {#call unsafe editable_get_position#} (toEditable ed)\n\n-- @method entrySetEditable@ Make an @ref type Entry@ insensitive.\n--\n-- * Called with False will make the text uneditable.\n--\nentrySetEditable :: EntryClass ed => ed -> Bool -> IO ()\nentrySetEditable ed isEditable = {#call editable_set_editable#}\n (toEditable ed) (fromBool isEditable)\n\n\n-- methods\n\n-- @constructor entryNew@ Create a new @ref type Entry@ widget.\n--\nentryNew :: IO Entry\nentryNew = makeNewObject mkEntry $ liftM castPtr $ {#call unsafe entry_new#}\n\n\n\n-- @method entrySetText@ Set the text of the @ref type Entry@ widget.\n--\nentrySetText :: EntryClass ec => ec -> String -> IO ()\nentrySetText ec str = withCString str $ {#call entry_set_text#} (toEntry ec)\n\n-- @method entryAppendText@ Append to the text of the @ref type Entry@ widget.\n--\nentryAppendText :: EntryClass ec => ec -> String -> IO ()\nentryAppendText ec str = \n withCString str $ {#call entry_append_text#} (toEntry ec)\n\n-- @method entryPrependText@ Prepend the text of the @ref type Entry@ widget.\n--\nentryPrependText :: EntryClass ec => ec -> String -> IO ()\nentryPrependText ec str = \n withCString str $ {#call entry_prepend_text#} (toEntry ec)\n\n-- @method entrySetVisibility@ Set whether to use password mode (display stars\n-- instead of the text).\n--\n-- * The replacement character can be changed with\n-- @ref method entrySetInvisibleChar@.\n--\nentrySetVisibility :: EntryClass ec => ec -> Bool -> IO ()\nentrySetVisibility ec visible =\n {#call entry_set_visibility#} (toEntry ec) (fromBool visible)\n\n-- @method entrySetInvisibleChar@ Set the replacement character for invisible\n-- text.\n--\nentrySetInvisibleChar :: EntryClass ec => ec -> Char -> IO ()\nentrySetInvisibleChar ec ch =\n {#call unsafe entry_set_invisible_char#} (toEntry ec) ((fromIntegral.ord) ch)\n\n-- @method entrySetMaxLength@ Sets a maximum length the text may grow to.\n--\n-- * A negative number resets the restriction.\n--\nentrySetMaxLength :: EntryClass ec => ec -> Int -> IO ()\nentrySetMaxLength ec max = \n {#call entry_set_max_length#} (toEntry ec) (fromIntegral max)\n\n-- @method entryGetActivatesDefault@ Query whether pressing return will\n-- activate the default widget.\n--\nentryGetActivatesDefault :: EntryClass ec => ec -> IO Bool\nentryGetActivatesDefault ec = liftM toBool $\n {#call unsafe entry_get_activates_default#} (toEntry ec)\n\n-- @method entrySetActivatesDefault@ Specify if pressing return will activate\n-- the default widget.\n--\n-- * This setting is useful in @ref arg Dialog@ boxes where enter should press\n-- the default button.\n--\nentrySetActivatesDefault :: EntryClass ec => ec -> Bool -> IO ()\nentrySetActivatesDefault ec setting = {#call entry_set_activates_default#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetHasFrame@ Query if the text @ref type Entry@ is displayed\n-- with a frame around it.\n--\nentryGetHasFrame :: EntryClass ec => ec -> IO Bool\nentryGetHasFrame ec = liftM toBool $\n {#call unsafe entry_get_has_frame#} (toEntry ec)\n\n-- @method entrySetHasFrame@ Specifies whehter the @ref type Entry@ should be\n-- in an etched-in frame.\n--\nentrySetHasFrame :: EntryClass ec => ec -> Bool -> IO ()\nentrySetHasFrame ec setting = {#call entry_set_has_frame#}\n (toEntry ec) (fromBool setting)\n\n-- @method entryGetWidthChars@ Retrieve the number of characters the widget\n-- should ask for.\n--\nentryGetWidthChars :: EntryClass ec => ec -> IO Int\nentryGetWidthChars ec = liftM fromIntegral $ \n {#call unsafe entry_get_width_chars#} (toEntry ec)\n\n-- @method entrySetWidthChars@ Specifies how large the @ref type Entry@ should\n-- be in characters.\n--\n-- * This setting is only considered when the widget formulates its size\n-- request. Make sure that it is not mapped (shown) before you change this\n-- value.\n--\nentrySetWidthChars :: EntryClass ec => ec -> Int -> IO ()\nentrySetWidthChars ec setting = {#call entry_set_width_chars#}\n (toEntry ec) (fromIntegral setting)\n\n\n-- signals\n\n-- @signal connectToEntryActivate@ Emitted when the user presses return within\n-- the @ref arg Entry@ field.\n--\nonEntryActivate, afterEntryActivate :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryActivate = connect_NONE__NONE \"activate\" False\nafterEntryActivate = connect_NONE__NONE \"activate\" True\n\n-- @signal connectToEntryChanged@ Emitted when the settings of the\n-- @ref arg Entry@ widget changes.\n--\nonEntryChanged, afterEntryChanged :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonEntryChanged = connect_NONE__NONE \"changed\" False\nafterEntryChanged = connect_NONE__NONE \"changed\" True\n\n-- @signal connectToCopyClipboard@ Emitted when the current selection has been\n-- copied to the clipboard.\n--\nonCopyClipboard, afterCopyClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCopyClipboard = connect_NONE__NONE \"copy_clipboard\" False\nafterCopyClipboard = connect_NONE__NONE \"copy_clipboard\" True\n\n-- @signal connectToCutClipboard@ Emitted when the current selection has been\n-- cut to the clipboard.\n--\nonCutClipboard, afterCutClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonCutClipboard = connect_NONE__NONE \"cut_clipboard\" False\nafterCutClipboard = connect_NONE__NONE \"cut_clipboard\" True\n\n-- @signal connectToPasteClipboard@ Emitted when the current selection has\n-- been pasted from the clipboard.\n--\nonPasteClipboard, afterPasteClipboard :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonPasteClipboard = connect_NONE__NONE \"paste_clipboard\" False\nafterPasteClipboard = connect_NONE__NONE \"paste_clipboard\" True\n\n-- @signal connectToDeleteText@ Emitted when a piece of text is deleted from\n-- the @ref arg Entry@.\n--\nonDeleteText, afterDeleteText :: EntryClass ec => ec ->\n (Int -> Int -> IO ()) -> IO (ConnectId ec)\nonDeleteText = connect_INT_INT__NONE \"delete_text\" False\nafterDeleteText = connect_INT_INT__NONE \"delete_text\" True\n\n-- @signal connectToInsertAtCursor@ Emitted when a piece of text is inserted\n-- at the cursor position.\n--\nonInsertAtCursor, afterInsertAtCursor :: EntryClass ec => ec ->\n (String -> IO ()) ->\n IO (ConnectId ec)\nonInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" False\nafterInsertAtCursor = connect_STRING__NONE \"insert_at_cursor\" True\n\n-- @signal connectToToggleOverwrite@ Emitted when the user changes from\n-- overwriting to inserting.\n--\nonToggleOverwrite, afterToggleOverwrite :: EntryClass ec => ec -> IO () ->\n IO (ConnectId ec)\nonToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" False\nafterToggleOverwrite = connect_NONE__NONE \"toggle_overwrite\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0aa70765fa8d9e2271cbe35e0453e2be62b57b22","subject":"Fix documentation and some types in Window. Remove key-binding signals.","message":"Fix documentation and some types in Window. Remove key-binding signals.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\n{#import Graphics.UI.Gtk.Gdk.Keys#} (KeyVal)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this 'Window'. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO (Maybe Widget)\nwindowGetDefaultWidget self = \n maybeNull (makeNewObject mkWidget) $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- Enter in a dialog (for example). This function sets or unsets the default\n-- widget for a Window about. When setting (rather than unsetting) the\n-- default widget it's generally easier to call widgetGrabDefault on the\n-- widget. Before making a widget the default widget, you must set the\n-- 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n#endif\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ returns @(left, top, right, bottom)@. @left@ is the\n -- width of the frame at the left, @top@ is the height of the frame at the top, @right@\n -- is the width of the frame at the right, @bottom@ is the height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Maybe Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n (Pixbuf nullForeignPtr)\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO (Maybe Pixbuf) -- ^ returns icon for window, or @Nothing@ if none was set\nwindowGetIcon self =\n maybeNull (makeNewGObject mkPixbuf) $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self (Maybe Pixbuf)\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame-event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys-changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set-focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set-focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set-focus\" True\n\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n activateDefault,\n activateFocus,\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> Int -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> Int -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> Int -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this GtkWindow. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO Widget\nwindowGetDefaultWidget self = \n makeNewObject mkWidget $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- | Enter in a dialog (for example). This function sets or unsets the default\n-- | widget for a Window about. When setting (rather than unsetting) the\n-- | default widget it's generally easier to call widgetGrabDefault on the\n-- | widget. Before making a widget the default widget, you must set the\n-- | 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the \\\"window_state_event\\\" signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the \\\"window_state_event\\\" signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling gtk_window_show().\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ return @(left, top, right, bottom)@ is location to store size frame. @left@ is\n -- width of the frame at the left, @top@ is height of the frame at the top, @right@\n -- is width of the frame at the right, @bottom@ is height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self icon =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO Pixbuf -- ^ returns icon for window\nwindowGetIcon self =\n makeNewGObject mkPixbuf $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a GtkWindow. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self Pixbuf\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n-- | The 'activateDefault' signal is a keybinding signal which gets emitted when the user activates the default widget of window.\nactivateDefault :: WindowClass self => Signal self (IO ())\nactivateDefault = Signal (connect_NONE__NONE \"activate_default\")\n\n-- | The 'activateDefault' signal is a keybinding signal which gets emitted when the user activates the currently focused widget of window.\nactivateFocus :: WindowClass self => Signal self (IO ())\nactivateFocus = Signal (connect_NONE__NONE \"activate_focus\")\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame_event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys_changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set_focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set_focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set_focus\" True\n\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a581a8f5edd8b87d61be06f4bab530c1224e61fe","subject":"Document the Matrix representation","message":"Document the Matrix representation\n","repos":"gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"60837f45939b1ec2c27e9c499a1df07e5c369d02","subject":"MINOR: Improve scEnDeCryptInplace Implementation","message":"MINOR: Improve scEnDeCryptInplace Implementation\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 let !newContext = scCopyContext ctx\n in unsafePerformIO $\n BSU.unsafeUseAsCStringLen input $ \\(inputBytes, inputLen) ->\n withShonkyCryptContext newContext $ \\newContext' ->\n do\n outBuffer <- mallocBytes inputLen\n f newContext' inputBytes outBuffer (fromIntegral inputLen)\n out <- unsafePackMallocCStringLen (outBuffer, inputLen)\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":"0ae74685372d5e9ee9d064bf5d3f5986ebc7715a","subject":"Add CPP language directive to Transforms.chs","message":"Add CPP language directive to Transforms.chs\n\nTo handle Transform.chs's OpenCV24 ifdefs\ncorrectly, run it with CPP pre-processor\nbefore compiling.\n","repos":"aleator\/CV,aleator\/CV,BeautifulDestinations\/CV,TomMD\/CV","old_file":"CV\/Transforms.chs","new_file":"CV\/Transforms.chs","new_contents":"{-#LANGUAGE CPP, 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 as I \nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\nimport qualified CV.Matrix as M\nimport CV.Matrix (Matrix,withMatPtr)\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 cl <- I.create (getSize 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 target <- I.create (getSize 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 <- I.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 <- I.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\nperspectiveTransform' :: (CreateImage (Image c d)) => Matrix Float -> Image c d -> (Int,Int)-> Image c d\nperspectiveTransform' mat img size\n = unsafePerformIO $ do\n r <- create size\n withImage img $ \\c_img ->\n withMatPtr mat $ \\c_mat ->\n withImage r $ \\c_r -> {#call wrapWarpPerspective#} (castPtr c_img) (castPtr c_r) (castPtr c_mat)\n return r\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#c\nenum HomographyMethod {\n Default = 0,\n Ransac = CV_RANSAC,\n LMeds = CV_LMEDS\n };\n#endc\n{#enum HomographyMethod {}#}\n\ngetHomography' :: Matrix Float -> Matrix Float -> HomographyMethod -> Float -> Matrix Float\ngetHomography' srcPts dstPts method ransacThreshold = \n unsafePerformIO $ do\n hmg <- M.create (3,3) :: IO (Matrix Float)\n withMatPtr srcPts $\u00a0\\c_src ->\n withMatPtr dstPts $\u00a0\\c_dst ->\n withMatPtr hmg $\u00a0\\c_hmg -> do\n {#call cvFindHomography#} \n (castPtr c_src) \n (castPtr c_dst) \n (castPtr c_hmg)\n (fromIntegral $ fromEnum method)\n (realToFrac ransacThreshold)\n nullPtr\n return hmg\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 <- I.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 <- I.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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- 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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n CCOMP = CV_DIST_LABEL_CCOMP\n ,PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\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 <- I.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#ifdef OpenCV24\n (fromIntegral . fromEnum $ CCOMP)\n#endif\n\n return result\n\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 as I \nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\nimport qualified CV.Matrix as M\nimport CV.Matrix (Matrix,withMatPtr)\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 cl <- I.create (getSize 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 target <- I.create (getSize 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 <- I.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 <- I.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\nperspectiveTransform' :: (CreateImage (Image c d)) => Matrix Float -> Image c d -> (Int,Int)-> Image c d\nperspectiveTransform' mat img size\n = unsafePerformIO $ do\n r <- create size\n withImage img $ \\c_img ->\n withMatPtr mat $ \\c_mat ->\n withImage r $ \\c_r -> {#call wrapWarpPerspective#} (castPtr c_img) (castPtr c_r) (castPtr c_mat)\n return r\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#c\nenum HomographyMethod {\n Default = 0,\n Ransac = CV_RANSAC,\n LMeds = CV_LMEDS\n };\n#endc\n{#enum HomographyMethod {}#}\n\ngetHomography' :: Matrix Float -> Matrix Float -> HomographyMethod -> Float -> Matrix Float\ngetHomography' srcPts dstPts method ransacThreshold = \n unsafePerformIO $ do\n hmg <- M.create (3,3) :: IO (Matrix Float)\n withMatPtr srcPts $\u00a0\\c_src ->\n withMatPtr dstPts $\u00a0\\c_dst ->\n withMatPtr hmg $\u00a0\\c_hmg -> do\n {#call cvFindHomography#} \n (castPtr c_src) \n (castPtr c_dst) \n (castPtr c_hmg)\n (fromIntegral $ fromEnum method)\n (realToFrac ransacThreshold)\n nullPtr\n return hmg\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 <- I.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 <- I.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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- 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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n CCOMP = CV_DIST_LABEL_CCOMP\n ,PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\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 <- I.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#ifdef OpenCV24\n (fromIntegral . fromEnum $ CCOMP)\n#endif\n\n return result\n\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":"e3e87036f46bafab0057f842bf081f35511dc1a5","subject":"Switch to a soft close of the connection by default.","message":"Switch to a soft close of the connection by default.\n\nThis better supports resource pool usage, where closing the client does not\ncause all pending asynchronous requests to return HyperclientGarbage\nstatuses.\n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Client.chs","new_file":"src\/Database\/HyperDex\/Internal\/Client.chs","new_contents":"{-# LANGUAGE ViewPatterns #-}\n\nmodule Database.HyperDex.Internal.Client \n ( Hyperclient, Client\n , ConnectInfo (..)\n , defaultConnectInfo\n , ConnectOptions (..)\n , defaultConnectOptions\n , BackoffMethod (..)\n , Handle\n , Result, AsyncResult, AsyncResultHandle, SearchStream (..)\n , connect, close, forceClose\n , loopClient, loopClientUntil\n , withClient, withClientImmediate\n , withClientStream\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Data.ByteString (ByteString)\n\n{# import Database.HyperDex.Internal.ReturnCode #}\nimport Database.HyperDex.Internal.Util\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\nimport Control.Concurrent (yield, threadDelay)\nimport Control.Concurrent.MVar\n\nimport Data.Text.Encoding (encodeUtf8)\nimport qualified Data.Text as Text (pack) \n\nimport Data.Default\n\n#include \"hyperclient.h\"\n\n{#pointer *hyperclient as Hyperclient #}\n\n-- | Parameters for connecting to a HyperDex cluster.\ndata ConnectInfo =\n ConnectInfo\n { connectHost :: String\n , connectPort :: Word16\n , connectOptions :: ConnectOptions\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectInfo where\n def = \n ConnectInfo\n { connectHost = \"127.0.0.1\"\n , connectPort = 1982\n , connectOptions = def\n }\n\ndefaultConnectInfo :: ConnectInfo\ndefaultConnectInfo = def\n\n-- | Additional options for connecting and managing the connection\n-- to a HyperDex cluster.\ndata ConnectOptions =\n ConnectOptions\n { connectionBackoff :: BackoffMethod\n , connectionBackoffCap :: Maybe Int\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectOptions where\n def =\n ConnectOptions\n { connectionBackoff = BackoffYield -- 10 * 2^n\n , connectionBackoffCap = Just 50000 -- 0.05 seconds.\n }\n\n-- | Sane defaults for HyperDex connection options.\ndefaultConnectOptions :: ConnectOptions\ndefaultConnectOptions = def\n\n-- | A connectionBackoff method controls how frequently the client polls internally.\n-- \n-- This is provided to allow fine-tuning performance. Do note that \n-- this does not affect any method the HyperClient C library uses to poll\n-- its connection to a HyperDex cluster.\n--\n-- All integer values are in microseconds.\ndata BackoffMethod\n -- | No delay is used except the thread is yielded.\n = BackoffYield\n -- | Delay a constant number of microseconds each inter.\n | BackoffConstant Int\n -- | Delay with an initial number of microseconds, increasing linearly by the second value. \n | BackoffLinear Int Int\n -- | Delay with an initial number of microseconds, increasing exponentially by the second value. \n | BackoffExponential Int Double\n deriving (Eq, Read, Show)\n\n-- | A callback used to perform work when the Hyperclient loop indicates an\n-- operation has been completed.\n--\n-- A 'Nothing' value indicates that no further work is necessary, and a 'Just' value\n-- will store a new Handle and HandleCallback.\nnewtype HandleCallback = HandleCallback (Maybe ReturnCode -> IO (Maybe (Handle, HandleCallback)))\n\n-- | The core data type managing access to a 'Hyperclient' object and all\n-- currently running asynchronous operations.\n--\n-- The 'MVar' is used as a lock to control access to the 'Hyperclient' and\n-- a map of open handles and continuations, or callbacks, that must be executed\n-- to complete operations. A 'HandleCallback' may yield Nothing or a new 'Handle'\n-- and 'HandleCallback' to be stored in the map.\ntype HyperclientWrapper = MVar (Maybe Hyperclient, Map Handle HandleCallback)\n\ndata ClientData =\n ClientData\n { hyperclientWrapper :: HyperclientWrapper\n , connectionInfo :: ConnectInfo\n }\n\n-- | A connection to a HyperDex cluster.\nnewtype Client = Client { unClientData :: ClientData } \n\n-- | Internal method for returning the (MVar) wrapped connection. \ngetClient :: Client -> HyperclientWrapper\ngetClient = hyperclientWrapper . unClientData\n\n-- | Get the connection info used for a 'Client'.\ngetConnectInfo :: Client -> ConnectInfo\ngetConnectInfo = connectionInfo . unClientData\n\n-- | Get the connection options for a 'Client'.\ngetConnectOptions :: Client -> ConnectOptions\ngetConnectOptions = connectOptions . getConnectInfo\n\n-- | Return value from hyperclient operations.\n--\n-- Per the specification, it's guaranteed to be a unique integer for\n-- each outstanding operation using a given HyperClient. In practice\n-- it is monotonically increasing while operations are outstanding,\n-- lower values are used first, and negative values represent an\n-- error.\ntype Handle = {# type int64_t #}\n\n-- | A return value from HyperDex.\ntype Result a = IO (Either ReturnCode a)\n\n-- | A return value used internally by HyperClient operations.\n--\n-- Internally the wrappers to the HyperDex library will return\n-- a computation that yields a 'Handle' referring to that request\n-- and a continuation that will force the request to return an \n-- error in the form of a ReturnCode or a result.\n--\n-- The result of forcing the result is undefined.\n-- The HyperClient and its workings are not party to the MVar locking\n-- mechanism, and the ReturnCode and\/or return value may be in the\n-- process of being modified when the computation is forced.\n--\n-- Consequently, the only safe way to use this is with a wrapper such\n-- as 'withClient', which only allows the continuation to be run after\n-- the HyperClient has returned the corresponding Handle or after the\n-- HyperClient has been destroyed.\ntype AsyncResultHandle a = IO (Handle, Result a)\n\n-- | A return value used internally by HyperClient operations.\n--\n-- This is the same as 'AsyncResultHandle' except it gives the callback\n-- the result of the loop operation that yields the returned 'Handle'.\ntype StreamResultHandle a = IO (Handle, Maybe ReturnCode -> Result a)\n\n-- | A return value from HyperDex in an asynchronous wrapper.\n--\n-- The full type is an IO (IO (Either ReturnCode a)). Evaluating\n-- the result of an asynchronous call, such as the default get and\n-- put operations starts the request to the HyperDex cluster. Evaluating\n-- the result of that evaluation will poll internally, using the \n-- connection's 'BackoffMethod' until the result is available.\n--\n-- This API may be deprecated in favor of exclusively using MVars in\n-- a future version.\ntype AsyncResult a = IO (Result a)\n\nnewtype SearchStream a = SearchStream (a, Result (SearchStream a))\n\n-- | Connect to a HyperDex cluster.\nconnect :: ConnectInfo -> IO Client\nconnect info = do\n hyperclient <- hyperclientCreate (encodeUtf8 . Text.pack . connectHost $ info) (connectPort info)\n clientData <- newMVar (Just hyperclient, Map.empty)\n return $\n Client\n $ ClientData\n { hyperclientWrapper = clientData \n , connectionInfo = info\n }\n\n-- | Close a connection and terminate any outstanding asynchronous\n-- requests.\n--\n-- \/Note:\/ This does force all asynchronous requests to complete\n-- immediately. Any outstanding requests at the time the 'Client'\n-- is closed ought to return a 'ReturnCode' indicating the failure\n-- condition, but the behavior is ultimately undefined. Any pending\n-- requests should be disregarded. \nforceClose :: Client -> IO ()\nforceClose (getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> error \"HyperDex client error - cannot close a client connection twice.\"\n (Just hc, handles) -> do\n hyperclientDestroy hc\n mapM_ (\\(HandleCallback cont) -> cont Nothing) $ Map.elems handles \n putMVar c (Nothing, Map.empty)\n\n-- | Wait for graceful termination of all outstanding requests and\n-- then close the connection.\n--\n-- \/Note:\/ If it is necessary to have this operation complete quickly\n-- and outstanding requests are not needed, then use 'forceClose'.\nclose :: Client -> IO ()\nclose client@(getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> error \"HyperDex client error - cannot close a client connection twice.\"\n (Just hc, handles) -> do\n case Map.null handles of\n True -> do\n hyperclientDestroy hc\n putMVar c (Nothing, Map.empty)\n False -> do\n -- Have to put it back in order to run loopClient\n (_, newHandles) <- handleLoop hc handles\n putMVar c (Just hc, newHandles)\n close client\n\ndoExponentialBackoff :: Int -> Double -> (Int, BackoffMethod)\ndoExponentialBackoff b x = \n let result = ceiling (fromIntegral b ** x) in\n (result, BackoffExponential result x)\n{-# INLINE doExponentialBackoff #-}\n\ncappedBackoff :: Int -> Maybe Int -> (Int, Bool)\ncappedBackoff n Nothing = (n, False)\ncappedBackoff n (Just c) | n < c = (n, False)\n | otherwise = (c, True)\n{-# INLINE cappedBackoff #-}\n\nperformBackoff :: BackoffMethod -> Maybe Int -> IO (BackoffMethod)\nperformBackoff method cap = do\n let (delay, newBackoff) = case method of\n BackoffYield -> (0, method)\n BackoffConstant n -> (n, method)\n BackoffLinear m b -> (m, BackoffLinear (m+b) b)\n BackoffExponential b x -> doExponentialBackoff b x\n (backoff, capped) = cappedBackoff delay cap\n let doDelay = case backoff of\n 0 -> yield\n n -> threadDelay n\n nextDelay = case capped of\n True -> BackoffConstant backoff\n False -> newBackoff\n doDelay >> return nextDelay\n{-# INLINE performBackoff #-}\n\n-- | Runs a single iteration of hyperclient_loop, returning whether\n-- or not a handle was completed and a new set of callbacks.\n--\n-- This function does not use locking around the client.\nhandleLoop :: Hyperclient -> Map Handle HandleCallback -> IO (Maybe Handle, Map Handle HandleCallback)\nhandleLoop hc handles = do\n -- TODO: Examine returnCode for things that might matter.\n (handle, returnCode) <- hyperclientLoop hc 0\n case returnCode of\n HyperclientSuccess -> do\n let clearedMap = Map.delete handle handles\n resultMap <- do\n case Map.lookup handle handles of\n Just (HandleCallback entry) -> do\n cont <- entry $ Just returnCode\n case cont of\n Nothing -> return clearedMap\n Just (h, e) -> return $ Map.insert h e clearedMap\n Nothing -> return clearedMap\n return $ (Just handle, resultMap)\n HyperclientTimeout -> do\n handleLoop hc handles\n HyperclientNonepending -> do\n mapM_ (\\(HandleCallback cont) -> cont Nothing) $ Map.elems handles\n return $ (Just handle, Map.empty)\n _ -> do\n handleLoop hc handles\n\n{-# INLINE handleLoop #-}\n\n-- | Runs hyperclient_loop exactly once, setting the appropriate MVar.\nloopClient :: Client -> IO (Maybe Handle)\nloopClient (getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> error \"HyperDex client error - client has been closed.\"\n (Just hc, handles) -> do\n (maybeHandle, newHandles) <- handleLoop hc handles\n putMVar c (Just hc, newHandles)\n return maybeHandle\n{-# INLINE loopClient #-}\n\n-- | Run hyperclient_loop at most N times or forever until a handle\n-- is returned.\nloopClientUntil :: Client -> Handle -> MVar a -> BackoffMethod -> Maybe Int -> IO (Bool)\nloopClientUntil _ _ _ _ (Just 0) = return False\n\nloopClientUntil client h v back (Just n) = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential connectionBackoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return True\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> do\n back' <- performBackoff back (connectionBackoffCap . getConnectOptions $ client)\n loopClientUntil client h v back' (Just $ n - 1)\n False -> return True\n\nloopClientUntil client h v back Nothing = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential connectionBackoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return False\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> do \n back' <- performBackoff back (connectionBackoffCap . getConnectOptions $ client)\n loopClientUntil client h v back' Nothing\n False -> return True\n{-# INLINE loopClientUntil #-}\n\n-- | Wrap a HyperClient request and wait until completion or failure.\nwithClientImmediate :: Client -> (Hyperclient -> IO a) -> IO a\nwithClientImmediate (getClient -> c) f =\n withMVar c $ \\value -> do\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, _) -> f hc\n{-# INLINE withClientImmediate #-}\n\n-- | Wrap a Hyperclient request.\nwithClient :: Client -> (Hyperclient -> AsyncResultHandle a) -> AsyncResult a\nwithClient client@(getClient -> c) f = do\n value <- takeMVar c\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, handles) -> do\n (h, cont) <- f hc\n case h > 0 of\n True -> do\n v <- newEmptyMVar :: IO (MVar (Either ReturnCode a))\n let wrappedCallback = HandleCallback $ const $ do\n returnValue <- cont\n putMVar v returnValue\n return Nothing\n putMVar c (Just hc, Map.insert h wrappedCallback handles)\n return $ do\n success <- loopClientUntil client h v (connectionBackoff . getConnectOptions $ client) Nothing \n case success of\n True -> takeMVar v\n False -> return $ Left HyperclientPollfailed\n False -> do\n putMVar c (Just hc, handles)\n returnValue <- cont\n -- A HyperclientInterrupted return code indicates that there was a signal\n -- received by the client that prevented the call from completing, thus\n -- the request should be transparently retried.\n case returnValue of\n Left HyperclientInterrupted -> withClient client f\n _ -> return . return $ returnValue\n{-# INLINE withClient #-}\n\n-- | Wrap a Hyperclient request that returns a search stream.\nwithClientStream :: Client -> (Hyperclient -> StreamResultHandle a) -> AsyncResult (SearchStream a)\nwithClientStream client@(getClient -> c) f = do\n value <- takeMVar c\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, handles) -> do\n (h, cont) <- f hc\n case h > 0 of\n True -> do\n v <- newEmptyMVar :: IO (MVar (Either ReturnCode (SearchStream a)))\n let wrappedCallback = HandleCallback $ \\code -> do\n returnValue <- cont code\n (result, callback) <- wrapSearchStream returnValue client h cont\n putMVar v $ result\n return $ Just (h, callback)\n putMVar c (Just hc, Map.insert h wrappedCallback handles)\n return $ do\n success <- loopClientUntil client h v (connectionBackoff . getConnectOptions $ client) Nothing \n case success of\n True -> takeMVar v\n False -> return $ Left HyperclientPollfailed\n False -> do\n putMVar c (Just hc, handles)\n returnValue <- cont Nothing\n case returnValue of\n Left HyperclientInterrupted -> withClientStream client f\n _ -> do\n (result, _) <- wrapSearchStream returnValue client h cont\n return . return $ result\n{-# INLINE withClientStream #-}\n\nwrapSearchStream :: Either ReturnCode a -> Client -> Handle -> (Maybe ReturnCode -> Result a) -> IO (Either ReturnCode (SearchStream a), HandleCallback)\nwrapSearchStream (Left e) _ _ _ = return $ (Left e, HandleCallback $ const $ return Nothing)\nwrapSearchStream (Right a) client h cont = do\n v <- newEmptyMVar\n let wrappedCallback = HandleCallback $ \\code -> do\n returnValue <- cont code\n (result, callback) <- wrapSearchStream returnValue client h cont\n putMVar v $ result\n return $ Just (h, callback)\n let cont' = do\n success <- loopClientUntil client h v (connectionBackoff . getConnectOptions $ client) Nothing\n case success of\n True -> takeMVar v\n -- TODO: Return actual ReturnCode\n False -> return $ Left HyperclientPollfailed\n return $ (return $ SearchStream (a, cont'), wrappedCallback)\n{-# INLINE wrapSearchStream #-}\n\n-- | C wrapper for hyperclient_create. Creates a HyperClient given a host\n-- and a port.\n--\n-- C definition:\n-- \n-- > struct hyperclient*\n-- > hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: ByteString -> Word16 -> IO Hyperclient\nhyperclientCreate h port = withCBString h $ \\host ->\n wrapHyperCall $ {# call hyperclient_create #} host (fromIntegral port)\n\n-- | C wrapper for hyperclient_destroy. Destroys a HyperClient.\n--\n-- \/Note:\/ This does not ensure resources are freed. Any memory \n-- allocated as staging for incomplete requests will not be returned.\n--\n-- C definition:\n-- \n-- > void\n-- > hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: Hyperclient -> IO ()\nhyperclientDestroy client = wrapHyperCall $ \n {# call hyperclient_destroy #} client\n\n-- | C wrapper for hyperclient_loop. Waits up to some number of\n-- milliseconds for a result before returning.\n--\n-- A negative 'Handle' return value indicates a failure condition\n-- or timeout, a positive value indicates completion of an asynchronous\n-- request.\n--\n-- C definition:\n--\n-- > int64_t\n-- > hyperclient_loop(struct hyperclient* client, int timeout,\n-- > enum hyperclient_returncode* status);\nhyperclientLoop :: Hyperclient -> Int -> IO (Handle, ReturnCode)\nhyperclientLoop client timeout =\n alloca $ \\returnCodePtr -> do\n handle <- wrapHyperCall $ {# call hyperclient_loop #} client (fromIntegral timeout) returnCodePtr\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n return (handle, returnCode)\n{-# INLINE hyperclientLoop #-}\n","old_contents":"{-# LANGUAGE ViewPatterns #-}\n\nmodule Database.HyperDex.Internal.Client \n ( Hyperclient, Client\n , ConnectInfo (..)\n , defaultConnectInfo\n , ConnectOptions (..)\n , defaultConnectOptions\n , BackoffMethod (..)\n , Handle\n , Result, AsyncResult, AsyncResultHandle, SearchStream (..)\n , connect, close\n , loopClient, loopClientUntil\n , withClient, withClientImmediate\n , withClientStream\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Data.ByteString (ByteString)\n\n{# import Database.HyperDex.Internal.ReturnCode #}\nimport Database.HyperDex.Internal.Util\n\nimport Data.Map (Map)\nimport qualified Data.Map as Map\n\nimport Control.Concurrent (yield, threadDelay)\nimport Control.Concurrent.MVar\n\nimport Data.Text.Encoding (encodeUtf8)\nimport qualified Data.Text as Text (pack) \n\nimport Data.Default\n\n#include \"hyperclient.h\"\n\n{#pointer *hyperclient as Hyperclient #}\n\n-- | Parameters for connecting to a HyperDex cluster.\ndata ConnectInfo =\n ConnectInfo\n { connectHost :: String\n , connectPort :: Word16\n , connectOptions :: ConnectOptions\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectInfo where\n def = \n ConnectInfo\n { connectHost = \"127.0.0.1\"\n , connectPort = 1982\n , connectOptions = def\n }\n\ndefaultConnectInfo :: ConnectInfo\ndefaultConnectInfo = def\n\n-- | Additional options for connecting and managing the connection\n-- to a HyperDex cluster.\ndata ConnectOptions =\n ConnectOptions\n { connectionBackoff :: BackoffMethod\n , connectionBackoffCap :: Maybe Int\n }\n deriving (Eq, Read, Show)\n\ninstance Default ConnectOptions where\n def =\n ConnectOptions\n { connectionBackoff = BackoffExponential 10 2 -- 10 * 2^n\n , connectionBackoffCap = Just 500000 -- Half a second.\n }\n\n-- | Sane defaults for HyperDex connection options.\ndefaultConnectOptions :: ConnectOptions\ndefaultConnectOptions = def\n\n-- | A connectionBackoff method controls how frequently the client polls internally.\n-- \n-- This is provided to allow fine-tuning performance. Do note that \n-- this does not affect any method the HyperClient C library uses to poll\n-- its connection to a HyperDex cluster.\n--\n-- All integer values are in microseconds.\ndata BackoffMethod\n -- | No delay is used except the thread is yielded.\n = BackoffYield\n -- | Delay a constant number of microseconds each inter.\n | BackoffConstant Int\n -- | Delay with an initial number of microseconds, increasing linearly by the second value. \n | BackoffLinear Int Int\n -- | Delay with an initial number of microseconds, increasing exponentially by the second value. \n | BackoffExponential Int Double\n deriving (Eq, Read, Show)\n\n-- | A callback used to perform work when the Hyperclient loop indicates an\n-- operation has been completed.\n--\n-- A 'Nothing' value indicates that no further work is necessary, and a 'Just' value\n-- will store a new Handle and HandleCallback.\nnewtype HandleCallback = HandleCallback (Maybe ReturnCode -> IO (Maybe (Handle, HandleCallback)))\n\n-- | The core data type managing access to a 'Hyperclient' object and all\n-- currently running asynchronous operations.\n--\n-- The 'MVar' is used as a lock to control access to the 'Hyperclient' and\n-- a map of open handles and continuations, or callbacks, that must be executed\n-- to complete operations. A 'HandleCallback' may yield Nothing or a new 'Handle'\n-- and 'HandleCallback' to be stored in the map.\ntype HyperclientWrapper = MVar (Maybe Hyperclient, Map Handle HandleCallback)\n\ndata ClientData =\n ClientData\n { hyperclientWrapper :: HyperclientWrapper\n , connectionInfo :: ConnectInfo\n }\n\n-- | A connection to a HyperDex cluster.\nnewtype Client = Client { unClientData :: ClientData } \n\n-- | Internal method for returning the (MVar) wrapped connection. \ngetClient :: Client -> HyperclientWrapper\ngetClient = hyperclientWrapper . unClientData\n\n-- | Get the connection info used for a 'Client'.\ngetConnectInfo :: Client -> ConnectInfo\ngetConnectInfo = connectionInfo . unClientData\n\n-- | Get the connection options for a 'Client'.\ngetConnectOptions :: Client -> ConnectOptions\ngetConnectOptions = connectOptions . getConnectInfo\n\n-- | Return value from hyperclient operations.\n--\n-- Per the specification, it's guaranteed to be a unique integer for\n-- each outstanding operation using a given HyperClient. In practice\n-- it is monotonically increasing while operations are outstanding,\n-- lower values are used first, and negative values represent an\n-- error.\ntype Handle = {# type int64_t #}\n\n-- | A return value from HyperDex.\ntype Result a = IO (Either ReturnCode a)\n\n-- | A return value used internally by HyperClient operations.\n--\n-- Internally the wrappers to the HyperDex library will return\n-- a computation that yields a 'Handle' referring to that request\n-- and a continuation that will force the request to return an \n-- error in the form of a ReturnCode or a result.\n--\n-- The result of forcing the result is undefined.\n-- The HyperClient and its workings are not party to the MVar locking\n-- mechanism, and the ReturnCode and\/or return value may be in the\n-- process of being modified when the computation is forced.\n--\n-- Consequently, the only safe way to use this is with a wrapper such\n-- as 'withClient', which only allows the continuation to be run after\n-- the HyperClient has returned the corresponding Handle or after the\n-- HyperClient has been destroyed.\ntype AsyncResultHandle a = IO (Handle, Result a)\n\n-- | A return value used internally by HyperClient operations.\n--\n-- This is the same as 'AsyncResultHandle' except it gives the callback\n-- the result of the loop operation that yields the returned 'Handle'.\ntype StreamResultHandle a = IO (Handle, Maybe ReturnCode -> Result a)\n\n-- | A return value from HyperDex in an asynchronous wrapper.\n--\n-- The full type is an IO (IO (Either ReturnCode a)). Evaluating\n-- the result of an asynchronous call, such as the default get and\n-- put operations starts the request to the HyperDex cluster. Evaluating\n-- the result of that evaluation will poll internally, using the \n-- connection's 'BackoffMethod' until the result is available.\n--\n-- This API may be deprecated in favor of exclusively using MVars in\n-- a future version.\ntype AsyncResult a = IO (Result a)\n\nnewtype SearchStream a = SearchStream (a, Result (SearchStream a))\n\n-- | Connect to a HyperDex cluster.\nconnect :: ConnectInfo -> IO Client\nconnect info = do\n hyperclient <- hyperclientCreate (encodeUtf8 . Text.pack . connectHost $ info) (connectPort info)\n clientData <- newMVar (Just hyperclient, Map.empty)\n return $\n Client\n $ ClientData\n { hyperclientWrapper = clientData \n , connectionInfo = info\n }\n\n-- | Close a connection and terminate any outstanding asynchronous\n-- requests.\n--\n-- \/Note:\/ This does force all asynchronous requests to complete\n-- immediately. Any outstanding requests at the time the 'Client'\n-- is closed ought to return a 'ReturnCode' indicating the failure\n-- condition, but the behavior is ultimately undefined. Any pending\n-- requests should be disregarded. \nclose :: Client -> IO ()\nclose (getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> error \"HyperDex client error - cannot close a client connection twice.\"\n (Just hc, handles) -> do\n hyperclientDestroy hc\n mapM_ (\\(HandleCallback cont) -> cont Nothing) $ Map.elems handles \n putMVar c (Nothing, Map.empty)\n\ndoExponentialBackoff :: Int -> Double -> (Int, BackoffMethod)\ndoExponentialBackoff b x = \n let result = ceiling (fromIntegral b ** x) in\n (result, BackoffExponential result x)\n{-# INLINE doExponentialBackoff #-}\n\ncappedBackoff :: Int -> Maybe Int -> (Int, Bool)\ncappedBackoff n Nothing = (n, False)\ncappedBackoff n (Just c) | n < c = (n, False)\n | otherwise = (c, True)\n{-# INLINE cappedBackoff #-}\n\nperformBackoff :: BackoffMethod -> Maybe Int -> IO (BackoffMethod)\nperformBackoff method cap = do\n let (delay, newBackoff) = case method of\n BackoffYield -> (0, method)\n BackoffConstant n -> (n, method)\n BackoffLinear m b -> (m, BackoffLinear (m+b) b)\n BackoffExponential b x -> doExponentialBackoff b x\n (backoff, capped) = cappedBackoff delay cap\n let doDelay = case backoff of\n 0 -> yield\n n -> threadDelay n\n nextDelay = case capped of\n True -> BackoffConstant backoff\n False -> newBackoff\n doDelay >> return nextDelay\n{-# INLINE performBackoff #-}\n\n-- | Runs hyperclient_loop exactly once, setting the appropriate MVar.\nloopClient :: Client -> IO (Maybe Handle)\nloopClient client@(getClient -> c) = do\n clientData <- takeMVar c\n case clientData of\n (Nothing, _) -> return Nothing\n (Just hc, handles) -> do\n -- TODO: Examine returnCode for things that might matter.\n (handle, returnCode) <- hyperclientLoop hc 0\n case returnCode of\n HyperclientSuccess -> do\n let newMap = Map.delete handle handles\n case Map.lookup handle handles of\n Just (HandleCallback entry) -> do\n cont <- entry $ Just returnCode\n case cont of\n Nothing -> putMVar c (Just hc, newMap)\n Just (h, e) -> putMVar c (Just hc, Map.insert h e newMap)\n Nothing -> putMVar c (Just hc, newMap)\n return $ Just handle\n HyperclientTimeout -> do\n putMVar c (Just hc, handles)\n loopClient client\n HyperclientNonepending -> do\n mapM_ (\\(HandleCallback cont) -> cont Nothing) $ Map.elems handles\n putMVar c (Just hc, Map.empty)\n return $ Just handle\n _ -> do\n putMVar c (Just hc, handles)\n loopClient client\n{-# INLINE loopClient #-}\n\n-- | Run hyperclient_loop at most N times or forever until a handle\n-- is returned.\nloopClientUntil :: Client -> Handle -> MVar a -> BackoffMethod -> Maybe Int -> IO (Bool)\nloopClientUntil _ _ _ _ (Just 0) = return False\n\nloopClientUntil client h v back (Just n) = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential connectionBackoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return True\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> do\n back' <- performBackoff back (connectionBackoffCap . getConnectOptions $ client)\n loopClientUntil client h v back' (Just $ n - 1)\n False -> return True\n\nloopClientUntil client h v back Nothing = do\n empty <- isEmptyMVar v\n case empty of\n True -> do\n _ <- loopClient client\n clientData <- readMVar $ getClient client\n -- TODO: Exponential connectionBackoff or some other approach for polling\n case clientData of\n (Nothing, _) -> return False\n (Just _, handles) -> do\n case Map.member h handles of\n False -> return True\n True -> do \n back' <- performBackoff back (connectionBackoffCap . getConnectOptions $ client)\n loopClientUntil client h v back' Nothing\n False -> return True\n{-# INLINE loopClientUntil #-}\n\n-- | Wrap a HyperClient request and wait until completion or failure.\nwithClientImmediate :: Client -> (Hyperclient -> IO a) -> IO a\nwithClientImmediate (getClient -> c) f =\n withMVar c $ \\value -> do\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, _) -> f hc\n{-# INLINE withClientImmediate #-}\n\n-- | Wrap a Hyperclient request.\nwithClient :: Client -> (Hyperclient -> AsyncResultHandle a) -> AsyncResult a\nwithClient client@(getClient -> c) f = do\n value <- takeMVar c\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, handles) -> do\n (h, cont) <- f hc\n case h > 0 of\n True -> do\n v <- newEmptyMVar :: IO (MVar (Either ReturnCode a))\n let wrappedCallback = HandleCallback $ const $ do\n returnValue <- cont\n putMVar v returnValue\n return Nothing\n putMVar c (Just hc, Map.insert h wrappedCallback handles)\n return $ do\n success <- loopClientUntil client h v (connectionBackoff . getConnectOptions $ client) Nothing \n case success of\n True -> takeMVar v\n False -> return $ Left HyperclientPollfailed\n False -> do\n putMVar c (Just hc, handles)\n returnValue <- cont\n -- A HyperclientInterrupted return code indicates that there was a signal\n -- received by the client that prevented the call from completing, thus\n -- the request should be transparently retried.\n case returnValue of\n Left HyperclientInterrupted -> withClient client f\n _ -> return . return $ returnValue\n{-# INLINE withClient #-}\n\n-- | Wrap a Hyperclient request that returns a search stream.\nwithClientStream :: Client -> (Hyperclient -> StreamResultHandle a) -> AsyncResult (SearchStream a)\nwithClientStream client@(getClient -> c) f = do\n value <- takeMVar c\n case value of\n (Nothing, _) -> error \"HyperDex client error - cannot use a closed connection.\"\n (Just hc, handles) -> do\n (h, cont) <- f hc\n case h > 0 of\n True -> do\n v <- newEmptyMVar :: IO (MVar (Either ReturnCode (SearchStream a)))\n let wrappedCallback = HandleCallback $ \\code -> do\n returnValue <- cont code\n (result, callback) <- wrapSearchStream returnValue client h cont\n putMVar v $ result\n return $ Just (h, callback)\n putMVar c (Just hc, Map.insert h wrappedCallback handles)\n return $ do\n success <- loopClientUntil client h v (connectionBackoff . getConnectOptions $ client) Nothing \n case success of\n True -> takeMVar v\n False -> return $ Left HyperclientPollfailed\n False -> do\n putMVar c (Just hc, handles)\n returnValue <- cont Nothing\n case returnValue of\n Left HyperclientInterrupted -> withClientStream client f\n _ -> do\n (result, _) <- wrapSearchStream returnValue client h cont\n return . return $ result\n{-# INLINE withClientStream #-}\n\nwrapSearchStream :: Either ReturnCode a -> Client -> Handle -> (Maybe ReturnCode -> Result a) -> IO (Either ReturnCode (SearchStream a), HandleCallback)\nwrapSearchStream (Left e) _ _ _ = return $ (Left e, HandleCallback $ const $ return Nothing)\nwrapSearchStream (Right a) client h cont = do\n v <- newEmptyMVar\n let wrappedCallback = HandleCallback $ \\code -> do\n returnValue <- cont code\n (result, callback) <- wrapSearchStream returnValue client h cont\n putMVar v $ result\n return $ Just (h, callback)\n let cont' = do\n success <- loopClientUntil client h v (connectionBackoff . getConnectOptions $ client) Nothing\n case success of\n True -> takeMVar v\n -- TODO: Return actual ReturnCode\n False -> return $ Left HyperclientPollfailed\n return $ (return $ SearchStream (a, cont'), wrappedCallback)\n{-# INLINE wrapSearchStream #-}\n\n-- | C wrapper for hyperclient_create. Creates a HyperClient given a host\n-- and a port.\n--\n-- C definition:\n-- \n-- > struct hyperclient*\n-- > hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: ByteString -> Word16 -> IO Hyperclient\nhyperclientCreate h port = withCBString h $ \\host ->\n wrapHyperCall $ {# call hyperclient_create #} host (fromIntegral port)\n\n-- | C wrapper for hyperclient_destroy. Destroys a HyperClient.\n--\n-- \/Note:\/ This does not ensure resources are freed. Any memory \n-- allocated as staging for incomplete requests will not be returned.\n--\n-- C definition:\n-- \n-- > void\n-- > hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: Hyperclient -> IO ()\nhyperclientDestroy client = wrapHyperCall $ \n {# call hyperclient_destroy #} client\n\n-- | C wrapper for hyperclient_loop. Waits up to some number of\n-- milliseconds for a result before returning.\n--\n-- A negative 'Handle' return value indicates a failure condition\n-- or timeout, a positive value indicates completion of an asynchronous\n-- request.\n--\n-- C definition:\n--\n-- > int64_t\n-- > hyperclient_loop(struct hyperclient* client, int timeout,\n-- > enum hyperclient_returncode* status);\nhyperclientLoop :: Hyperclient -> Int -> IO (Handle, ReturnCode)\nhyperclientLoop client timeout =\n alloca $ \\returnCodePtr -> do\n handle <- wrapHyperCall $ {# call hyperclient_loop #} client (fromIntegral timeout) returnCodePtr\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n return (handle, returnCode)\n{-# INLINE hyperclientLoop #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"dae25c09b995b07672e49266ec64f7ec3401e9e7","subject":"Documentation effort: 5\/23","message":"Documentation effort: 5\/23","repos":"aleator\/CV,BeautifulDestinations\/CV,TomMD\/CV,aleator\/CV","old_file":"CV\/Drawing.chs","new_file":"CV\/Drawing.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, TypeFamilies, MultiParamTypeClasses, TypeSynonymInstances#-}\n#include \"cvWrapLEO.h\"\n-- | Module for exposing opencv drawing functions. These are meant for quick and dirty marking\n-- and not for anything presentable. For any real drawing\n-- you should figure out how to use cairo or related package, such as diagrams. They are\n-- way better.\n--\n-- Consult the \"CV.ImageOp\" module for functions to apply the operations in this module to images.\n\nmodule CV.Drawing(\n -- * Drawable class\n ShapeStyle(Filled,Stroked)\n ,Drawable(..)\n -- * Extra drawing operations\n ,drawLinesOp\n ,rectOpS\n -- * Floodfill operations\n ,fillOp\n ,floodfill\n -- * Shorthand for drawing single shapes\n ,circle\n ,drawLines\n ,rectangle\n ,fillPoly) where\n\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport System.IO.Unsafe\nimport Control.Monad(when)\n\n{#import CV.Image#}\n\nimport CV.ImageOp\n\n-- | Is the shape filled or just a boundary?\ndata ShapeStyle = Filled | Stroked Int\n deriving(Eq,Show)\n\nstyleToCV Filled = -1\nstyleToCV (Stroked w) = fromIntegral w\n\n-- TODO: The instances in here could be significantly smaller..\n-- |Typeclass for images that support elementary drawing operations. \nclass Drawable a b where\n -- |\u00a0Type of the pixel, i.e. Float for a grayscale image and 3-tuple for RGB image.\n type Color a b :: * \n -- |\u00a0Put text of certain color to given coordinates. Good size seems to be around 0.5-1.5.\n putTextOp :: (Color a b) -> Float -> String -> (Int,Int) -> ImageOperation a b\n -- |\u00a0Draw a line between two points.\n lineOp :: (Color a b) -> Int -> (Int,Int) -> (Int,Int) -> ImageOperation a b\n -- |\u00a0Draw a Circle\n circleOp :: (Color a b) -> (Int,Int) -> Int -> ShapeStyle -> ImageOperation a b\n -- | Draw a Rectangle by supplying two corners\n rectOp :: (Color a b) -> Int -> (Int,Int) -> (Int,Int) -> ImageOperation a b\n -- |\u00a0Draw a filled polygon\n fillPolyOp :: (Color a b) -> [(Int,Int)] -> ImageOperation a b\n\ninstance Drawable RGB D32 where\n type Color RGB D32 = (D32,D32,D32)\n putTextOp (r,g,b) size text (x,y) = ImgOp $ \\img -> do\n withGenImage img $\u00a0\\cimg ->\n withCString text $ \\(ctext) ->\n {#call wrapDrawText#} cimg ctext (realToFrac size) \n (fromIntegral x) (fromIntegral y) \n (realToFrac r) (realToFrac g) (realToFrac b) \n\n lineOp (r,g,b) t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawLine#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral x1) (fromIntegral y1) \n (realToFrac r) (realToFrac g) \n (realToFrac b) (fromIntegral t) \n \n circleOp (red,g,b) (x,y) r s = ImgOp $ \\i -> do\n when (r>0) $ withGenImage i $ \\img -> \n ({#call wrapDrawCircle#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral r) (realToFrac red) \n (realToFrac g) (realToFrac b)\n $ styleToCV s)\n rectOp (r,g,b) t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawRectangle#} img (fromIntegral x)\n (fromIntegral y) (fromIntegral x1) (fromIntegral y1)\n (realToFrac r) (realToFrac g)(realToFrac b)(fromIntegral t)\n fillPolyOp (r,g,b) pts = ImgOp $ \\i -> do\n withImage i $ \\img -> do\n let (xs,ys) = unzip pts\n xs' <- newArray $ map fromIntegral xs\n ys' <- newArray $ map fromIntegral ys\n {#call wrapFillPolygon#} img \n (fromIntegral $ length xs) xs' ys' \n (realToFrac r) (realToFrac g) (realToFrac b) \n free xs'\n free ys'\n\n\ninstance Drawable GrayScale D32 where\n type Color GrayScale D32 = D32\n\n putTextOp color size text (x,y) = ImgOp $ \\img -> do\n withGenImage img $\u00a0\\cimg ->\n withCString text $ \\(ctext) ->\n {#call wrapDrawText#} cimg ctext (realToFrac size) \n (fromIntegral x) (fromIntegral y) \n (realToFrac color) (realToFrac color) (realToFrac color) \n\n lineOp c t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawLine#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral x1) (fromIntegral y1) \n (realToFrac c) (realToFrac c) \n (realToFrac c) (fromIntegral t) \n\n circleOp c (x,y) r s = ImgOp $ \\i -> do\n when (r>0) $ withGenImage i $ \\img -> \n ({#call wrapDrawCircle#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral r) \n (realToFrac c) (realToFrac c) (realToFrac c) \n $ styleToCV s)\n\n rectOp c t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawRectangle#} img (fromIntegral x)\n (fromIntegral y) (fromIntegral x1) (fromIntegral y1)\n (realToFrac c)(realToFrac c)(realToFrac c) (fromIntegral t)\n\n fillPolyOp c pts = ImgOp $ \\i -> do\n withImage i $ \\img -> do\n let (xs,ys) = unzip pts\n xs' <- newArray $ map fromIntegral xs\n ys' <- newArray $ map fromIntegral ys\n {#call wrapFillPolygon#} img \n (fromIntegral $ length xs) xs' ys' \n (realToFrac c) (realToFrac c) (realToFrac c) \n free xs'\n free ys'\n\n\n-- |\u00a0Draw a rectangle by giving top left corner and size.\nrectOpS :: Drawable a b => Color a b -> Int -> (Int, Int) -> (Int, Int) \n -> ImageOperation a b\nrectOpS c t pos@(x,y) (w,h) = rectOp c t pos (x+w,y+h)\n\n-- | Flood fill a region of the image\nfillOp :: (Int,Int) -> D32 -> D32 -> D32 -> Bool -> ImageOperation GrayScale D32\nfillOp (x,y) color low high floats = \n ImgOp $ \\i -> do\n withImage i $ \\img -> \n ({#call wrapFloodFill#} img (fromIntegral x) (fromIntegral y)\n (realToFrac color) (realToFrac low) (realToFrac high) (toCINT $ floats))\n where\n toCINT False = 0\n toCINT True = 1\n\n-- | Apply rectOp to an image\nrectangle :: Drawable c d => Color c d -> Int -> (Int, Int) -> (Int, Int) -> Image c d\n -> IO (Image c d)\nrectangle color thickness a b i = \n operate (rectOp color thickness a b ) i\n\n-- | Apply fillPolyOp to an image\nfillPoly :: Drawable c d => Color c d -> [(Int, Int)] -> Image c d -> IO (Image c d)\nfillPoly c pts i = operate (fillPolyOp c pts) i\n\n-- | Draw a polyline\ndrawLinesOp :: Drawable c d => Color c d -> Int -> [((Int, Int), (Int, Int))] -> CV.ImageOp.ImageOperation c d\ndrawLinesOp color thickness segments = \n foldl (#>) nonOp \n $ map (\\(a,b) -> lineOp color thickness a b) segments\n\n-- |\u00a0Apply drawLinesOp to an image\ndrawLines :: Drawable c d => Image c d -> Color c d -> Int -> [((Int, Int), (Int, Int))]\n -> IO (Image c d)\ndrawLines img color thickness segments = operateOn img\n (drawLinesOp color thickness segments)\n\n-- | Apply circleOp to an image\ncircle :: Drawable c d => (Int, Int) -> Int -> Color c d -> ShapeStyle -> Image c d -> Image c d\ncircle center r color s i = unsafeOperate (circleOp color center r s) i\n\n-- |\u00a0Apply fillOp to an image\nfloodfill :: (Int, Int) -> D32 -> D32 -> D32 -> Bool -> Image GrayScale D32 -> Image GrayScale D32\nfloodfill (x,y) color low high floats = \n unsafeOperate (fillOp (x,y) color low high floats) \n\n \n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, TypeFamilies, MultiParamTypeClasses, TypeSynonymInstances#-}\n#include \"cvWrapLEO.h\"\n\nmodule CV.Drawing(ShapeStyle(Filled,Stroked),circle\n ,Drawable(..)\n ,floodfill,drawLinesOp,drawLines,rectangle\n ,rectOpS,fillPoly) where\n\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport System.IO.Unsafe\nimport Control.Monad(when)\n\n{#import CV.Image#}\n\nimport CV.ImageOp\n\ndata ShapeStyle = Filled | Stroked Int\n deriving(Eq,Show)\n\nstyleToCV Filled = -1\nstyleToCV (Stroked w) = fromIntegral w\n\n-- TODO: Add fillstyle for rectOp\n\n\n-- TODO: The instances in here could be significantly smaller..\nclass Drawable a b where\n type Color a b :: * \n putTextOp :: (Color a b) -> Float -> String -> (Int,Int) -> ImageOperation a b\n lineOp :: (Color a b) -> Int -> (Int,Int) -> (Int,Int) -> ImageOperation a b\n circleOp :: (Color a b) -> (Int,Int) -> Int -> ShapeStyle -> ImageOperation a b\n rectOp :: (Color a b) -> Int -> (Int,Int) -> (Int,Int) -> ImageOperation a b\n fillPolyOp :: (Color a b) -> [(Int,Int)] -> ImageOperation a b\n\ninstance Drawable RGB D32 where\n type Color RGB D32 = (D32,D32,D32)\n putTextOp (r,g,b) size text (x,y) = ImgOp $ \\img -> do\n withGenImage img $\u00a0\\cimg ->\n withCString text $ \\(ctext) ->\n {#call wrapDrawText#} cimg ctext (realToFrac size) \n (fromIntegral x) (fromIntegral y) \n (realToFrac r) (realToFrac g) (realToFrac b) \n\n lineOp (r,g,b) t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawLine#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral x1) (fromIntegral y1) \n (realToFrac r) (realToFrac g) \n (realToFrac b) (fromIntegral t) \n \n circleOp (red,g,b) (x,y) r s = ImgOp $ \\i -> do\n when (r>0) $ withGenImage i $ \\img -> \n ({#call wrapDrawCircle#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral r) (realToFrac red) \n (realToFrac g) (realToFrac b)\n $ styleToCV s)\n rectOp (r,g,b) t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawRectangle#} img (fromIntegral x)\n (fromIntegral y) (fromIntegral x1) (fromIntegral y1)\n (realToFrac r) (realToFrac g)(realToFrac b)(fromIntegral t)\n fillPolyOp (r,g,b) pts = ImgOp $ \\i -> do\n withImage i $ \\img -> do\n let (xs,ys) = unzip pts\n xs' <- newArray $ map fromIntegral xs\n ys' <- newArray $ map fromIntegral ys\n {#call wrapFillPolygon#} img \n (fromIntegral $ length xs) xs' ys' \n (realToFrac r) (realToFrac g) (realToFrac b) \n free xs'\n free ys'\n\n\ninstance Drawable GrayScale D32 where\n type Color GrayScale D32 = D32\n\n putTextOp color size text (x,y) = ImgOp $ \\img -> do\n withGenImage img $\u00a0\\cimg ->\n withCString text $ \\(ctext) ->\n {#call wrapDrawText#} cimg ctext (realToFrac size) \n (fromIntegral x) (fromIntegral y) \n (realToFrac color) (realToFrac color) (realToFrac color) \n\n lineOp c t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawLine#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral x1) (fromIntegral y1) \n (realToFrac c) (realToFrac c) \n (realToFrac c) (fromIntegral t) \n\n circleOp c (x,y) r s = ImgOp $ \\i -> do\n when (r>0) $ withGenImage i $ \\img -> \n ({#call wrapDrawCircle#} img (fromIntegral x) (fromIntegral y) \n (fromIntegral r) \n (realToFrac c) (realToFrac c) (realToFrac c) \n $ styleToCV s)\n\n rectOp c t (x,y) (x1,y1) = ImgOp $ \\i -> do\n withGenImage i $ \\img -> \n {#call wrapDrawRectangle#} img (fromIntegral x)\n (fromIntegral y) (fromIntegral x1) (fromIntegral y1)\n (realToFrac c)(realToFrac c)(realToFrac c) (fromIntegral t)\n\n fillPolyOp c pts = ImgOp $ \\i -> do\n withImage i $ \\img -> do\n let (xs,ys) = unzip pts\n xs' <- newArray $ map fromIntegral xs\n ys' <- newArray $ map fromIntegral ys\n {#call wrapFillPolygon#} img \n (fromIntegral $ length xs) xs' ys' \n (realToFrac c) (realToFrac c) (realToFrac c) \n free xs'\n free ys'\n\n\nrectOpS c t pos@(x,y) (w,h) = rectOp c t pos (x+w,y+h)\n\nfillOp :: (Int,Int) -> D32 -> D32 -> D32 -> Bool -> ImageOperation GrayScale D32\nfillOp (x,y) color low high floats = \n ImgOp $ \\i -> do\n withImage i $ \\img -> \n ({#call wrapFloodFill#} img (fromIntegral x) (fromIntegral y)\n (realToFrac color) (realToFrac low) (realToFrac high) (toCINT $ floats))\n where\n toCINT False = 0\n toCINT True = 1\n\n-- Shorthand for single drawing operations. You should however use #> and <## in CV.ImageOp \n-- rather than these\n\n--line color thickness start end i = \n-- operate (lineOp color thickness start end ) i\n\nrectangle color thickness a b i = \n operate (rectOp color thickness a b ) i\n\nfillPoly c pts i = operate (fillPolyOp c pts) i\n\ndrawLinesOp color thickness segments = \n foldl (#>) nonOp \n $ map (\\(a,b) -> lineOp color thickness a b) segments\n\ndrawLines img color thickness segments = operateOn img\n (drawLinesOp color thickness segments)\n\ncircle center r color s i = unsafeOperate (circleOp color center r s) i\n\nfloodfill (x,y) color low high floats = \n unsafeOperate (fillOp (x,y) color low high floats) \n\n \n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"b4baeefdb3593c0eef3bc6a1281aa55f6685b919","subject":"Added binding for planMany.","message":"Added binding for planMany.\n","repos":"flowbox-public\/cufft","old_file":"Foreign\/CUDA\/FFT\/Plan.chs","new_file":"Foreign\/CUDA\/FFT\/Plan.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.FFT.Plan (\n\n -- * Context\n Handle(..),\n Type(..),\n plan1D,\n plan2D,\n plan3D,\n planMany,\n destroy,\n\n) where\n\n-- Friends\nimport Foreign.CUDA.FFT.Error\nimport Foreign.CUDA.FFT.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\n\n#include \n{# context lib=\"cufft\" #}\n\n\n-- | Operations handle\n--\nnewtype Handle = Handle { useHandle :: {# type cufftHandle #}}\n\n{# enum cufftType as Type\n {}\n with prefix=\"CUFFT\" deriving (Eq, Show) #}\n\n-- Context management ----------------------------------------------------------\n--\n\n-- | Creates a 1D FFT plan configuration for a specified signal size and data type.\n-- The third argument tells CUFFT how many 1D transforms to configure.\n--\nplan1D :: Int -> Type -> Int -> IO Handle\nplan1D nx t batch = resultIfOk =<< cufftPlan1d nx t batch\n\n{# fun unsafe cufftPlan1d\n { alloca- `Handle' peekHdl*\n , `Int'\n , cFromEnum `Type'\n , `Int' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 2D FFT plan configuration for a specified signal size and data type.\n--\nplan2D :: Int -> Int -> Type -> IO Handle\nplan2D nx ny t = resultIfOk =<< cufftPlan2d nx ny t\n\n{# fun unsafe cufftPlan2d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 3D FFT plan configuration for a specified signal size and data type.\n--\nplan3D :: Int -> Int -> Int -> Type -> IO Handle\nplan3D nx ny nz t = resultIfOk =<< cufftPlan3d nx ny nz t\n\n{# fun unsafe cufftPlan3d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a batched plan configuration for many signals of a specified size in\n-- either 1, 2 or 3 dimensions, and of the specified data type.\n--\nplanMany :: Int -> [Int] -> [Int] -> Int -> Int -> [Int] -> Int -> Int -> Type -> Int -> IO Handle\nplanMany rank n inembed istride idist onembed ostride odist t batch\n = resultIfOk =<< cufftPlanMany rank n inembed istride idist onembed ostride odist t batch\n\n{# fun unsafe cufftPlanMany\n { alloca- `Handle' peekHdl*\n , `Int'\n , asArray * `[Int]' free*-\n , asArray * `[Int]' free*-\n , `Int'\n , `Int'\n , asArray * `[Int]' free*-\n , `Int'\n , `Int'\n , cFromEnum `Type'\n , `Int'} -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n asArray [] f = f nullPtr\n asArray xs f = withArray (map fromIntegral xs) f\n\n-- | This function releases hardware resources used by the CUFFT plan. The\n-- release of GPU resources may be deferred until the application exits. This\n-- function is usually the last call with a particular handle to the CUFFT\n-- plan.\n--\ndestroy :: Handle -> IO ()\ndestroy ctx = nothingIfOk =<< cufftDestroy ctx\n\n{# fun unsafe cufftDestroy\n { useHandle `Handle' } -> `Result' cToEnum #}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.FFT.Plan (\n\n -- * Context\n Handle(..),\n Type(..),\n plan1D,\n plan2D,\n plan3D,\n destroy,\n\n) where\n\n-- Friends\nimport Foreign.CUDA.FFT.Error\nimport Foreign.CUDA.FFT.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad ( liftM )\n\n#include \n{# context lib=\"cufft\" #}\n\n\n-- | Operations handle\n--\nnewtype Handle = Handle { useHandle :: {# type cufftHandle #}}\n\n{# enum cufftType as Type\n {}\n with prefix=\"CUFFT\" deriving (Eq, Show) #}\n\n-- Context management ----------------------------------------------------------\n--\n\n-- | Creates a 1D FFT plan configuration for a specified signal size and data type.\n-- The third argument tells CUFFT how many 1D transforms to configure.\n--\nplan1D :: Int -> Type -> Int -> IO Handle\nplan1D nx t batch = resultIfOk =<< cufftPlan1d nx t batch\n\n{# fun unsafe cufftPlan1d\n { alloca- `Handle' peekHdl*\n , `Int'\n , cFromEnum `Type'\n , `Int' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 2D FFT plan configuration for a specified signal size and data type.\n--\nplan2D :: Int -> Int -> Type -> IO Handle\nplan2D nx ny t = resultIfOk =<< cufftPlan2d nx ny t\n\n{# fun unsafe cufftPlan2d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | Creates a 3D FFT plan configuration for a specified signal size and data type.\n--\nplan3D :: Int -> Int -> Int -> Type -> IO Handle\nplan3D nx ny nz t = resultIfOk =<< cufftPlan3d nx ny nz t\n\n{# fun unsafe cufftPlan3d\n { alloca- `Handle' peekHdl*\n , `Int'\n , `Int'\n , `Int'\n , cFromEnum `Type' } -> `Result' cToEnum #}\n where\n peekHdl = liftM Handle . peek\n\n-- | This function releases hardware resources used by the CUFFT plan. The\n-- release of GPU resources may be deferred until the application exits. This\n-- function is usually the last call with a particular handle to the CUFFT\n-- plan.\n--\ndestroy :: Handle -> IO ()\ndestroy ctx = nothingIfOk =<< cufftDestroy ctx\n\n{# fun unsafe cufftDestroy\n { useHandle `Handle' } -> `Result' cToEnum #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bd18f7d65d106d8320c3cd3635c65ddb8070f579","subject":"Make warnings in Foreign.hs non-fatal","message":"Make warnings in Foreign.hs non-fatal\n\nc2hs produces code with name shadowing and lots of unused\nbindings. Instead of simply suppressing these errors, make\nthem non-fatal.\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{-# OPTIONS_GHC -Wwarn #-}\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\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"c11a4a64fa6a7b076b14f4b0c9f76eaa0dd16ed2","subject":"Fix documentation and some types in Window. Remove key-binding signals.","message":"Fix documentation and some types in Window. Remove key-binding signals.\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\n{#import Graphics.UI.Gtk.Gdk.Keys#} (KeyVal)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this 'Window'. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO (Maybe Widget)\nwindowGetDefaultWidget self = \n maybeNull (makeNewObject mkWidget) $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- Enter in a dialog (for example). This function sets or unsets the default\n-- widget for a Window about. When setting (rather than unsetting) the\n-- default widget it's generally easier to call widgetGrabDefault on the\n-- widget. Before making a widget the default widget, you must set the\n-- 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n#endif\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ returns @(left, top, right, bottom)@. @left@ is the\n -- width of the frame at the left, @top@ is the height of the frame at the top, @right@\n -- is the width of the frame at the right, @bottom@ is the height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Maybe Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n (Pixbuf nullForeignPtr)\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO (Maybe Pixbuf) -- ^ returns icon for window, or @Nothing@ if none was set\nwindowGetIcon self =\n maybeNull (makeNewGObject mkPixbuf) $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self (Maybe Pixbuf)\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame-event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys-changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set-focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set-focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set-focus\" True\n\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n activateDefault,\n activateFocus,\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> Int -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> Int -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> Int -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this GtkWindow. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO Widget\nwindowGetDefaultWidget self = \n makeNewObject mkWidget $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- | Enter in a dialog (for example). This function sets or unsets the default\n-- | widget for a Window about. When setting (rather than unsetting) the\n-- | default widget it's generally easier to call widgetGrabDefault on the\n-- | widget. Before making a widget the default widget, you must set the\n-- | 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the \\\"window_state_event\\\" signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the \\\"window_state_event\\\" signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling gtk_window_show().\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ return @(left, top, right, bottom)@ is location to store size frame. @left@ is\n -- width of the frame at the left, @top@ is height of the frame at the top, @right@\n -- is width of the frame at the right, @bottom@ is height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the \\\"window_state_event\\\" signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self icon =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO Pixbuf -- ^ returns icon for window\nwindowGetIcon self =\n makeNewGObject mkPixbuf $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a GtkWindow. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self Pixbuf\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n-- | The 'activateDefault' signal is a keybinding signal which gets emitted when the user activates the default widget of window.\nactivateDefault :: WindowClass self => Signal self (IO ())\nactivateDefault = Signal (connect_NONE__NONE \"activate_default\")\n\n-- | The 'activateDefault' signal is a keybinding signal which gets emitted when the user activates the currently focused widget of window.\nactivateFocus :: WindowClass self => Signal self (IO ())\nactivateFocus = Signal (connect_NONE__NONE \"activate_focus\")\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame_event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys_changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set_focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set_focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set_focus\" True\n\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"04a5a0e5136773fea13e68ec53a3e49c0c24f9f5","subject":"gstreamer: M.S.G.Core.Format: document everything; remove formatsContains as it's pretty redundant","message":"gstreamer: M.S.G.Core.Format: document everything; remove formatsContains as it's pretty redundant","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Format.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Format.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.Format (\n \n -- * Types\n Format(..),\n FormatDefinition(..),\n FormatId,\n \n -- * Format Operations\n formatPercentMax,\n formatPercentScale,\n formatGetName,\n formatToQuark,\n formatRegister,\n formatGetByNick,\n formatGetDetails,\n formatIterateDefinitions\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.GObject#}\n\n-- | Get a printable name for the given format.\nformatGetName :: Format -- ^ @format@ - a format\n -> IO String -- ^ the name of the format\nformatGetName format =\n peekUTFString $\n ({# call fun format_get_name #} $\n fromIntegral $ fromFormat format)\n\n-- | Get the unique quark for the given format.\nformatToQuark :: Format -- ^ @format@ - a format\n -> IO Quark -- ^ the unique quark for the format\nformatToQuark =\n {# call format_to_quark #} . fromIntegral . fromFormat\n\n-- | Create a new format based on the given nickname, or register a new format with that nickname.\nformatRegister :: String -- ^ @nick@ - the nickname for the format\n -> String -- ^ @description@ - the description for the format\n -> IO Format -- ^ the format with the given nickname\nformatRegister nick description =\n liftM (toFormat . fromIntegral) $\n withUTFString nick $ \\cNick ->\n (withUTFString description $\n {# call format_register #} cNick)\n\n-- | Get the format with the given nickname, or 'FormatUndefined' if\n-- no format by that nickname was found.\nformatGetByNick :: String -- ^ @nick@ - the nickname for the format\n -> IO Format -- ^ the format with the given nickname,\n -- or 'FormatUndefined' if it was not found\nformatGetByNick nick =\n liftM (toFormat . fromIntegral) $\n withUTFString nick {# call format_get_by_nick #}\n\n-- | Get the given format's definition.\nformatGetDetails :: Format -- ^ @format@ - a format\n -> IO (Maybe FormatDefinition) -- ^ the definition for the given format, or \n -- 'Nothing' if the format was not found\nformatGetDetails format =\n ({# call format_get_details #} $ fromIntegral $ fromFormat format) >>=\n maybePeek peek . castPtr\n\n-- | Get an Iterator over all registered formats.\nformatIterateDefinitions :: IO (Iterator FormatDefinition)\nformatIterateDefinitions =\n {# call format_iterate_definitions #} >>= takeIterator\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.Format (\n \n -- * Types\n Format(..),\n FormatDefinition(..),\n FormatId,\n \n -- * Format Operations\n formatPercentMax,\n formatPercentScale,\n formatGetName,\n formatToQuark,\n formatRegister,\n formatGetByNick,\n formatsContains,\n formatGetDetails,\n formatIterateDefinitions\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.GObject#}\n\nformatGetName :: Format\n -> IO String\nformatGetName format =\n peekUTFString $\n ({# call fun format_get_name #} $\n fromIntegral $ fromFormat format)\n\nformatToQuark :: Format\n -> IO Quark\nformatToQuark =\n {# call format_to_quark #} . fromIntegral . fromFormat\n\nformatRegister :: String\n -> String\n -> IO Format\nformatRegister nick description =\n liftM (toFormat . fromIntegral) $\n withUTFString nick $ \\cNick ->\n (withUTFString description $\n {# call format_register #} cNick)\n\nformatGetByNick :: String\n -> IO Format\nformatGetByNick nick =\n liftM (toFormat . fromIntegral) $\n withUTFString nick {# call format_get_by_nick #}\n\nformatsContains :: [Format]\n -> Format\n -> IO Bool\nformatsContains formats format =\n liftM toBool $ \n withArray0 0 (map cFromEnum formats) $ \\cFormats ->\n {# call formats_contains #} cFormats $ cFromEnum format\n\nformatGetDetails :: Format\n -> IO FormatDefinition\nformatGetDetails format =\n ({# call format_get_details #} $ fromIntegral $ fromFormat format) >>=\n maybePeek peek . castPtr\n\nformatIterateDefinitions :: IO (Iterator FormatDefinition)\nformatIterateDefinitions =\n {# call format_iterate_definitions #} >>= takeIterator\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"93e57c5c514b58f5e3b3ab4fa70c67ea6f9aada8","subject":"export functions","message":"export functions\n","repos":"adamwalker\/haskell_cudd,maweki\/haskell_cudd","old_file":"CuddReorder.chs","new_file":"CuddReorder.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadSiftMaxVar,\n cuddSetSiftMaxVar,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: DdManager -> IO ()\ncuddAutodynDisable (DdManager m) = c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: DdManager -> IO ()\ncuddTurnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetSiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: DdManager -> IO Int\nregReordGCHook m = do\n hk <- makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: DdManager -> IO ()\ncuddAutodynDisable (DdManager m) = c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: DdManager -> IO ()\ncuddTurnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: DdManager -> IO Int\nregReordGCHook m = do\n hk <- makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d6b15874b66b210e6c2a2b0007feca8084d94b33","subject":"Export object(Get\/Set)PropertyInternal Just to make the old TreeList\/CellRenderer.hs build Added a note to make them private again when TreeList\/* is dropped.","message":"Export object(Get\/Set)PropertyInternal\nJust to make the old TreeList\/CellRenderer.hs build\nAdded a note to make them private again when TreeList\/* is dropped.\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\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"305e4d4409c51ba622ccaf9def97356768583675","subject":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty","message":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty\n\ndarcs-hash:20081219165308-21862-db017ad78a847cbc9e34e0532c9d9a73873f9482.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"7cbb85dd9083ca55d8b8b0436e49c8f478834e8d","subject":"Make `within`'s type signature less restrictive.","message":"Make `within`'s type signature less restrictive.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Group.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Group.chs","new_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Group\n (\n -- * Constructor\n groupNew,\n groupCustom,\n groupSetCurrent,\n groupCurrent,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Group functions\n --\n -- $groupfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Widget\nimport Control.Exception (finally)\n\n{# fun Fl_Group_set_current as groupSetCurrent' { id `Ptr ()' } -> `()' #}\n{# fun Fl_Group_current as groupCurrent' {} -> `Ptr ()' id #}\n\ngroupSetCurrent :: (Parent a Group) => Maybe (Ref a) -> IO ()\ngroupSetCurrent group = withMaybeRef group $ \\groupPtr -> groupSetCurrent' groupPtr\n\ngroupCurrent :: IO (Maybe (Ref Group))\ngroupCurrent = groupCurrent' >>= toMaybeRef\n\n{# fun Fl_Group_New as groupNew' { `Int',`Int', `Int', `Int'} -> `Ptr ()' id #}\n{# fun Fl_Group_New_WithLabel as groupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text'} -> `Ptr ()' id #}\ngroupNew :: Rectangle -> Maybe T.Text -> IO (Ref Group)\ngroupNew rectangle label' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case label' of\n (Just l') -> groupNewWithLabel' x_pos y_pos width height l' >>= toRef\n Nothing -> groupNew' x_pos y_pos width height >>= toRef\n\n{# fun Fl_OverriddenGroup_New_WithLabel as overriddenGroupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGroup_New as overriddenGroupNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\ngroupCustom :: Rectangle -> Maybe T.Text -> Maybe (Ref Group -> IO ()) -> CustomWidgetFuncs Group -> IO (Ref Group)\ngroupCustom rectangle l' draw' funcs' =\n widgetMaker rectangle l' draw' (Just funcs') overriddenGroupNew' overriddenGroupNewWithLabel'\n\n{# fun Fl_Group_Destroy as groupDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Destroy ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> groupDestroy' groupPtr\n\n\n{# fun Fl_Group_draw_child as drawChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawChild' groupPtr widgetPtr\n\n{# fun Fl_Group_draw_children as drawChildren' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ (IO ())) => Op (DrawChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> drawChildren' groupPtr\n\n{# fun Fl_Group_draw_outside_label as drawOutsideLabel' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawOutsideLabel ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawOutsideLabel' groupPtr widgetPtr\n\n{# fun Fl_Group_update_child as updateChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (UpdateChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> updateChild' groupPtr widgetPtr\n\n{# fun Fl_Group_begin as begin' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Begin ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> begin' groupPtr\n\n{# fun Fl_Group_end as end' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (End ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> end' groupPtr\n\ninstance (\n Match obj ~ FindOp orig orig (Begin ()),\n Match obj ~ FindOp orig orig (End ()),\n Op (Begin ()) obj orig (IO ()),\n Op (End ()) obj orig (IO ()),\n impl ~ (IO a -> IO a)\n )\n =>\n Op (Within ()) Group orig impl where\n runOp _ _ group action = do\n () <- begin (castTo group :: Ref orig)\n finally action ((end (castTo group :: Ref orig)) :: IO ())\n\n{# fun Fl_Group_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Find ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> find' groupPtr wPtr\n\n{# fun Fl_Group_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> IO ())) => Op (Add ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> add' groupPtr wPtr\n\n{# fun Fl_Group_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> Int -> IO ())) => Op (Insert ()) Group orig impl where\n runOp _ _ group w i = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> insert' groupPtr wPtr i\n\n{# fun Fl_Group_remove_index as removeIndex' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (RemoveIndex ()) Group orig impl where\n runOp _ _ group index' = withRef group $ \\groupPtr -> removeIndex' groupPtr index'\n\n{# fun Fl_Group_remove_widget as removeWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (RemoveWidget ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> removeWidget' groupPtr wPtr\n\n{# fun Fl_Group_clear as clear' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Clear ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clear' groupPtr\n\n{# fun Fl_Group_set_resizable as setResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Maybe ( Ref a ) -> IO ())) => Op (SetResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withMaybeRef o $ \\oPtr -> setResizable' groupPtr oPtr\n\ninstance (impl ~ IO ()) => Op (SetNotResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> setResizable' groupPtr nullPtr\n\n{# fun Fl_Group_resizable as resizable' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Widget)))) => Op (GetResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> resizable' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_add_resizable as addResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (AddResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withRef o $ \\oPtr -> addResizable' groupPtr oPtr\n\n{# fun Fl_Group_init_sizes as initSizes' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (InitSizes ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> initSizes' groupPtr\n\n{# fun Fl_Group_children as children' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Children ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> children' groupPtr\n\n{# fun Fl_Group_set_clip_children as setClipChildren' { id `Ptr ()', cFromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetClipChildren ()) Group orig impl where\n runOp _ _ group c = withRef group $ \\groupPtr -> setClipChildren' groupPtr c\n\n{# fun Fl_Group_clip_children as clipChildren' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (ClipChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clipChildren' groupPtr\n\n{# fun Fl_Group_focus as focus' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (Focus ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> focus' groupPtr wPtr\n\n{# fun Fl_Group__ddfdesign_kludge as ddfdesignKludge' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Widget)))) => Op (DdfdesignKludge ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> ddfdesignKludge' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_insert_with_before as insertWithBefore' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> Ref b -> IO ())) => Op (InsertWithBefore ()) Group orig impl where\n runOp _ _ self w before = withRef self $ \\selfPtr -> withRef w $ \\wPtr -> withRef before $ \\beforePtr -> insertWithBefore' selfPtr wPtr beforePtr\n\n{# fun Fl_Group_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id#}\ninstance (impl ~ (IO [Ref Widget])) => Op (GetArray ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> do\n childArrayPtr <- array' groupPtr\n numChildren <- children group\n arrayToRefs childArrayPtr numChildren\n\n{# fun Fl_Group_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ninstance (impl ~ (Int -> IO (Maybe (Ref Widget)))) => Op (GetChild ()) Group orig impl where\n runOp _ _ self n = withRef self $ \\selfPtr -> child' selfPtr n >>= toMaybeRef\n\n-- $groupfunctions\n-- @\n-- add:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'IO' ()\n--\n-- addResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- begin :: 'Ref' 'Group' -> 'IO' ()\n--\n-- children :: 'Ref' 'Group' -> 'IO' ('Int')\n--\n-- clear :: 'Ref' 'Group' -> 'IO' ()\n--\n-- clipChildren :: 'Ref' 'Group' -> 'IO' ('Bool')\n--\n-- ddfdesignKludge :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- destroy :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- drawChildren :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawOutsideLabel:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- end :: 'Ref' 'Group' -> 'IO' ()\n--\n-- find:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ('Int')\n--\n-- focus:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- getArray :: 'Ref' 'Group' -> 'IO' ['Ref' 'Widget']\n--\n-- getChild :: 'Ref' 'Group' -> 'Int' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- getResizable :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- initSizes :: 'Ref' 'Group' -> 'IO' ()\n--\n-- insert:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'Int' -> 'IO' ()\n--\n-- insertWithBefore:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'Ref' b -> 'IO' ()\n--\n-- removeIndex :: 'Ref' 'Group' -> 'Int' -> 'IO' ()\n--\n-- removeWidget:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- setClipChildren :: 'Ref' 'Group' -> 'Bool' -> 'IO' ()\n--\n-- setNotResizable :: 'Ref' 'Group' -> 'IO' ()\n--\n-- setResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Maybe' ( 'Ref' a ) -> 'IO' ()\n--\n-- updateChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- within:: 'Ref' 'Group' -> 'IO' a -> 'IO' a\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- @\n","old_contents":"{-# LANGUAGE CPP, RankNTypes, UndecidableInstances, GADTs, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Group\n (\n -- * Constructor\n groupNew,\n groupCustom,\n groupSetCurrent,\n groupCurrent,\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Group functions\n --\n -- $groupfunctions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Widget\nimport Control.Exception (finally)\n\n{# fun Fl_Group_set_current as groupSetCurrent' { id `Ptr ()' } -> `()' #}\n{# fun Fl_Group_current as groupCurrent' {} -> `Ptr ()' id #}\n\ngroupSetCurrent :: (Parent a Group) => Maybe (Ref a) -> IO ()\ngroupSetCurrent group = withMaybeRef group $ \\groupPtr -> groupSetCurrent' groupPtr\n\ngroupCurrent :: IO (Maybe (Ref Group))\ngroupCurrent = groupCurrent' >>= toMaybeRef\n\n{# fun Fl_Group_New as groupNew' { `Int',`Int', `Int', `Int'} -> `Ptr ()' id #}\n{# fun Fl_Group_New_WithLabel as groupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text'} -> `Ptr ()' id #}\ngroupNew :: Rectangle -> Maybe T.Text -> IO (Ref Group)\ngroupNew rectangle label' =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case label' of\n (Just l') -> groupNewWithLabel' x_pos y_pos width height l' >>= toRef\n Nothing -> groupNew' x_pos y_pos width height >>= toRef\n\n{# fun Fl_OverriddenGroup_New_WithLabel as overriddenGroupNewWithLabel' { `Int',`Int',`Int',`Int',unsafeToCString `T.Text', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGroup_New as overriddenGroupNew' { `Int',`Int',`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\ngroupCustom :: Rectangle -> Maybe T.Text -> Maybe (Ref Group -> IO ()) -> CustomWidgetFuncs Group -> IO (Ref Group)\ngroupCustom rectangle l' draw' funcs' =\n widgetMaker rectangle l' draw' (Just funcs') overriddenGroupNew' overriddenGroupNewWithLabel'\n\n{# fun Fl_Group_Destroy as groupDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Destroy ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> groupDestroy' groupPtr\n\n\n{# fun Fl_Group_draw_child as drawChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawChild' groupPtr widgetPtr\n\n{# fun Fl_Group_draw_children as drawChildren' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ (IO ())) => Op (DrawChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> drawChildren' groupPtr\n\n{# fun Fl_Group_draw_outside_label as drawOutsideLabel' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (DrawOutsideLabel ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> drawOutsideLabel' groupPtr widgetPtr\n\n{# fun Fl_Group_update_child as updateChild' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (UpdateChild ()) Group orig impl where\n runOp _ _ group widget = withRef group $ \\groupPtr -> withRef widget $ \\widgetPtr -> updateChild' groupPtr widgetPtr\n\n{# fun Fl_Group_begin as begin' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Begin ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> begin' groupPtr\n\n{# fun Fl_Group_end as end' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (End ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> end' groupPtr\n\ninstance (\n Match obj ~ FindOp orig orig (Begin ()),\n Match obj ~ FindOp orig orig (End ()),\n Op (Begin ()) obj orig (IO ()),\n Op (End ()) obj orig (IO ()),\n impl ~ (IO () -> IO ())\n ) => Op (Within ()) Group orig impl where\n runOp _ _ group action = do\n () <- begin (castTo group :: Ref orig)\n finally action ((end (castTo group :: Ref orig)) :: IO ())\n\n{# fun Fl_Group_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO (Int))) => Op (Find ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> find' groupPtr wPtr\n\n{# fun Fl_Group_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> IO ())) => Op (Add ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> add' groupPtr wPtr\n\n{# fun Fl_Group_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a-> Int -> IO ())) => Op (Insert ()) Group orig impl where\n runOp _ _ group w i = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> insert' groupPtr wPtr i\n\n{# fun Fl_Group_remove_index as removeIndex' { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Int -> IO ())) => Op (RemoveIndex ()) Group orig impl where\n runOp _ _ group index' = withRef group $ \\groupPtr -> removeIndex' groupPtr index'\n\n{# fun Fl_Group_remove_widget as removeWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (RemoveWidget ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> removeWidget' groupPtr wPtr\n\n{# fun Fl_Group_clear as clear' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Clear ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clear' groupPtr\n\n{# fun Fl_Group_set_resizable as setResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Maybe ( Ref a ) -> IO ())) => Op (SetResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withMaybeRef o $ \\oPtr -> setResizable' groupPtr oPtr\n\ninstance (impl ~ IO ()) => Op (SetNotResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> setResizable' groupPtr nullPtr\n\n{# fun Fl_Group_resizable as resizable' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Widget)))) => Op (GetResizable ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> resizable' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_add_resizable as addResizable' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (AddResizable ()) Group orig impl where\n runOp _ _ group o = withRef group $ \\groupPtr -> withRef o $ \\oPtr -> addResizable' groupPtr oPtr\n\n{# fun Fl_Group_init_sizes as initSizes' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (InitSizes ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> initSizes' groupPtr\n\n{# fun Fl_Group_children as children' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Children ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> children' groupPtr\n\n{# fun Fl_Group_set_clip_children as setClipChildren' { id `Ptr ()', cFromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetClipChildren ()) Group orig impl where\n runOp _ _ group c = withRef group $ \\groupPtr -> setClipChildren' groupPtr c\n\n{# fun Fl_Group_clip_children as clipChildren' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (ClipChildren ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> clipChildren' groupPtr\n\n{# fun Fl_Group_focus as focus' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> IO ())) => Op (Focus ()) Group orig impl where\n runOp _ _ group w = withRef group $ \\groupPtr -> withRef w $ \\wPtr -> focus' groupPtr wPtr\n\n{# fun Fl_Group__ddfdesign_kludge as ddfdesignKludge' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ (IO (Maybe (Ref Widget)))) => Op (DdfdesignKludge ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> ddfdesignKludge' groupPtr >>= toMaybeRef\n\n{# fun Fl_Group_insert_with_before as insertWithBefore' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a Widget, impl ~ (Ref a -> Ref b -> IO ())) => Op (InsertWithBefore ()) Group orig impl where\n runOp _ _ self w before = withRef self $ \\selfPtr -> withRef w $ \\wPtr -> withRef before $ \\beforePtr -> insertWithBefore' selfPtr wPtr beforePtr\n\n{# fun Fl_Group_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id#}\ninstance (impl ~ (IO [Ref Widget])) => Op (GetArray ()) Group orig impl where\n runOp _ _ group = withRef group $ \\groupPtr -> do\n childArrayPtr <- array' groupPtr\n numChildren <- children group\n arrayToRefs childArrayPtr numChildren\n\n{# fun Fl_Group_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ninstance (impl ~ (Int -> IO (Maybe (Ref Widget)))) => Op (GetChild ()) Group orig impl where\n runOp _ _ self n = withRef self $ \\selfPtr -> child' selfPtr n >>= toMaybeRef\n\n-- $groupfunctions\n-- @\n-- add:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'IO' ()\n--\n-- addResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- begin :: 'Ref' 'Group' -> 'IO' ()\n--\n-- children :: 'Ref' 'Group' -> 'IO' ('Int')\n--\n-- clear :: 'Ref' 'Group' -> 'IO' ()\n--\n-- clipChildren :: 'Ref' 'Group' -> 'IO' ('Bool')\n--\n-- ddfdesignKludge :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- destroy :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- drawChildren :: 'Ref' 'Group' -> 'IO' ()\n--\n-- drawOutsideLabel:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- end :: 'Ref' 'Group' -> 'IO' ()\n--\n-- find:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ('Int')\n--\n-- focus:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- getArray :: 'Ref' 'Group' -> 'IO' ['Ref' 'Widget']\n--\n-- getChild :: 'Ref' 'Group' -> 'Int' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- getResizable :: 'Ref' 'Group' -> 'IO' ('Maybe' ('Ref' 'Widget'))\n--\n-- initSizes :: 'Ref' 'Group' -> 'IO' ()\n--\n-- insert:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a-> 'Int' -> 'IO' ()\n--\n-- insertWithBefore:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'Ref' b -> 'IO' ()\n--\n-- removeIndex :: 'Ref' 'Group' -> 'Int' -> 'IO' ()\n--\n-- removeWidget:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n--\n-- setClipChildren :: 'Ref' 'Group' -> 'Bool' -> 'IO' ()\n--\n-- setNotResizable :: 'Ref' 'Group' -> 'IO' ()\n--\n-- setResizable:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Maybe' ( 'Ref' a ) -> 'IO' ()\n--\n-- updateChild:: ('Parent' a 'Widget') => 'Ref' 'Group' -> 'Ref' a -> 'IO' ()\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"59467b5f14801034fa0de329aaf807b89ec6a6ad","subject":"INLINE small helpers and aliases","message":"INLINE small helpers and aliases\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 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","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\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . peek\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\npeekAudioPort = maybeForeignPtr_ AudioPort\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n\npeekStream = maybeForeignPtr_ Stream\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":"0f73e9448f8f1090e347be7c89b0e697da7a0b55","subject":"pointer import","message":"pointer import\n","repos":"BeautifulDestinations\/CV","old_file":"CV\/LightBalance.chs","new_file":"CV\/LightBalance.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns#-}\n#include \"cvWrapLEO.h\"\nmodule CV.LightBalance where\n\nimport Foreign.C.Types\nimport Foreign.Ptr as C2HSImp\n\nimport System.IO.Unsafe\n{#import CV.Image#}\n\nf::Int -> CInt\nf = fromIntegral\nx2cylinder (f->w,f->h) m s c = unsafePerformIO $\u00a0creatingImage ({#call vignettingModelX2Cyl#} w h\n (realToFrac m) (realToFrac s) (realToFrac c))\ncos4cylinder (f->w,f->h) = unsafePerformIO $\u00a0creatingImage ({#call vignettingModelCos4XCyl#} w h)\ncos4vignetting (f->w,f->h) = unsafePerformIO $\u00a0creatingImage ({#call vignettingModelCos4#} w h)\nthreeB (f->w,f->h) b1 b2 b3 = unsafePerformIO $ creatingImage ({#call vignettingModelB3#} w h b1 b2 b3)\ntwoPar (f->w,f->h) sx sy m = unsafePerformIO $ creatingImage ({#call vignettingModelP#} w h sx sy m)\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns#-}\n#include \"cvWrapLEO.h\"\nmodule CV.LightBalance where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\n\nimport System.IO.Unsafe\n{#import CV.Image#}\n\nf::Int -> CInt\nf = fromIntegral\nx2cylinder (f->w,f->h) m s c = unsafePerformIO $\u00a0creatingImage ({#call vignettingModelX2Cyl#} w h \n (realToFrac m) (realToFrac s) (realToFrac c))\ncos4cylinder (f->w,f->h) = unsafePerformIO $\u00a0creatingImage ({#call vignettingModelCos4XCyl#} w h)\ncos4vignetting (f->w,f->h) = unsafePerformIO $\u00a0creatingImage ({#call vignettingModelCos4#} w h)\nthreeB (f->w,f->h) b1 b2 b3 = unsafePerformIO $ creatingImage ({#call vignettingModelB3#} w h b1 b2 b3)\ntwoPar (f->w,f->h) sx sy m = unsafePerformIO $ creatingImage ({#call vignettingModelP#} w h sx sy m)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3d1ede552b26e688d0bbfe16b77217b0b270a9b2","subject":"Montage fix, again","message":"Montage fix, again","repos":"BeautifulDestinations\/CV,TomMD\/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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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 = 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 (rh,rw)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) \n | y <- [0..u-1] , x <- [0..v-1] \n | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"57c1d890863c31353e5f4d62b4d9f35ef7f6c13b","subject":"Haddock tweaks in IO module.","message":"Haddock tweaks in IO module.\n\nIgnore-this: b196f8eb273decb2b48ef0744f4ff21\n\ndarcs-hash:20090309003406-ed7c9-59b52172dff531ed82dd48c8ac6696c830dadaab.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-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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, parseChunk, Encoding(..), XMLParseError(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level interface\n unsafeParseChunk,\n withHandlers,\n unsafeSetHandlers,\n unsafeReleaseHandlers,\n ExpatHandlers,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = withHandlers parser $ unsafeParseChunk parser xml final\n\n-- | This variant of parseChunk must either be called inside 'withHandlers' (safest), or\n-- between 'unsafeSetHandlers' and 'unsafeReleaseHandlers', and this\n-- will give you better performance than 'parseChunk' if you process multiple chunks inside.\nunsafeParseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nunsafeParseChunk parser xml final = do\n ok <- doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\n\ndata ExpatHandlers = ExpatHandlers\n (FunPtr CStartElementHandler)\n (FunPtr CEndElementHandler)\n (FunPtr CCharacterDataHandler)\n\nunsafeSetHandlers :: Parser -> IO ExpatHandlers\nunsafeSetHandlers parser@(Parser fp startRef endRef charRef) = 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 $ ExpatHandlers cStartH cEndH cCharH\n\nunsafeReleaseHandlers :: ExpatHandlers -> IO ()\nunsafeReleaseHandlers (ExpatHandlers cStartH cEndH cCharH) = do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH\n\n-- | 'unsafeParseChunk' is required to be called inside @withHandlers@.\n-- Safer than using 'unsafeSetHandlers' \/ 'unsafeReleaseHandlers'.\nwithHandlers :: Parser\n -> IO a -- ^ Computation where unsafeParseChunk may be used\n -> IO a\nwithHandlers parser code = do\n bracket\n (unsafeSetHandlers parser)\n unsafeReleaseHandlers\n (\\_ -> code)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- | Parse error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return True\n-- to continue parsing as normal, or False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return True to continue parsing as normal, or False to\n-- terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return True to continue\n-- parsing as normal, or False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","old_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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, parseChunk, Encoding(..), XMLParseError(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level interface\n withHandlers,\n unsafeSetHandlers,\n unsafeReleaseHandlers,\n ExpatHandlers,\n unsafeParseChunk,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = withHandlers parser $ unsafeParseChunk parser xml final\n\n-- | This version of parseChunk must either be called inside withHandlers (safest), or\n-- between 'unsafeSetHandlers' and 'unsafeReleaseHandlers', and this\n-- will give you better performance if you process multiple chunks inside.\nunsafeParseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nunsafeParseChunk parser xml final = do\n ok <- doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\n\ndata ExpatHandlers = ExpatHandlers\n (FunPtr CStartElementHandler)\n (FunPtr CEndElementHandler)\n (FunPtr CCharacterDataHandler)\n\nunsafeSetHandlers :: Parser -> IO ExpatHandlers\nunsafeSetHandlers parser@(Parser fp startRef endRef charRef) = 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 $ ExpatHandlers cStartH cEndH cCharH\n\nunsafeReleaseHandlers :: ExpatHandlers -> IO ()\nunsafeReleaseHandlers (ExpatHandlers cStartH cEndH cCharH) = do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH\n\n-- | 'unsafeParseChunk' is required to be called inside the argument to this.\n-- Safer than using unsafeSetHandlers \/ unsafeReleaseHandlers.\nwithHandlers :: Parser -> IO a -> IO a\nwithHandlers parser code = do\n bracket\n (unsafeSetHandlers parser)\n unsafeReleaseHandlers\n (\\_ -> code)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- | Parse error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return True\n-- to continue parsing as normal, or False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return True to continue parsing as normal, or False to\n-- terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return True to continue\n-- parsing as normal, or False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"749ad9aed3451a351a03aed2c820e5fdb8fea041","subject":"Add new coordinate functions to get \"header height\" of treeView. (Deprecated `treeViewWidgetToTreeCoords` and `treeViewTreeToWidgetCoords`)","message":"Add new coordinate functions to get \"header height\" of treeView. (Deprecated `treeViewWidgetToTreeCoords` and `treeViewTreeToWidgetCoords`)","repos":"vincenthz\/webkit","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-- | @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","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 treeViewWidgetToTreeCoords,\n treeViewTreeToWidgetCoords,\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 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-- | Convert tree to widget pixel coordinates.\n--\n-- * See module description.\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-- | Convert widget to tree pixel coordinates.\n--\n-- * See module description.\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\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":"d6e93ec0897cac53d6dfd6cd4a5856909133a91f","subject":"Fix #3: Fix spelling of \"Quarts\" to \"Quartz\" and deprecate misspelt functions","message":"Fix #3: Fix spelling of \"Quarts\" to \"Quartz\" and deprecate misspelt functions\n\n* applicationGetUseQuartsAccelerators deprecated in favour of applicationGetUseQuartzAccelerators\n* applicationSetUseQuartsAccelerators deprecated in favour of applicationSetUseQuartzAccelerators\n","repos":"gtk2hs\/gtk-mac-integration,gtk2hs\/gtk-mac-integration","old_file":"Graphics\/UI\/Gtk\/OSX\/Application.chs","new_file":"Graphics\/UI\/Gtk\/OSX\/Application.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.OSX.Application (\n Application,\n ApplicationClass,\n castToApplication,\n gTypeApplication,\n toApplication,\n\n applicationNew,\n applicationReady,\n applicationSetUseQuartsAccelerators,\n applicationSetUseQuartzAccelerators,\n applicationGetUseQuartsAccelerators,\n applicationGetUseQuartzAccelerators,\n applicationSetMenuBar,\n applicationSyncMenuBar,\n applicationInsertAppMenuItem,\n applicationSetWindowMenu,\n applicationSetHelpMenu,\n GtkosxApplicationAttentionType(..),\n applicationSetDockMenu,\n applicationSetDockIconPixbuf,\n applicationSetDockIconResource,\n AttentionRequestID(..),\n applicationAttentionRequest,\n applicationCancelAttentionRequest,\n applicationGetBundlePath,\n applicationGetResourcePath,\n applicationGetExecutablePath,\n applicationGetBundleId,\n applicationGetBundleInfo,\n didBecomeActive,\n willResignActive,\n blockTermination,\n willTerminate,\n openFile\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject (objectNew, makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.OSX.Types#}\n{#import Graphics.UI.Gtk.OSX.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\napplicationNew :: IO Application\napplicationNew = makeNewGObject mkApplication $ liftM castPtr $\n objectNew gTypeApplication []\n\n-- |\n--\napplicationReady :: ApplicationClass self => self -> IO ()\napplicationReady self =\n {#call unsafe gtkosx_application_ready#} (toApplication self)\n\n-- |\n--\napplicationSetUseQuartzAccelerators :: ApplicationClass self => self -> Bool -> IO ()\napplicationSetUseQuartzAccelerators self b =\n {#call unsafe gtkosx_application_set_use_quartz_accelerators#} (toApplication self) (fromBool b)\napplicationSetUseQuartsAccelerators :: ApplicationClass self => self -> Bool -> IO ()\napplicationSetUseQuartsAccelerators = applicationSetUseQuartzAccelerators\n{-# DEPRECATED applicationSetUseQuartsAccelerators \"instead of 'applicationSetUseQuartsAccelerators' use 'applicationSetUseQuartzAccelerators'\" #-}\n\n-- |\n--\napplicationGetUseQuartzAccelerators :: ApplicationClass self => self -> IO Bool\napplicationGetUseQuartzAccelerators self = liftM toBool $\n {#call unsafe gtkosx_application_use_quartz_accelerators#} (toApplication self)\napplicationGetUseQuartsAccelerators :: ApplicationClass self => self -> IO Bool\napplicationGetUseQuartsAccelerators = applicationGetUseQuartzAccelerators\n{-# DEPRECATED applicationGetUseQuartsAccelerators \"instead of 'applicationGetUseQuartsAccelerators' use 'applicationGetUseQuartzAccelerators'\" #-}\n\n-- |\n--\napplicationSetMenuBar :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetMenuBar self menu =\n {#call unsafe gtkosx_application_set_menu_bar#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSyncMenuBar :: ApplicationClass self => self -> IO ()\napplicationSyncMenuBar self =\n {#call unsafe gtkosx_application_sync_menubar#} (toApplication self)\n\n-- |\n--\napplicationInsertAppMenuItem :: (ApplicationClass self, WidgetClass menu_item) => self -> menu_item -> Int -> IO ()\napplicationInsertAppMenuItem self menu_item index =\n {#call unsafe gtkosx_application_insert_app_menu_item#} (toApplication self) (toWidget menu_item) (fromIntegral index)\n\n-- |\n--\napplicationSetWindowMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetWindowMenu self menuItem =\n {#call unsafe gtkosx_application_set_window_menu#} (toApplication self) (toMenuItem menuItem)\n\n-- |\n--\napplicationSetHelpMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetHelpMenu self menuItem =\n {#call unsafe gtkosx_application_set_help_menu#} (toApplication self) (toMenuItem menuItem)\n\n{#enum GtkosxApplicationAttentionType {underscoreToCase} deriving (Eq,Show)#}\n\n-- |\n--\napplicationSetDockMenu :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetDockMenu self menu =\n {#call unsafe gtkosx_application_set_dock_menu#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSetDockIconPixbuf :: (ApplicationClass self, PixbufClass pixbuf) => self -> Maybe pixbuf -> IO ()\napplicationSetDockIconPixbuf self mbPixbuf =\n {#call unsafe gtkosx_application_set_dock_icon_pixbuf#} (toApplication self)\n (maybe (Pixbuf nullForeignPtr) toPixbuf mbPixbuf)\n\n-- |\n--\napplicationSetDockIconResource :: (ApplicationClass self, GlibString string)\n => self -> string -> string -> string -> IO ()\napplicationSetDockIconResource self name rType subdir =\n withUTFString name $ \\namePtr ->\n withUTFString rType $ \\typePtr ->\n withUTFString subdir $ \\subdirPtr ->\n {#call unsafe gtkosx_application_set_dock_icon_resource#} (toApplication self) namePtr typePtr subdirPtr\n\nnewtype AttentionRequestID = AttentionRequestID CInt\n\n-- |\n--\napplicationAttentionRequest :: ApplicationClass self => self -> GtkosxApplicationAttentionType -> IO AttentionRequestID\napplicationAttentionRequest self rType = liftM AttentionRequestID $\n {#call unsafe gtkosx_application_attention_request#} (toApplication self) (fromIntegral $ fromEnum rType)\n\n-- |\n--\napplicationCancelAttentionRequest :: ApplicationClass self => self -> AttentionRequestID -> IO ()\napplicationCancelAttentionRequest self (AttentionRequestID id) =\n {#call unsafe gtkosx_application_cancel_attention_request#} (toApplication self) id\n\n-- |\n--\napplicationGetBundlePath :: GlibString string => IO string\napplicationGetBundlePath =\n {#call unsafe gtkosx_application_get_bundle_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetResourcePath :: GlibString string => IO string\napplicationGetResourcePath =\n {#call unsafe gtkosx_application_get_resource_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetExecutablePath :: GlibString string => IO string\napplicationGetExecutablePath =\n {#call unsafe gtkosx_application_get_executable_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleId :: GlibString string => IO string\napplicationGetBundleId =\n {#call unsafe gtkosx_application_get_bundle_id#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleInfo :: GlibString string => string -> IO string\napplicationGetBundleInfo key =\n withUTFString key $ \\keyPtr ->\n {#call unsafe gtkosx_application_get_bundle_info#} keyPtr >>= peekUTFString\n\n-- |\n--\ndidBecomeActive :: ApplicationClass self => Signal self (IO ())\ndidBecomeActive = Signal (connect_NONE__NONE \"NSApplicationDidBecomeActive\")\n\n-- |\n--\nwillResignActive :: ApplicationClass self => Signal self (IO ())\nwillResignActive = Signal (connect_NONE__NONE \"NSApplicationWillResignActive\")\n\n-- |\n--\nblockTermination :: ApplicationClass self => Signal self (IO Bool)\nblockTermination = Signal (connect_NONE__BOOL \"NSApplicationBlockTermination\")\n\n-- |\n--\nwillTerminate :: ApplicationClass self => Signal self (IO ())\nwillTerminate = Signal (connect_NONE__NONE \"NSApplicationWillTerminate\")\n\n-- |\n--\nopenFile :: (ApplicationClass self, GlibString string) => Signal self (string -> IO ())\nopenFile = Signal (connect_GLIBSTRING__NONE \"NSApplicationOpenFile\")\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.OSX.Application (\n Application,\n ApplicationClass,\n castToApplication,\n gTypeApplication,\n toApplication,\n\n applicationNew,\n applicationReady,\n applicationSetUseQuartsAccelerators,\n applicationGetUseQuartsAccelerators,\n applicationSetMenuBar,\n applicationSyncMenuBar,\n applicationInsertAppMenuItem,\n applicationSetWindowMenu,\n applicationSetHelpMenu,\n GtkosxApplicationAttentionType(..),\n applicationSetDockMenu,\n applicationSetDockIconPixbuf,\n applicationSetDockIconResource,\n AttentionRequestID(..),\n applicationAttentionRequest,\n applicationCancelAttentionRequest,\n applicationGetBundlePath,\n applicationGetResourcePath,\n applicationGetExecutablePath,\n applicationGetBundleId,\n applicationGetBundleInfo,\n didBecomeActive,\n willResignActive,\n blockTermination,\n willTerminate,\n openFile\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject (objectNew, makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.OSX.Types#}\n{#import Graphics.UI.Gtk.OSX.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\napplicationNew :: IO Application\napplicationNew = makeNewGObject mkApplication $ liftM castPtr $\n objectNew gTypeApplication []\n\n-- |\n--\napplicationReady :: ApplicationClass self => self -> IO ()\napplicationReady self =\n {#call unsafe gtkosx_application_ready#} (toApplication self)\n\n-- |\n--\napplicationSetUseQuartsAccelerators :: ApplicationClass self => self -> Bool -> IO ()\napplicationSetUseQuartsAccelerators self b =\n {#call unsafe gtkosx_application_set_use_quartz_accelerators#} (toApplication self) (fromBool b)\n\n-- |\n--\napplicationGetUseQuartsAccelerators :: ApplicationClass self => self -> IO Bool\napplicationGetUseQuartsAccelerators self = liftM toBool $\n {#call unsafe gtkosx_application_use_quartz_accelerators#} (toApplication self)\n\n-- |\n--\napplicationSetMenuBar :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetMenuBar self menu =\n {#call unsafe gtkosx_application_set_menu_bar#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSyncMenuBar :: ApplicationClass self => self -> IO ()\napplicationSyncMenuBar self =\n {#call unsafe gtkosx_application_sync_menubar#} (toApplication self)\n\n-- |\n--\napplicationInsertAppMenuItem :: (ApplicationClass self, WidgetClass menu_item) => self -> menu_item -> Int -> IO ()\napplicationInsertAppMenuItem self menu_item index =\n {#call unsafe gtkosx_application_insert_app_menu_item#} (toApplication self) (toWidget menu_item) (fromIntegral index)\n\n-- |\n--\napplicationSetWindowMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetWindowMenu self menuItem =\n {#call unsafe gtkosx_application_set_window_menu#} (toApplication self) (toMenuItem menuItem)\n\n-- |\n--\napplicationSetHelpMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetHelpMenu self menuItem =\n {#call unsafe gtkosx_application_set_help_menu#} (toApplication self) (toMenuItem menuItem)\n\n{#enum GtkosxApplicationAttentionType {underscoreToCase} deriving (Eq,Show)#}\n\n-- |\n--\napplicationSetDockMenu :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetDockMenu self menu =\n {#call unsafe gtkosx_application_set_dock_menu#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSetDockIconPixbuf :: (ApplicationClass self, PixbufClass pixbuf) => self -> Maybe pixbuf -> IO ()\napplicationSetDockIconPixbuf self mbPixbuf =\n {#call unsafe gtkosx_application_set_dock_icon_pixbuf#} (toApplication self)\n (maybe (Pixbuf nullForeignPtr) toPixbuf mbPixbuf)\n\n-- |\n--\napplicationSetDockIconResource :: (ApplicationClass self, GlibString string)\n => self -> string -> string -> string -> IO ()\napplicationSetDockIconResource self name rType subdir =\n withUTFString name $ \\namePtr ->\n withUTFString rType $ \\typePtr ->\n withUTFString subdir $ \\subdirPtr ->\n {#call unsafe gtkosx_application_set_dock_icon_resource#} (toApplication self) namePtr typePtr subdirPtr\n\nnewtype AttentionRequestID = AttentionRequestID CInt\n\n-- |\n--\napplicationAttentionRequest :: ApplicationClass self => self -> GtkosxApplicationAttentionType -> IO AttentionRequestID\napplicationAttentionRequest self rType = liftM AttentionRequestID $\n {#call unsafe gtkosx_application_attention_request#} (toApplication self) (fromIntegral $ fromEnum rType)\n\n-- |\n--\napplicationCancelAttentionRequest :: ApplicationClass self => self -> AttentionRequestID -> IO ()\napplicationCancelAttentionRequest self (AttentionRequestID id) =\n {#call unsafe gtkosx_application_cancel_attention_request#} (toApplication self) id\n\n-- |\n--\napplicationGetBundlePath :: GlibString string => IO string\napplicationGetBundlePath =\n {#call unsafe gtkosx_application_get_bundle_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetResourcePath :: GlibString string => IO string\napplicationGetResourcePath =\n {#call unsafe gtkosx_application_get_resource_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetExecutablePath :: GlibString string => IO string\napplicationGetExecutablePath =\n {#call unsafe gtkosx_application_get_executable_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleId :: GlibString string => IO string\napplicationGetBundleId =\n {#call unsafe gtkosx_application_get_bundle_id#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleInfo :: GlibString string => string -> IO string\napplicationGetBundleInfo key =\n withUTFString key $ \\keyPtr ->\n {#call unsafe gtkosx_application_get_bundle_info#} keyPtr >>= peekUTFString\n\n-- |\n--\ndidBecomeActive :: ApplicationClass self => Signal self (IO ())\ndidBecomeActive = Signal (connect_NONE__NONE \"NSApplicationDidBecomeActive\")\n\n-- |\n--\nwillResignActive :: ApplicationClass self => Signal self (IO ())\nwillResignActive = Signal (connect_NONE__NONE \"NSApplicationWillResignActive\")\n\n-- |\n--\nblockTermination :: ApplicationClass self => Signal self (IO Bool)\nblockTermination = Signal (connect_NONE__BOOL \"NSApplicationBlockTermination\")\n\n-- |\n--\nwillTerminate :: ApplicationClass self => Signal self (IO ())\nwillTerminate = Signal (connect_NONE__NONE \"NSApplicationWillTerminate\")\n\n-- |\n--\nopenFile :: (ApplicationClass self, GlibString string) => Signal self (string -> IO ())\nopenFile = Signal (connect_GLIBSTRING__NONE \"NSApplicationOpenFile\")\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"acff04eea3715e92c5c9ec27f33b353661a62892","subject":"Some more commit functions","message":"Some more commit functions\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\nnewtype Tree = Tree 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\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\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\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\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\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ee617921da9f7049c2a4f70c87aadf272980a070","subject":"[project @ 2002-07-04 10:44:47 by as49] Realized that the onDestroy should actually be bound to the destroy of GtkObject, not to the destroy-event of GtkWidget.","message":"[project @ 2002-07-04 10:44:47 by as49]\nRealized that the onDestroy should actually be bound to the destroy of\nGtkObject, not to the destroy-event of GtkWidget.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/vte","old_file":"gtk\/abstract\/Widget.chs","new_file":"gtk\/abstract\/Widget.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget class@\n--\n-- Author : Axel Simon\n-- \n-- Created: 27 April 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/04 10:44:47 $\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 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 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-- @dunno@Lock accelerators.\n-- * @literal@\n--widgetLockAccelerators :: WidgetClass w => w -> IO ()\n--widgetLockAccelerators = {#call unsafe widget_lock_accelerators#}.toWidget\n\n\n-- @dunno@Unlock accelerators.\n-- * @literal@\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 -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonGrabFocus = event \"grab_focus\" [] False\nafterGrabFocus = event \"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 class@\n--\n-- Author : Axel Simon\n-- \n-- Created: 27 April 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/05\/24 09:43:24 $\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 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 onDestroy,\n afterDestroy,\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 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 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-- @dunno@Lock accelerators.\n-- * @literal@\n--widgetLockAccelerators :: WidgetClass w => w -> IO ()\n--widgetLockAccelerators = {#call unsafe widget_lock_accelerators#}.toWidget\n\n\n-- @dunno@Unlock accelerators.\n-- * @literal@\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 connectToDestroy@ The widget will be destroyed.\n--\n-- * This is the last signal this widget will receive.\n--\nonDestroy, afterDestroy :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonDestroy = event \"destroy_event\" [] False\nafterDestroy = 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 -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonGrabFocus = event \"grab_focus\" [] False\nafterGrabFocus = event \"grab_focus\" [] 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":"ed06dd16a55b1c49f31e67b09d461725937cc829","subject":"remove comments","message":"remove comments\n","repos":"maweki\/haskell_cudd,adamwalker\/haskell_cudd","old_file":"Cudd\/Reorder.chs","new_file":"Cudd\/Reorder.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule Cudd.Reorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadSiftMaxVar,\n cuddSetSiftMaxVar,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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\nimport Control.Monad.ST\nimport Control.Monad.ST.Unsafe\n\nimport Cudd.Internal\nimport Cudd.C\nimport Cudd.Hook\n\n#include \n#include \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> STDdManager s u -> ST s j\nreadIntegral f (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> STDdManager s u -> i -> ST s ()\nsetIntegral f (STDdManager m) v = unsafeIOToST $ f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> STDdManager s u -> ST s f\nreadFloat f (STDdManager m) = unsafeIOToST $ liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> STDdManager s u -> r -> ST s ()\nsetFloat f (STDdManager m) v = unsafeIOToST $ f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: STDdManager s u -> ST s (Int, CuddReorderingType)\ncuddReorderingStatus (STDdManager m) = unsafeIOToST $ do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: STDdManager s u -> CuddReorderingType -> ST s ()\ncuddAutodynEnable (STDdManager m) t = unsafeIOToST $ c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: STDdManager s u -> ST s ()\ncuddAutodynDisable (STDdManager m) = unsafeIOToST $ c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: STDdManager s u -> CuddReorderingType -> Int -> ST s Int\ncuddReduceHeap (STDdManager m) typ minsize = unsafeIOToST $ liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: STDdManager s u -> Int -> Int -> Int -> ST s (Ptr ())\ncuddMakeTreeNode (STDdManager m) low size typ = unsafeIOToST $ do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: STDdManager s u -> ST s Int\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CUInt)\n\ncuddReadReorderings :: STDdManager s u -> ST s Int\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: STDdManager s u -> ST s Int\ncuddEnableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: STDdManager s u -> ST s Int\ncuddDisableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: STDdManager s u -> ST s Int\ncuddReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: STDdManager s u -> ST s Int\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: STDdManager s u -> ST s Int\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: STDdManager s u -> ST s ()\ncuddTurnOffCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: STDdManager s u -> ST s ()\ncuddTurnOnCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: STDdManager s u -> ST s Int\ncuddDeadAreCounted (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: STDdManager s u -> ST s Int\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: STDdManager s u -> ST s Int\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxVar :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: STDdManager s u -> ST s Int\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: STDdManager s u -> Int -> ST s ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: STDdManager s u -> ST s Double\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: STDdManager s u -> ST s Double\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: STDdManager s u -> ST s Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: STDdManager s u -> Int -> ST s ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: STDdManager s u -> ST s Int\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: STDdManager s u -> Int -> ST s ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: STDdManager s u -> ST s Int\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: STDdManager s u -> Int -> ST s ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n performGC\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: STDdManager s u -> ST s Int\nregReordGCHook m = do\n hk <- unsafeIOToST $ makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule Cudd.Reorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadSiftMaxVar,\n cuddSetSiftMaxVar,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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\nimport Control.Monad.ST\nimport Control.Monad.ST.Unsafe\n\nimport Cudd.Internal\nimport Cudd.C\nimport Cudd.Hook\n\n#include \n#include \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> STDdManager s u -> ST s j\nreadIntegral f (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> STDdManager s u -> i -> ST s ()\nsetIntegral f (STDdManager m) v = unsafeIOToST $ f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> STDdManager s u -> ST s f\nreadFloat f (STDdManager m) = unsafeIOToST $ liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> STDdManager s u -> r -> ST s ()\nsetFloat f (STDdManager m) v = unsafeIOToST $ f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: STDdManager s u -> ST s (Int, CuddReorderingType)\ncuddReorderingStatus (STDdManager m) = unsafeIOToST $ do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: STDdManager s u -> CuddReorderingType -> ST s ()\ncuddAutodynEnable (STDdManager m) t = unsafeIOToST $ c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: STDdManager s u -> ST s ()\ncuddAutodynDisable (STDdManager m) = unsafeIOToST $ c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: STDdManager s u -> CuddReorderingType -> Int -> ST s Int\ncuddReduceHeap (STDdManager m) typ minsize = unsafeIOToST $ liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: STDdManager s u -> Int -> Int -> Int -> ST s (Ptr ())\ncuddMakeTreeNode (STDdManager m) low size typ = unsafeIOToST $ do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: STDdManager s u -> ST s Int\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CUInt)\n\ncuddReadReorderings :: STDdManager s u -> ST s Int\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: STDdManager s u -> ST s Int\ncuddEnableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: STDdManager s u -> ST s Int\ncuddDisableReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: STDdManager s u -> ST s Int\ncuddReorderingReporting (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: STDdManager s u -> ST s Int\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: STDdManager s u -> ST s Int\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: STDdManager s u -> ST s ()\ncuddTurnOffCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: STDdManager s u -> ST s ()\ncuddTurnOnCountDead (STDdManager m) = unsafeIOToST $ c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: STDdManager s u -> ST s Int\ncuddDeadAreCounted (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: STDdManager s u -> ST s Int\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: STDdManager s u -> ST s Int\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxVar :: STDdManager s u -> Int -> ST s ()\ncuddSetSiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: STDdManager s u -> ST s Int\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: STDdManager s u -> Int -> ST s ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: STDdManager s u -> ST s Double\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: STDdManager s u -> ST s Double\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: STDdManager s u -> Double -> ST s ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: STDdManager s u -> ST s Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: STDdManager s u -> Int -> ST s ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: STDdManager s u -> ST s Int\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: STDdManager s u -> Int -> ST s ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: STDdManager s u -> ST s Int\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: STDdManager s u -> Int -> ST s ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: STDdManager s u -> ST s Int\nregReordGCHook m = do\n hk <- unsafeIOToST $ makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2e0a9816b8a43ab7e8a42846dd88b7c3c405d151","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\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit","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":"570bde40024f00194e78aa61afb1452af2b85e2a","subject":"Rename the conditional map insert operation","message":"Rename the conditional map insert operation\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\n ( -- Simple, single-key operations \n get\n , put\n , putIfNotExist\n , delete \n , putConditional\n -- Atomic numeric operations\n , atomicAdd, atomicSub\n , atomicMul, atomicDiv\n -- Atomic integral operations\n , atomicMod\n , atomicAnd, atomicOr\n , atomicXor\n -- Atomic string operations\n , atomicStringPrepend, atomicStringAppend\n , atomicListLPush, atomicListRPush\n , atomicSetAdd, atomicSetRemove\n , atomicSetUnion, atomicSetIntersect\n -- Atomic simple map operations\n , atomicMapInsert, atomicMapDelete\n -- , atomicConditionalMapInsert\n -- Atomic numeric value operations\n , atomicMapAdd, atomicMapSub\n , atomicMapMul, atomicMapDiv\n -- Atomic integral value operations\n , atomicMapMod\n , atomicMapAnd, atomicMapOr\n , atomicMapXor\n -- Atomic string value operations \n , atomicMapStringPrepend \n , atomicMapStringAppend\n -- Search operations\n , search\n , deleteGroup\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Data.ByteString (ByteString)\nimport Data.Text (Text)\n\n#include \"hyperclient.h\"\n\n{# import Database.HyperDex.Internal.ReturnCode #}\n{# import Database.HyperDex.Internal.Client #}\n{# import Database.HyperDex.Internal.Attribute #}\n{# import Database.HyperDex.Internal.AttributeCheck #}\n{# import Database.HyperDex.Internal.MapAttribute #}\nimport Database.HyperDex.Internal.Util\n\ndata Op = OpPut\n | OpPutIfNotExist\n | OpAtomicAdd\n | OpAtomicSub\n | OpAtomicMul\n | OpAtomicDiv\n | OpAtomicMod\n | OpAtomicAnd\n | OpAtomicOr\n | OpAtomicXor\n | OpAtomicStringPrepend\n | OpAtomicStringAppend\n | OpAtomicListLPush\n | OpAtomicListRPush\n | OpAtomicSetAdd\n | OpAtomicSetRemove\n | OpAtomicSetIntersect\n | OpAtomicSetUnion\n\ndata MapOp = OpAtomicMapInsert\n | OpAtomicMapDelete\n | OpAtomicMapAdd\n | OpAtomicMapSub\n | OpAtomicMapMul\n | OpAtomicMapDiv\n | OpAtomicMapMod\n | OpAtomicMapAnd\n | OpAtomicMapOr\n | OpAtomicMapXor\n | OpAtomicMapStringPrepend\n | OpAtomicMapStringAppend\n\nput :: Client -> Text -> ByteString -> [Attribute] -> AsyncResult ()\nput = hyperclientOp OpPut\n\nputIfNotExist :: Client -> Text -> ByteString -> [Attribute] -> AsyncResult ()\nputIfNotExist = hyperclientOp OpPutIfNotExist\n\natomicAdd, atomicSub,\n atomicMul, atomicDiv,\n atomicMod,\n atomicAnd, atomicOr,\n atomicXor,\n atomicStringPrepend, atomicStringAppend,\n atomicListLPush, atomicListRPush,\n atomicSetAdd, atomicSetRemove,\n atomicSetUnion, atomicSetIntersect :: Client -> Text -> ByteString -> [Attribute] -> AsyncResult ()\n\natomicAdd = hyperclientOp OpAtomicAdd \natomicSub = hyperclientOp OpAtomicSub \natomicMul = hyperclientOp OpAtomicMul \natomicDiv = hyperclientOp OpAtomicDiv \natomicMod = hyperclientOp OpAtomicMod \natomicAnd = hyperclientOp OpAtomicAnd \natomicOr = hyperclientOp OpAtomicOr \natomicXor = hyperclientOp OpAtomicXor \natomicStringPrepend = hyperclientOp OpAtomicStringPrepend \natomicStringAppend = hyperclientOp OpAtomicStringAppend \natomicListLPush = hyperclientOp OpAtomicListLPush \natomicListRPush = hyperclientOp OpAtomicListRPush \natomicSetAdd = hyperclientOp OpAtomicSetAdd \natomicSetRemove = hyperclientOp OpAtomicSetRemove \natomicSetIntersect = hyperclientOp OpAtomicSetIntersect\natomicSetUnion = hyperclientOp OpAtomicSetUnion \n\natomicMapInsert,\n atomicMapDelete,\n atomicMapAdd,\n atomicMapSub,\n atomicMapMul,\n atomicMapDiv,\n atomicMapMod,\n atomicMapAnd,\n atomicMapOr,\n atomicMapXor,\n atomicMapStringPrepend, \n atomicMapStringAppend :: Client -> Text -> ByteString -> [MapAttribute] -> AsyncResult () \n\natomicMapInsert = hyperclientMapOp OpAtomicMapInsert\natomicMapDelete = hyperclientMapOp OpAtomicMapDelete\natomicMapAdd = hyperclientMapOp OpAtomicMapAdd \natomicMapSub = hyperclientMapOp OpAtomicMapSub \natomicMapMul = hyperclientMapOp OpAtomicMapMul \natomicMapDiv = hyperclientMapOp OpAtomicMapDiv \natomicMapMod = hyperclientMapOp OpAtomicMapMod \natomicMapAnd = hyperclientMapOp OpAtomicMapAnd \natomicMapOr = hyperclientMapOp OpAtomicMapOr \natomicMapXor = hyperclientMapOp OpAtomicMapXor \natomicMapStringPrepend = hyperclientMapOp OpAtomicMapStringPrepend\natomicMapStringAppend = hyperclientMapOp OpAtomicMapStringAppend \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);\nget :: Client\n -> Text\n -> ByteString\n -> AsyncResult [Attribute] \nget client s k = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n attributePtrPtr <- malloc\n attributeSizePtr <- malloc\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n handle <- wrapHyperCall $\n {# call hyperclient_get #}\n hyperclient\n space key (fromIntegral keySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n attributes <-\n case returnCode of\n HyperclientSuccess -> do\n attributePtr <- peek attributePtrPtr\n attributeSize <- fmap fromIntegral $ peek attributeSizePtr\n attrs <- peekArray attributeSize attributePtr\n hyperdexFreeAttributes attributePtr attributeSize\n return attrs\n _ -> return []\n free returnCodePtr\n free attributePtrPtr\n free attributeSizePtr\n free space\n free key\n return $ \n case returnCode of \n HyperclientSuccess -> Right attributes\n _ -> Left returnCode\n return (handle, continuation)\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);\ndelete :: Client\n -> Text\n -> ByteString\n -> AsyncResult ()\ndelete client s k = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n handle <- wrapHyperCall $\n {# call hyperclient_del #}\n hyperclient\n space key (fromIntegral keySize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n\n-- int64_t\n-- hyperclient_cond_put(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_attribute_check* checks, size_t checks_sz,\n-- const struct hyperclient_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\nputConditional :: Client \n -> Text\n -> ByteString\n -> [AttributeCheck]\n -> [Attribute]\n -> AsyncResult ()\nputConditional client s k checks attributes = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n handle <- wrapHyperCall $\n {# call hyperclient_cond_put #}\n hyperclient\n space key (fromIntegral keySize)\n checkPtr (fromIntegral checkSize)\n attributePtr (fromIntegral attributeSize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n haskellFreeAttributes attributePtr attributeSize\n haskellFreeAttributeChecks checkPtr checkSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n\n-- int64_t\n-- hyperclient_atomic_xor(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\nhyperclientOp :: Op\n -> Client\n -> Text\n -> ByteString\n -> [Attribute]\n -> AsyncResult ()\nhyperclientOp op = \n \\client s k attributes ->\n withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n let ccall = case op of\n OpPut -> {# call hyperclient_put #}\n OpPutIfNotExist -> {# call hyperclient_put_if_not_exist #}\n OpAtomicAdd -> {# call hyperclient_atomic_add #}\n OpAtomicSub -> {# call hyperclient_atomic_sub #}\n OpAtomicMul -> {# call hyperclient_atomic_mul #}\n OpAtomicDiv -> {# call hyperclient_atomic_div #}\n OpAtomicMod -> {# call hyperclient_atomic_mod #}\n OpAtomicAnd -> {# call hyperclient_atomic_and #}\n OpAtomicOr -> {# call hyperclient_atomic_or #}\n OpAtomicXor -> {# call hyperclient_atomic_xor #}\n OpAtomicStringPrepend -> {# call hyperclient_string_prepend #}\n OpAtomicStringAppend -> {# call hyperclient_string_append #}\n OpAtomicListLPush -> {# call hyperclient_list_lpush #}\n OpAtomicListRPush -> {# call hyperclient_list_rpush #}\n OpAtomicSetAdd -> {# call hyperclient_set_add #}\n OpAtomicSetRemove -> {# call hyperclient_set_remove #}\n OpAtomicSetIntersect -> {# call hyperclient_set_intersect #}\n OpAtomicSetUnion -> {# call hyperclient_set_union #}\n handle <- wrapHyperCall $\n ccall\n hyperclient\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n hyperdexFreeAttributes attributePtr attributeSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n{-# INLINE hyperclientOp #-}\n\n-- int64_t\n-- hyperclient_map_add(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_map_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\nhyperclientMapOp :: MapOp \n -> Client\n -> Text\n -> ByteString\n -> [MapAttribute]\n -> AsyncResult ()\nhyperclientMapOp op =\n \\client s k mapAttributes ->\n withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n (mapAttributePtr, mapAttributeSize) <- newHyperDexMapAttributeArray mapAttributes\n let ccall = case op of\n OpAtomicMapInsert -> {# call hyperclient_map_add #}\n OpAtomicMapDelete -> {# call hyperclient_map_remove #}\n OpAtomicMapAdd -> {# call hyperclient_map_atomic_add #}\n OpAtomicMapSub -> {# call hyperclient_map_atomic_sub #}\n OpAtomicMapMul -> {# call hyperclient_map_atomic_mul #}\n OpAtomicMapDiv -> {# call hyperclient_map_atomic_div #}\n OpAtomicMapMod -> {# call hyperclient_map_atomic_mod #}\n OpAtomicMapAnd -> {# call hyperclient_map_atomic_and #}\n OpAtomicMapOr -> {# call hyperclient_map_atomic_or #}\n OpAtomicMapXor -> {# call hyperclient_map_atomic_xor #}\n OpAtomicMapStringPrepend -> {# call hyperclient_map_string_prepend #}\n OpAtomicMapStringAppend -> {# call hyperclient_map_string_append #}\n handle <- wrapHyperCall $\n ccall\n hyperclient space\n key (fromIntegral keySize)\n mapAttributePtr (fromIntegral mapAttributeSize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n --haskellFreeMapAttributes mapAttributePtr mapAttributeSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n{-# INLINE hyperclientMapOp #-}\n\n-- int64_t\n-- hyperclient_map_add(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_map_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\n---- A compilation error prevents this from being implemented:\n-- \/home\/cloudium\/git\/hyhac\/dist\/build\/libHShyhac-0.2.0.0_p.a(Hyperclient.p_o): In function `ra9O_info':\n-- \/tmp\/ghc20379_0\/ghc20379_1.p_o:(.text+0x1d6): undefined reference to `hyperclient_cond_map_add'\n-- \/home\/cloudium\/git\/hyhac\/dist\/build\/libHShyhac-0.2.0.0_p.a(Hyperclient.p_o): In function `sdlx_info':\n-- \/tmp\/ghc20379_0\/ghc20379_1.p_o:(.text+0x3d08d): undefined reference to `hyperclient_cond_map_add'\n-- \/home\/cloudium\/git\/hyhac\/dist\/build\/libHShyhac-0.2.0.0_p.a(Hyperclient.p_o): In function `sdm2_info':\n-- \/tmp\/ghc20379_0\/ghc20379_1.p_o:(.text+0x3dc85): undefined reference to `hyperclient_cond_map_add'\n\n-- atomicConditionalMapInsert :: Hyperclient -> Text -> ByteString\n-- -> [AttributeCheck]\n-- -> [MapAttribute]\n-- -> AsyncResultHandle ()\n-- atomicConditionalMapInsert client s k checks mapAttributes = do\n-- returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n-- space <- newTextUtf8 s\n-- (key,keySize) <- newCBStringLen k\n-- (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n-- (mapAttributePtr, mapAttributeSize) <- newHyperDexMapAttributeArray mapAttributes\n-- handle <- {# call hyperclient_cond_map_add #}\n-- client space\n-- key (fromIntegral keySize)\n-- checkPtr (fromIntegral checkSize)\n-- mapAttributePtr (fromIntegral mapAttributeSize)\n-- returnCodePtr\n-- let continuation = do\n-- returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n-- free returnCodePtr\n-- free space\n-- free key\n-- --haskellFreeMapAttributes mapAttributePtr mapAttributeSize\n-- return $ \n-- case returnCode of \n-- HyperclientSuccess -> Right ()\n-- _ -> Left returnCode\n-- return (handle, continuation)\n-- {-# INLINE atomicConditionalMapInsert #-}\n\n-- int64_t\n-- hyperclient_search(struct hyperclient* client, const char* space,\n-- const struct hyperclient_attribute_check* checks, size_t checks_sz,\n-- enum hyperclient_returncode* status,\n-- struct hyperclient_attribute** attrs, size_t* attrs_sz);\nsearch :: Client\n -> Text\n -> [AttributeCheck] \n -> AsyncResult (SearchStream [Attribute])\nsearch client s checks = withClientStream client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n resultSetPtrPtr <- malloc\n resultSetSizePtr <- malloc\n handle <- wrapHyperCall $\n {# call hyperclient_search #}\n hyperclient space\n checkPtr (fromIntegral checkSize :: {# type size_t #})\n returnCodePtr\n resultSetPtrPtr resultSetSizePtr\n case handle >= 0 of\n True -> do\n let continuation (Just HyperclientSuccess) = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n case returnCode of\n HyperclientSuccess -> do\n resultSize <- peek resultSetSizePtr\n resultSetPtr <- peek resultSetPtrPtr\n resultSet <- peekArray (fromIntegral resultSize) resultSetPtr\n return $ Right resultSet\n _ -> return $ Left returnCode\n continuation e = do\n free returnCodePtr\n free space\n haskellFreeAttributeChecks checkPtr checkSize\n free resultSetPtrPtr\n free resultSetSizePtr\n return $ Left $ case e of \n Nothing -> HyperclientDupeattr\n Just rc -> rc\n return (handle, continuation)\n False -> do\n let continuation = const $ do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n haskellFreeAttributeChecks checkPtr checkSize\n free resultSetPtrPtr\n free resultSetSizePtr\n return $ Left returnCode\n return (handle, continuation)\n\n-- int64_t\n-- hyperclient_group_del(struct hyperclient* client, const char* space,\n-- const struct hyperclient_attribute_check* checks, size_t checks_sz,\n-- enum hyperclient_returncode* status);\n--\ndeleteGroup :: Client \n -> Text\n -> [AttributeCheck]\n -> AsyncResult ()\ndeleteGroup client s checks = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n handle <- wrapHyperCall $\n {# call hyperclient_group_del #}\n hyperclient space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n haskellFreeAttributeChecks checkPtr checkSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n","old_contents":"module Database.HyperDex.Internal.Hyperclient\n ( -- Simple, single-key operations \n get\n , put\n , putIfNotExist\n , delete \n , putConditional\n -- Atomic numeric operations\n , atomicAdd, atomicSub\n , atomicMul, atomicDiv\n -- Atomic integral operations\n , atomicMod\n , atomicAnd, atomicOr\n , atomicXor\n -- Atomic string operations\n , atomicStringPrepend, atomicStringAppend\n , atomicListLPush, atomicListRPush\n , atomicSetAdd, atomicSetRemove\n , atomicSetUnion, atomicSetIntersect\n -- Atomic simple map operations\n , atomicMapInsert, atomicMapDelete\n -- , hyperMapInsertConditional\n -- Atomic numeric value operations\n , atomicMapAdd, atomicMapSub\n , atomicMapMul, atomicMapDiv\n -- Atomic integral value operations\n , atomicMapMod\n , atomicMapAnd, atomicMapOr\n , atomicMapXor\n -- Atomic string value operations \n , atomicMapStringPrepend \n , atomicMapStringAppend\n -- Search operations\n , search\n , deleteGroup\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Data.ByteString (ByteString)\nimport Data.Text (Text)\n\n#include \"hyperclient.h\"\n\n{# import Database.HyperDex.Internal.ReturnCode #}\n{# import Database.HyperDex.Internal.Client #}\n{# import Database.HyperDex.Internal.Attribute #}\n{# import Database.HyperDex.Internal.AttributeCheck #}\n{# import Database.HyperDex.Internal.MapAttribute #}\nimport Database.HyperDex.Internal.Util\n\ndata Op = OpPut\n | OpPutIfNotExist\n | OpAtomicAdd\n | OpAtomicSub\n | OpAtomicMul\n | OpAtomicDiv\n | OpAtomicMod\n | OpAtomicAnd\n | OpAtomicOr\n | OpAtomicXor\n | OpAtomicStringPrepend\n | OpAtomicStringAppend\n | OpAtomicListLPush\n | OpAtomicListRPush\n | OpAtomicSetAdd\n | OpAtomicSetRemove\n | OpAtomicSetIntersect\n | OpAtomicSetUnion\n\ndata MapOp = OpAtomicMapInsert\n | OpAtomicMapDelete\n | OpAtomicMapAdd\n | OpAtomicMapSub\n | OpAtomicMapMul\n | OpAtomicMapDiv\n | OpAtomicMapMod\n | OpAtomicMapAnd\n | OpAtomicMapOr\n | OpAtomicMapXor\n | OpAtomicMapStringPrepend\n | OpAtomicMapStringAppend\n\nput :: Client -> Text -> ByteString -> [Attribute] -> AsyncResult ()\nput = hyperclientOp OpPut\n\nputIfNotExist :: Client -> Text -> ByteString -> [Attribute] -> AsyncResult ()\nputIfNotExist = hyperclientOp OpPutIfNotExist\n\natomicAdd, atomicSub,\n atomicMul, atomicDiv,\n atomicMod,\n atomicAnd, atomicOr,\n atomicXor,\n atomicStringPrepend, atomicStringAppend,\n atomicListLPush, atomicListRPush,\n atomicSetAdd, atomicSetRemove,\n atomicSetUnion, atomicSetIntersect :: Client -> Text -> ByteString -> [Attribute] -> AsyncResult ()\n\natomicAdd = hyperclientOp OpAtomicAdd \natomicSub = hyperclientOp OpAtomicSub \natomicMul = hyperclientOp OpAtomicMul \natomicDiv = hyperclientOp OpAtomicDiv \natomicMod = hyperclientOp OpAtomicMod \natomicAnd = hyperclientOp OpAtomicAnd \natomicOr = hyperclientOp OpAtomicOr \natomicXor = hyperclientOp OpAtomicXor \natomicStringPrepend = hyperclientOp OpAtomicStringPrepend \natomicStringAppend = hyperclientOp OpAtomicStringAppend \natomicListLPush = hyperclientOp OpAtomicListLPush \natomicListRPush = hyperclientOp OpAtomicListRPush \natomicSetAdd = hyperclientOp OpAtomicSetAdd \natomicSetRemove = hyperclientOp OpAtomicSetRemove \natomicSetIntersect = hyperclientOp OpAtomicSetIntersect\natomicSetUnion = hyperclientOp OpAtomicSetUnion \n\natomicMapInsert,\n atomicMapDelete,\n atomicMapAdd,\n atomicMapSub,\n atomicMapMul,\n atomicMapDiv,\n atomicMapMod,\n atomicMapAnd,\n atomicMapOr,\n atomicMapXor,\n atomicMapStringPrepend, \n atomicMapStringAppend :: Client -> Text -> ByteString -> [MapAttribute] -> AsyncResult () \n\natomicMapInsert = hyperclientMapOp OpAtomicMapInsert\natomicMapDelete = hyperclientMapOp OpAtomicMapDelete\natomicMapAdd = hyperclientMapOp OpAtomicMapAdd \natomicMapSub = hyperclientMapOp OpAtomicMapSub \natomicMapMul = hyperclientMapOp OpAtomicMapMul \natomicMapDiv = hyperclientMapOp OpAtomicMapDiv \natomicMapMod = hyperclientMapOp OpAtomicMapMod \natomicMapAnd = hyperclientMapOp OpAtomicMapAnd \natomicMapOr = hyperclientMapOp OpAtomicMapOr \natomicMapXor = hyperclientMapOp OpAtomicMapXor \natomicMapStringPrepend = hyperclientMapOp OpAtomicMapStringPrepend\natomicMapStringAppend = hyperclientMapOp OpAtomicMapStringAppend \n\n-- hyperMapInsertConditional :: Client -> Text -> ByteString -> [AttributeCheck] -> [MapAttribute] -> AsyncResult ()\n-- hyperMapInsertConditional c s k checks attrs = withClient c $ \\hc -> hyperclientConditionalMapInsert hc s k checks attrs\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);\nget :: Client\n -> Text\n -> ByteString\n -> AsyncResult [Attribute] \nget client s k = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n attributePtrPtr <- malloc\n attributeSizePtr <- malloc\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n handle <- wrapHyperCall $\n {# call hyperclient_get #}\n hyperclient\n space key (fromIntegral keySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n attributes <-\n case returnCode of\n HyperclientSuccess -> do\n attributePtr <- peek attributePtrPtr\n attributeSize <- fmap fromIntegral $ peek attributeSizePtr\n attrs <- peekArray attributeSize attributePtr\n hyperdexFreeAttributes attributePtr attributeSize\n return attrs\n _ -> return []\n free returnCodePtr\n free attributePtrPtr\n free attributeSizePtr\n free space\n free key\n return $ \n case returnCode of \n HyperclientSuccess -> Right attributes\n _ -> Left returnCode\n return (handle, continuation)\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);\ndelete :: Client\n -> Text\n -> ByteString\n -> AsyncResult ()\ndelete client s k = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n handle <- wrapHyperCall $\n {# call hyperclient_del #}\n hyperclient\n space key (fromIntegral keySize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n\n-- int64_t\n-- hyperclient_cond_put(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_attribute_check* checks, size_t checks_sz,\n-- const struct hyperclient_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\nputConditional :: Client \n -> Text\n -> ByteString\n -> [AttributeCheck]\n -> [Attribute]\n -> AsyncResult ()\nputConditional client s k checks attributes = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n handle <- wrapHyperCall $\n {# call hyperclient_cond_put #}\n hyperclient\n space key (fromIntegral keySize)\n checkPtr (fromIntegral checkSize)\n attributePtr (fromIntegral attributeSize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n haskellFreeAttributes attributePtr attributeSize\n haskellFreeAttributeChecks checkPtr checkSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n\n-- int64_t\n-- hyperclient_atomic_xor(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\nhyperclientOp :: Op\n -> Client\n -> Text\n -> ByteString\n -> [Attribute]\n -> AsyncResult ()\nhyperclientOp op = \n \\client s k attributes ->\n withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n let ccall = case op of\n OpPut -> {# call hyperclient_put #}\n OpPutIfNotExist -> {# call hyperclient_put_if_not_exist #}\n OpAtomicAdd -> {# call hyperclient_atomic_add #}\n OpAtomicSub -> {# call hyperclient_atomic_sub #}\n OpAtomicMul -> {# call hyperclient_atomic_mul #}\n OpAtomicDiv -> {# call hyperclient_atomic_div #}\n OpAtomicMod -> {# call hyperclient_atomic_mod #}\n OpAtomicAnd -> {# call hyperclient_atomic_and #}\n OpAtomicOr -> {# call hyperclient_atomic_or #}\n OpAtomicXor -> {# call hyperclient_atomic_xor #}\n OpAtomicStringPrepend -> {# call hyperclient_string_prepend #}\n OpAtomicStringAppend -> {# call hyperclient_string_append #}\n OpAtomicListLPush -> {# call hyperclient_list_lpush #}\n OpAtomicListRPush -> {# call hyperclient_list_rpush #}\n OpAtomicSetAdd -> {# call hyperclient_set_add #}\n OpAtomicSetRemove -> {# call hyperclient_set_remove #}\n OpAtomicSetIntersect -> {# call hyperclient_set_intersect #}\n OpAtomicSetUnion -> {# call hyperclient_set_union #}\n handle <- wrapHyperCall $\n ccall\n hyperclient\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n hyperdexFreeAttributes attributePtr attributeSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n{-# INLINE hyperclientOp #-}\n\n-- int64_t\n-- hyperclient_map_add(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_map_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\nhyperclientMapOp :: MapOp \n -> Client\n -> Text\n -> ByteString\n -> [MapAttribute]\n -> AsyncResult ()\nhyperclientMapOp op =\n \\client s k mapAttributes ->\n withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (key,keySize) <- newCBStringLen k\n (mapAttributePtr, mapAttributeSize) <- newHyperDexMapAttributeArray mapAttributes\n let ccall = case op of\n OpAtomicMapInsert -> {# call hyperclient_map_add #}\n OpAtomicMapDelete -> {# call hyperclient_map_remove #}\n OpAtomicMapAdd -> {# call hyperclient_map_atomic_add #}\n OpAtomicMapSub -> {# call hyperclient_map_atomic_sub #}\n OpAtomicMapMul -> {# call hyperclient_map_atomic_mul #}\n OpAtomicMapDiv -> {# call hyperclient_map_atomic_div #}\n OpAtomicMapMod -> {# call hyperclient_map_atomic_mod #}\n OpAtomicMapAnd -> {# call hyperclient_map_atomic_and #}\n OpAtomicMapOr -> {# call hyperclient_map_atomic_or #}\n OpAtomicMapXor -> {# call hyperclient_map_atomic_xor #}\n OpAtomicMapStringPrepend -> {# call hyperclient_map_string_prepend #}\n OpAtomicMapStringAppend -> {# call hyperclient_map_string_append #}\n handle <- wrapHyperCall $\n ccall\n hyperclient space\n key (fromIntegral keySize)\n mapAttributePtr (fromIntegral mapAttributeSize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n --haskellFreeMapAttributes mapAttributePtr mapAttributeSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n{-# INLINE hyperclientMapOp #-}\n\n-- int64_t\n-- hyperclient_map_add(struct hyperclient* client, const char* space,\n-- const char* key, size_t key_sz,\n-- const struct hyperclient_map_attribute* attrs, size_t attrs_sz,\n-- enum hyperclient_returncode* status);\n---- A compilation error prevents this from being implemented:\n-- \/home\/cloudium\/git\/hyhac\/dist\/build\/libHShyhac-0.2.0.0_p.a(Hyperclient.p_o): In function `ra9O_info':\n-- \/tmp\/ghc20379_0\/ghc20379_1.p_o:(.text+0x1d6): undefined reference to `hyperclient_cond_map_add'\n-- \/home\/cloudium\/git\/hyhac\/dist\/build\/libHShyhac-0.2.0.0_p.a(Hyperclient.p_o): In function `sdlx_info':\n-- \/tmp\/ghc20379_0\/ghc20379_1.p_o:(.text+0x3d08d): undefined reference to `hyperclient_cond_map_add'\n-- \/home\/cloudium\/git\/hyhac\/dist\/build\/libHShyhac-0.2.0.0_p.a(Hyperclient.p_o): In function `sdm2_info':\n-- \/tmp\/ghc20379_0\/ghc20379_1.p_o:(.text+0x3dc85): undefined reference to `hyperclient_cond_map_add'\n\n--hyperclientConditionalMapInsert :: Hyperclient -> Text -> ByteString\n-- -> [AttributeCheck]\n-- -> [MapAttribute]\n-- -> AsyncResultHandle ()\n--hyperclientConditionalMapInsert client s k checks mapAttributes = do\n-- returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n-- space <- newTextUtf8 s\n-- (key,keySize) <- newCBStringLen k\n-- (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n-- (mapAttributePtr, mapAttributeSize) <- newHyperDexMapAttributeArray mapAttributes\n-- handle <- {# call hyperclient_cond_map_add #}\n-- client space\n-- key (fromIntegral keySize)\n-- checkPtr (fromIntegral checkSize)\n-- mapAttributePtr (fromIntegral mapAttributeSize)\n-- returnCodePtr\n-- let continuation = do\n-- returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n-- free returnCodePtr\n-- free space\n-- free key\n-- --haskellFreeMapAttributes mapAttributePtr mapAttributeSize\n-- return $ \n-- case returnCode of \n-- HyperclientSuccess -> Right ()\n-- _ -> Left returnCode\n-- return (handle, continuation)\n--{-# INLINE hyperclientConditionalMapInsert #-}\n\n-- int64_t\n-- hyperclient_search(struct hyperclient* client, const char* space,\n-- const struct hyperclient_attribute_check* checks, size_t checks_sz,\n-- enum hyperclient_returncode* status,\n-- struct hyperclient_attribute** attrs, size_t* attrs_sz);\nsearch :: Client\n -> Text\n -> [AttributeCheck] \n -> AsyncResult (SearchStream [Attribute])\nsearch client s checks = withClientStream client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n resultSetPtrPtr <- malloc\n resultSetSizePtr <- malloc\n handle <- wrapHyperCall $\n {# call hyperclient_search #}\n hyperclient space\n checkPtr (fromIntegral checkSize :: {# type size_t #})\n returnCodePtr\n resultSetPtrPtr resultSetSizePtr\n case handle >= 0 of\n True -> do\n let continuation (Just HyperclientSuccess) = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n case returnCode of\n HyperclientSuccess -> do\n resultSize <- peek resultSetSizePtr\n resultSetPtr <- peek resultSetPtrPtr\n resultSet <- peekArray (fromIntegral resultSize) resultSetPtr\n return $ Right resultSet\n _ -> return $ Left returnCode\n continuation e = do\n free returnCodePtr\n free space\n haskellFreeAttributeChecks checkPtr checkSize\n free resultSetPtrPtr\n free resultSetSizePtr\n return $ Left $ case e of \n Nothing -> HyperclientDupeattr\n Just rc -> rc\n return (handle, continuation)\n False -> do\n let continuation = const $ do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n haskellFreeAttributeChecks checkPtr checkSize\n free resultSetPtrPtr\n free resultSetSizePtr\n return $ Left returnCode\n return (handle, continuation)\n\n-- int64_t\n-- hyperclient_group_del(struct hyperclient* client, const char* space,\n-- const struct hyperclient_attribute_check* checks, size_t checks_sz,\n-- enum hyperclient_returncode* status);\n--\ndeleteGroup :: Client \n -> Text\n -> [AttributeCheck]\n -> AsyncResult ()\ndeleteGroup client s checks = withClient client $ \\hyperclient -> do\n returnCodePtr <- new (fromIntegral . fromEnum $ HyperclientGarbage)\n space <- newTextUtf8 s\n (checkPtr, checkSize) <- newHyperDexAttributeCheckArray checks\n handle <- wrapHyperCall $\n {# call hyperclient_group_del #}\n hyperclient space\n checkPtr (fromIntegral checkSize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n haskellFreeAttributeChecks checkPtr checkSize\n return $ \n case returnCode of \n HyperclientSuccess -> Right ()\n _ -> Left returnCode\n return (handle, continuation)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7e798a5cf5e23d0da0264a538fe3fe85e0bb6b18","subject":"gstreamer: remove commented function messageParseAsyncStart in Message.chs","message":"gstreamer: remove commented function messageParseAsyncStart in Message.chs\n\ndarcs-hash:20070720201214-21862-86c3a174d5a556525132da314b7d0363b9e3c844.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n \n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n --messageParseAsyncStart\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\n{-\nmessageParseAsyncStart :: Message\n -> Bool\nmessageParseAsyncStart message =\n toBool $ unsafePerformIO $ alloca $ \\newBaseTimePtr ->\n do poke newBaseTimePtr $ fromBool False\n {# call message_parse_async_start #} message newBaseTimePtr\n peek newBaseTimePtr\n-}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"861147f3e3692606eb9b5040f6f487d5430c219e","subject":"Added GHC option -fno-warn-missing-signatures to avoid warnings from compiler","message":"Added GHC option -fno-warn-missing-signatures to avoid warnings from compiler\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 \"init_wrapper.h\"\n\nmodule Control.Parallel.MPI.Internal\n ( init, initThread, finalize, send, bsend, ssend, rsend, recv,\n commRank, probe, commSize,\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, error)\nimport C2HS\n\n{# context prefix = \"MPI\" #}\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_ #}\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\n#include \n#include \"init_wrapper.h\"\n\nmodule Control.Parallel.MPI.Internal\n ( init, initThread, finalize, send, bsend, ssend, rsend, recv,\n commRank, probe, commSize,\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, error)\nimport C2HS\n\n{# context prefix = \"MPI\" #}\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_ #}\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":"78bd10f46140fbe2c3b333ee272d61eb018ff986","subject":"Manually do Int->CInt conversions to avoid dependency on cIntConv","message":"Manually do Int->CInt conversions to avoid dependency on cIntConv\n","repos":"travitch\/hsqml,travitch\/hsqml","old_file":"src\/Graphics\/QML\/Internal\/Classes.chs","new_file":"src\/Graphics\/QML\/Internal\/Classes.chs","new_contents":"{-# LANGUAGE\n ForeignFunctionInterface\n #-}\n\nmodule Graphics.QML.Internal.Classes where\n\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.StablePtr\n\n#include \"hsqml.h\"\n\ntype UniformFunc = Ptr () -> Ptr (Ptr ()) -> IO ()\ntype PlacementFunc = Ptr () -> IO ()\n\nforeign import ccall \"wrapper\"\n marshalFunc :: UniformFunc -> IO (FunPtr UniformFunc)\n\nforeign import ccall \"wrapper\"\n marshalPlacementFunc :: PlacementFunc -> IO (FunPtr PlacementFunc)\n\n{#pointer *HsQMLClassHandle as ^ foreign newtype #}\n\nforeign import ccall \"hsqml.h &hsqml_finalise_class_handle\"\n hsqmlFinaliseClassHandlePtr :: FunPtr (Ptr (HsQMLClassHandle) -> IO ())\n\nnewClassHandle :: Ptr HsQMLClassHandle -> IO (Maybe HsQMLClassHandle)\nnewClassHandle p =\n if nullPtr == p\n then return Nothing\n else do\n fp <- newForeignPtr hsqmlFinaliseClassHandlePtr p\n return $ Just $ HsQMLClassHandle fp\n\n{#fun unsafe hsqml_create_class as ^\n {id `Ptr CUInt',\n id `Ptr CChar',\n id `Ptr (FunPtr UniformFunc)',\n id `Ptr (FunPtr UniformFunc)'} ->\n `Maybe HsQMLClassHandle' newClassHandle* #}\n\n{#fun unsafe hsqml_allocate_in_place as ^\n {id `Ptr ()',\n id `Ptr ()',\n id `Ptr HsQMLClassHandle'} -> `()' #}\n\n{#fun unsafe hsqml_register_type as ^\n {id `FunPtr PlacementFunc',\n `String',\n fromIntegral `CInt',\n fromIntegral `CInt',\n `String'} -> `()' #}\n\n{#pointer *HsQMLObjectHandle as ^ newtype #}\n\nobjToPtr :: a -> (Ptr () -> IO b) -> IO b\nobjToPtr obj f = do\n sPtr <- newStablePtr obj\n res <- f $ castStablePtrToPtr sPtr\n return res\n\nwithHsQMLClassHandle :: HsQMLClassHandle -> (Ptr HsQMLClassHandle -> IO b) -> IO b\n{#fun unsafe hsqml_create_object as ^\n {objToPtr* `a',\n withHsQMLClassHandle* `HsQMLClassHandle'} ->\n `HsQMLObjectHandle' id #}\n\nptrToObj :: Ptr () -> IO a\nptrToObj =\n deRefStablePtr . castPtrToStablePtr\n\n{#fun unsafe hsqml_get_haskell as ^\n {id `HsQMLObjectHandle'} ->\n `a' ptrToObj* #}\n\nofDynamicMetaObject :: CUInt\nofDynamicMetaObject = 0x01\n\nmfAccessPrivate, mfAccessProtected, mfAccessPublic, mfAccessMask,\n mfMethodMethod, mfMethodSignal, mfMethodSlot, mfMethodConstructor,\n mfMethodTypeMask, mfMethodCompatibility, mfMethodCloned, mfMethodScriptable\n :: CUInt\nmfAccessPrivate = 0x00\nmfAccessProtected = 0x01\nmfAccessPublic = 0x02\nmfAccessMask = 0x03\nmfMethodMethod = 0x00\nmfMethodSignal = 0x04\nmfMethodSlot = 0x08\nmfMethodConstructor = 0x0c\nmfMethodTypeMask = 0x0c\nmfMethodCompatibility = 0x10\nmfMethodCloned = 0x20\nmfMethodScriptable = 0x40\n\npfInvalid, pfReadable, pfWritable, pfResettable, pfEnumOrFlag, pfStdCppSet,\n pfConstant, pfFinal, pfDesignable, pfResolveDesignable, pfScriptable,\n pfResolveScriptable, pfStored, pfResolveStored, pfEditable,\n pfResolveEditable, pfUser, pfResolveUser, pfNotify :: CUInt\npfInvalid = 0x00000000\npfReadable = 0x00000001\npfWritable = 0x00000002\npfResettable = 0x00000004\npfEnumOrFlag = 0x00000008\npfStdCppSet = 0x00000100\npfConstant = 0x00000400\npfFinal = 0x00000800\npfDesignable = 0x00001000\npfResolveDesignable = 0x00002000\npfScriptable = 0x00004000\npfResolveScriptable = 0x00008000\npfStored = 0x00010000\npfResolveStored = 0x00020000\npfEditable = 0x00040000\npfResolveEditable = 0x00080000\npfUser = 0x00100000\npfResolveUser = 0x00200000\npfNotify = 0x00400000\n","old_contents":"{-# LANGUAGE\n ForeignFunctionInterface\n #-}\n\nmodule Graphics.QML.Internal.Classes where\n\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.StablePtr\n\n#include \"hsqml.h\"\n\ntype UniformFunc = Ptr () -> Ptr (Ptr ()) -> IO ()\ntype PlacementFunc = Ptr () -> IO ()\n\nforeign import ccall \"wrapper\"\n marshalFunc :: UniformFunc -> IO (FunPtr UniformFunc)\n\nforeign import ccall \"wrapper\"\n marshalPlacementFunc :: PlacementFunc -> IO (FunPtr PlacementFunc)\n\n{#pointer *HsQMLClassHandle as ^ foreign newtype #}\n\nforeign import ccall \"hsqml.h &hsqml_finalise_class_handle\"\n hsqmlFinaliseClassHandlePtr :: FunPtr (Ptr (HsQMLClassHandle) -> IO ())\n\nnewClassHandle :: Ptr HsQMLClassHandle -> IO (Maybe HsQMLClassHandle)\nnewClassHandle p =\n if nullPtr == p\n then return Nothing\n else do\n fp <- newForeignPtr hsqmlFinaliseClassHandlePtr p\n return $ Just $ HsQMLClassHandle fp\n\n{#fun unsafe hsqml_create_class as ^\n {id `Ptr CUInt',\n id `Ptr CChar',\n id `Ptr (FunPtr UniformFunc)',\n id `Ptr (FunPtr UniformFunc)'} ->\n `Maybe HsQMLClassHandle' newClassHandle* #}\n\n{#fun unsafe hsqml_allocate_in_place as ^\n {id `Ptr ()',\n id `Ptr ()',\n id `Ptr HsQMLClassHandle'} -> `()' #}\n\n{#fun unsafe hsqml_register_type as ^\n {id `FunPtr PlacementFunc',\n `String',\n `Int',\n `Int',\n `String'} -> `()' #}\n\n{#pointer *HsQMLObjectHandle as ^ newtype #}\n\nobjToPtr :: a -> (Ptr () -> IO b) -> IO b\nobjToPtr obj f = do\n sPtr <- newStablePtr obj\n res <- f $ castStablePtrToPtr sPtr\n return res\n\nwithHsQMLClassHandle :: HsQMLClassHandle -> (Ptr HsQMLClassHandle -> IO b) -> IO b\n{#fun unsafe hsqml_create_object as ^\n {objToPtr* `a',\n withHsQMLClassHandle* `HsQMLClassHandle'} ->\n `HsQMLObjectHandle' id #}\n\nptrToObj :: Ptr () -> IO a\nptrToObj =\n deRefStablePtr . castPtrToStablePtr\n\n{#fun unsafe hsqml_get_haskell as ^\n {id `HsQMLObjectHandle'} ->\n `a' ptrToObj* #}\n\nofDynamicMetaObject :: CUInt\nofDynamicMetaObject = 0x01\n\nmfAccessPrivate, mfAccessProtected, mfAccessPublic, mfAccessMask,\n mfMethodMethod, mfMethodSignal, mfMethodSlot, mfMethodConstructor,\n mfMethodTypeMask, mfMethodCompatibility, mfMethodCloned, mfMethodScriptable\n :: CUInt\nmfAccessPrivate = 0x00\nmfAccessProtected = 0x01\nmfAccessPublic = 0x02\nmfAccessMask = 0x03\nmfMethodMethod = 0x00\nmfMethodSignal = 0x04\nmfMethodSlot = 0x08\nmfMethodConstructor = 0x0c\nmfMethodTypeMask = 0x0c\nmfMethodCompatibility = 0x10\nmfMethodCloned = 0x20\nmfMethodScriptable = 0x40\n\npfInvalid, pfReadable, pfWritable, pfResettable, pfEnumOrFlag, pfStdCppSet,\n pfConstant, pfFinal, pfDesignable, pfResolveDesignable, pfScriptable,\n pfResolveScriptable, pfStored, pfResolveStored, pfEditable,\n pfResolveEditable, pfUser, pfResolveUser, pfNotify :: CUInt\npfInvalid = 0x00000000\npfReadable = 0x00000001\npfWritable = 0x00000002\npfResettable = 0x00000004\npfEnumOrFlag = 0x00000008\npfStdCppSet = 0x00000100\npfConstant = 0x00000400\npfFinal = 0x00000800\npfDesignable = 0x00001000\npfResolveDesignable = 0x00002000\npfScriptable = 0x00004000\npfResolveScriptable = 0x00008000\npfStored = 0x00010000\npfResolveStored = 0x00020000\npfEditable = 0x00040000\npfResolveEditable = 0x00080000\npfUser = 0x00100000\npfResolveUser = 0x00200000\npfNotify = 0x00400000\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"99e2f2f1bf674799c809bd9d473531a0cd52b8da","subject":"Fix the get side of all container child attributes. It was accidentally calling 'set' rather than 'get'. doh! :-)","message":"Fix the get side of all container child attributes.\nIt was accidentally calling 'set' rather than 'get'. doh! :-)\n","repos":"vincenthz\/webkit","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":"f9526bb56f7628f7b2d89f98c34bfba3ec426e1e","subject":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO","message":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO\n\ndarcs-hash:20081017185905-21862-ff108916af9d90432a21699a6134e550f62419a7.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 ) 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\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\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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"203b5a4d405346847495b4e7fb5f67ccbfb35ead","subject":"Correct arguments of a finally statement.","message":"Correct arguments of a finally statement.\n\nThis code has obviously never been tested. Thanks to Bertram Felgenhauer to spot this.\n\ndarcs-hash:20090417143511-e5ac5-1f71b04e8d52eee9c8e856ff7aee559ba2b40931.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gnomevfs\/System\/Gnome\/VFS\/Marshal.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Marshal.chs","new_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- 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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Marshal (\n \n cToEnum,\n cFromEnum,\n cToBool,\n cFromBool,\n cToFlags,\n cFromFlags,\n genericResultMarshal,\n voidResultMarshal,\n newObjectResultMarshal,\n volumeOpCallbackMarshal\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport Data.Dynamic\nimport System.Glib.FFI\nimport System.Glib.Flags (Flags, toFlags, fromFlags)\nimport System.Glib.UTFString (peekUTFString)\n{#import System.Gnome.VFS.Types#}\nimport System.Gnome.VFS.Error\nimport Prelude hiding (error)\n\ncToEnum :: (Integral a, Enum b) => a -> b\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum a, Integral b) => a -> b\ncFromEnum = fromIntegral . fromEnum\n\ncToBool :: Integral a => a -> Bool\ncToBool = toBool . fromIntegral\n\ncFromBool :: Integral a => Bool -> a\ncFromBool = fromIntegral . fromBool\n\ncToFlags :: (Integral a, Flags b) => a -> [b]\ncToFlags = toFlags . fromIntegral\n\ncFromFlags :: (Flags a, Integral b) => [a] -> b\ncFromFlags = fromIntegral . fromFlags\n\ngenericResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO a\n -> IO b\n -> IO a\ngenericResultMarshal cAction cSuccessAction cFailureAction =\n do result <- liftM cToEnum $ cAction\n case result of\n Ok -> cSuccessAction\n errorCode -> do cFailureAction\n error result\n\nvoidResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO ()\nvoidResultMarshal cAction =\n genericResultMarshal cAction (return ()) (return ())\n\nnewObjectResultMarshal :: (ForeignPtr obj -> obj)\n -> (Ptr (Ptr obj) -> IO {# type GnomeVFSResult #})\n -> IO obj\nnewObjectResultMarshal objConstructor cNewObj =\n alloca $ \\cObjPtr ->\n do poke cObjPtr nullPtr\n genericResultMarshal (cNewObj cObjPtr)\n (do cObj <- peek cObjPtr\n assert (cObj \/= nullPtr) $ return ()\n newObj <- newForeignPtr_ cObj\n return $ objConstructor newObj)\n (do cObj <- peek cObjPtr\n assert (cObj == nullPtr) $ return ())\n\nvolumeOpCallbackMarshal :: VolumeOpSuccessCallback\n -> VolumeOpFailureCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\nvolumeOpCallbackMarshal successCallback failureCallback =\n let cCallback :: CVolumeOpCallback\n cCallback cSucceeded cError cDetailedError cUserData =\n let succeeded = cToBool cSucceeded\n cCallbackFunPtr = castPtrToFunPtr cUserData\n in (flip finally) (freeHaskellFunPtr cCallbackFunPtr) $\n if succeeded\n then assert (and [cError == nullPtr, cDetailedError == nullPtr]) $\n successCallback\n else assert (and [cError \/= nullPtr, cDetailedError \/= nullPtr]) $\n do error <- peekUTFString cError\n detailedError <- peekUTFString cDetailedError\n failureCallback error detailedError\n in makeVolumeOpCallback cCallback\nforeign import ccall safe \"wrapper\"\n makeVolumeOpCallback :: CVolumeOpCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\n","old_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- 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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Marshal (\n \n cToEnum,\n cFromEnum,\n cToBool,\n cFromBool,\n cToFlags,\n cFromFlags,\n genericResultMarshal,\n voidResultMarshal,\n newObjectResultMarshal,\n volumeOpCallbackMarshal\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport Data.Dynamic\nimport System.Glib.FFI\nimport System.Glib.Flags (Flags, toFlags, fromFlags)\nimport System.Glib.UTFString (peekUTFString)\n{#import System.Gnome.VFS.Types#}\nimport System.Gnome.VFS.Error\nimport Prelude hiding (error)\n\ncToEnum :: (Integral a, Enum b) => a -> b\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum a, Integral b) => a -> b\ncFromEnum = fromIntegral . fromEnum\n\ncToBool :: Integral a => a -> Bool\ncToBool = toBool . fromIntegral\n\ncFromBool :: Integral a => Bool -> a\ncFromBool = fromIntegral . fromBool\n\ncToFlags :: (Integral a, Flags b) => a -> [b]\ncToFlags = toFlags . fromIntegral\n\ncFromFlags :: (Flags a, Integral b) => [a] -> b\ncFromFlags = fromIntegral . fromFlags\n\ngenericResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO a\n -> IO b\n -> IO a\ngenericResultMarshal cAction cSuccessAction cFailureAction =\n do result <- liftM cToEnum $ cAction\n case result of\n Ok -> cSuccessAction\n errorCode -> do cFailureAction\n error result\n\nvoidResultMarshal :: IO {# type GnomeVFSResult #}\n -> IO ()\nvoidResultMarshal cAction =\n genericResultMarshal cAction (return ()) (return ())\n\nnewObjectResultMarshal :: (ForeignPtr obj -> obj)\n -> (Ptr (Ptr obj) -> IO {# type GnomeVFSResult #})\n -> IO obj\nnewObjectResultMarshal objConstructor cNewObj =\n alloca $ \\cObjPtr ->\n do poke cObjPtr nullPtr\n genericResultMarshal (cNewObj cObjPtr)\n (do cObj <- peek cObjPtr\n assert (cObj \/= nullPtr) $ return ()\n newObj <- newForeignPtr_ cObj\n return $ objConstructor newObj)\n (do cObj <- peek cObjPtr\n assert (cObj == nullPtr) $ return ())\n\nvolumeOpCallbackMarshal :: VolumeOpSuccessCallback\n -> VolumeOpFailureCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\nvolumeOpCallbackMarshal successCallback failureCallback =\n let cCallback :: CVolumeOpCallback\n cCallback cSucceeded cError cDetailedError cUserData =\n let succeeded = cToBool cSucceeded\n cCallbackFunPtr = castPtrToFunPtr cUserData\n in finally (freeHaskellFunPtr cCallbackFunPtr) $\n if succeeded\n then assert (and [cError == nullPtr, cDetailedError == nullPtr]) $\n successCallback\n else assert (and [cError \/= nullPtr, cDetailedError \/= nullPtr]) $\n do error <- peekUTFString cError\n detailedError <- peekUTFString cDetailedError\n failureCallback error detailedError\n in makeVolumeOpCallback cCallback\nforeign import ccall safe \"wrapper\"\n makeVolumeOpCallback :: CVolumeOpCallback\n -> IO {# type GnomeVFSVolumeOpCallback #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"3115462e7605a5d2054bac1bbf58c9703e707488","subject":"Tests've shown that \"wait\" was not working with OpenMPI.","message":"Tests've shown that \"wait\" was not working with OpenMPI.\n\nReason: in OpenMPI, MPI_Request is a pointer to some structure.\nMPI_Wait expected arg of type (MPI_Request*), that is - pointer to\npointer to structure.\n\nHowever, castPtr was silenty casting one pointer to another, wreaking\nhavoc.\n\nFix: extra level of pointerness added as needed. Incidentally, code\nfor \"wait\" is now similar for both implementations (OpenMPI and\nMPICH2) and works (according to tests).\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , getFutureStatus\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\ngetFutureStatus :: Future a -> IO Status\ngetFutureStatus = readMVar . futureStatus\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n s <- peek statusPtr\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n","old_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , getFutureStatus\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\ngetFutureStatus :: Future a -> IO Status\ngetFutureStatus = readMVar . futureStatus\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\n#ifdef MPICH2\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n#else\nwait request =\n alloca $ \\statusPtr -> do\n checkError $ Internal.wait (castPtr request) (castPtr statusPtr)\n peek statusPtr\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e6c49fc7a1b1755aff3294a639107f17321a7ada","subject":"MPICH2: peek\/poke of MPI_Status","message":"MPICH2: peek\/poke of MPI_Status\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#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n <$> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\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#else\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#endif\n poke p x = do\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 {#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#else\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#endif\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_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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6bf5ecb7095abfa8a30da04e480fadfd4c461944","subject":"expose Types and flags constructors in System.GIO.File","message":"expose Types and flags constructors in System.GIO.File\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"21d7d55ef97f39dcdff71fd35e296ef24667e14f","subject":"[project @ 2003-11-02 23:57:07 by as49] Added marshalling functions to create GLists and GSLists.","message":"[project @ 2003-11-02 23:57:07 by as49]\nAdded marshalling functions to create GLists and GSLists.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/glib\/GList.chs","new_file":"gtk\/glib\/GList.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n-- \n-- Created: 19 March 2002\n--\n-- Version $Revision: 1.8 $ from $Date: 2003\/11\/02 23:57:07 $\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-- * Defines functions to extract data from a GList and to produce a GList from\n-- a list of pointers.\n--\n-- * The same for GSList.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n--\nmodule GList(\n ptrToInt,\n GList,\n fromGList,\n toGList,\n GSList,\n readGSList,\n fromGSList,\n fromGSListRev,\n toGSList\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n\n{# context lib=\"g\" prefix=\"g\" #}\n\n{#pointer * GList#}\n{#pointer * GSList#}\n\n-- methods\n\n-- Convert a pointer to an Int.\n--\nptrToInt :: Ptr a -> Int\nptrToInt ptr = minusPtr ptr nullPtr \n\n-- Turn a GList into a list of pointers.\n--\nfromGList :: GList -> IO [Ptr a]\nfromGList glist = do\n glist' <- {#call unsafe list_reverse#} glist\n extractList glist' []\n where\n extractList gl xs\n | gl==nullPtr = return xs\n | otherwise = do\n\tx <- {#get GList.data#} gl\n\tgl' <- {#call unsafe list_delete_link#} gl gl\n\textractList gl' (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers but don't destroy the list.\n--\nreadGSList :: GSList -> IO [Ptr a]\nreadGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#get GSList->next#} gslist\n xs <- readGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers.\n--\nfromGSList :: GSList -> IO [Ptr a]\nfromGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#call unsafe slist_delete_link#} gslist gslist\n xs <- fromGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers and reverse it.\n--\nfromGSListRev :: GSList -> IO [Ptr a]\nfromGSListRev gslist =\n extractList gslist []\n where\n extractList gslist xs\n | gslist==nullPtr = return xs\n | otherwise\t= do\n\tx <- {#get GSList->data#} gslist\n\tgslist' <- {#call unsafe slist_delete_link#} gslist gslist\n\textractList gslist' (castPtr x:xs)\n\n-- Convert an Int into a pointer.\n--\nintToPtr :: Int -> Ptr a\nintToPtr int = plusPtr nullPtr int\n\n\n-- Turn a list of something into a GList.\n--\ntoGList :: [Ptr a] -> IO GList\ntoGList xs = makeList nullPtr xs\n where\n -- makeList :: GList -> [Ptr a] -> IO GList\n makeList current (x:xs) = do\n newHead <- {#call unsafe list_prepend#} current (castPtr x)\n makeList newHead xs\n makeList current [] = return current\n\n-- Turn a list of something into a GSList.\n--\ntoGSList :: [Ptr a] -> IO GSList\ntoGSList xs = makeList nullPtr xs\n where\n -- makeList :: GSList -> [Ptr a] -> IO GSList\n makeList current (x:xs) = do\n newHead <- {#call unsafe slist_prepend#} current (castPtr x)\n makeList newHead xs\n makeList current [] = return current\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Axel Simon\n-- \n-- Created: 19 March 2002\n--\n-- Version $Revision: 1.7 $ from $Date: 2003\/07\/09 22:42:44 $\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-- * Define functions to extract data from a GList and to produce a GList from\n-- a list of pointers.\n--\n-- * Define functions to extract data from a GSList.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Figure out if we ever need to generate a GList.\n--\nmodule GList(\n ptrToInt,\n GList,\n fromGList,\n -- toGList,\n GSList,\n readGSList,\n fromGSList,\n fromGSListRev\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\n\n{# context lib=\"g\" prefix=\"g\" #}\n\n{#pointer * GList#}\n{#pointer * GSList#}\n\n-- methods\n\n-- Convert a pointer to an Int.\n--\nptrToInt :: Ptr a -> Int\nptrToInt ptr = minusPtr ptr nullPtr \n\n-- Turn a GList into a list of pointers.\n--\nfromGList :: GList -> IO [Ptr a]\nfromGList glist = do\n glist' <- {#call unsafe list_reverse#} glist\n extractList glist' []\n where\n extractList gl xs\n | gl==nullPtr = return xs\n | otherwise = do\n\tx <- {#get GList.data#} gl\n\tgl' <- {#call unsafe list_delete_link#} gl gl\n\textractList gl' (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers but don't destroy the list.\n--\nreadGSList :: GSList -> IO [Ptr a]\nreadGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#get GSList->next#} gslist\n xs <- readGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers.\n--\nfromGSList :: GSList -> IO [Ptr a]\nfromGSList gslist\n | gslist==nullPtr = return []\n | otherwise\t = do\n x <- {#get GSList->data#} gslist\n gslist' <- {#call unsafe slist_delete_link#} gslist gslist\n xs <- fromGSList gslist'\n return (castPtr x:xs)\n\n-- Turn a GSList into a list of pointers and reverse it.\n--\nfromGSListRev :: GSList -> IO [Ptr a]\nfromGSListRev gslist =\n extractList gslist []\n where\n extractList gslist xs\n | gslist==nullPtr = return xs\n | otherwise\t= do\n\tx <- {#get GSList->data#} gslist\n\tgslist' <- {#call unsafe slist_delete_link#} gslist gslist\n\textractList gslist' (castPtr x:xs)\n\n-- Convert an Int into a pointer.\n--\nintToPtr :: Int -> Ptr a\nintToPtr int = plusPtr nullPtr int\n\n\n-- Turn a list of something into a GList.\n--\ntoGList :: [a] -> (a -> Ptr b) -> IO GList\ntoGList xs conv = makeList nullPtr xs\n where\n -- makeList :: GList -> [a] -> IO GList\n makeList current (x:xs) = do\n newHead <- {#call unsafe list_prepend#} current ((castPtr.conv) x)\n makeList newHead xs\n makeList current [] = return current\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e8f42f8c5e30150e751f92a0fd0980cf157701d5","subject":"[project @ 2005-10-30 11:56:30 by as49] Fix wrong link.","message":"[project @ 2005-10-30 11:56:30 by as49]\nFix wrong link.\n","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), 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":"caec1cea02bba66b36e061a9b526baf6527d2b24","subject":"Unneeded extensions","message":"Unneeded extensions\n\n[ci skip]\n","repos":"iu-parfunc\/haskell-hpx,iu-parfunc\/haskell-hpx","old_file":"src\/Foreign\/HPX.chs","new_file":"src\/Foreign\/HPX.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE StaticPointers #-}\n\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.HPX\n-- Copyright :\n-- License : BSD\n--\n-- Haskell Bindings for HPX.\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.HPX {-\n(\n Action(..),\n Foreign.HPX.init, initWith,\n registerAction,\n run, shutdown\n)\n -} where\n\nimport Control.Monad (liftM2, unless)\n\nimport Data.Bifunctor (first)\nimport Data.Binary (Binary(..), decode, encode)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BL\nimport Data.ByteString.Unsafe (unsafePackCStringLen, unsafeUseAsCStringLen)\n-- import qualified Data.HVect as HVect (length)\n-- import Data.HVect (HVect, sNatToInt)\nimport Data.Function ((&))\nimport Data.Ix (Ix)\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport Data.IORef\nimport Data.Proxy\n\nimport Foreign\nimport Foreign.C\nimport Foreign.C2HS\n-- import Foreign.HPX.Classes\n-- import Foreign.LibFFI\n\nimport GHC.StaticPtr\n\nimport System.Environment (getProgName, getArgs)\nimport System.Exit (exitFailure)\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport Debug.Trace (traceShowM)\n\n#include \n#include \"wr_hpx_types.h\"\n\n--------------------------------------------------------------------------------\n-- Global Mutable Structures\n--------------------------------------------------------------------------------\n\n-- {-# NOINLINE hpxActionTable #-}\n-- hpxActionTable :: IORef (Map (FunPtr a) Action)\n-- hpxActionTable = unsafePerformIO $ newIORef M.empty\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\ntype Consumer a = forall b. (a -> IO b) -> IO b\n\nnewtype Action a = Action { useAction :: Ptr CAction }\n deriving (Eq, Show)\ntype CAction = {#type hpx_action_t #}\n\ntype ActionHandler = Ptr () -> {# type size_t #} -> IO CInt\n\nforeign import ccall unsafe \"wrapper\"\n newActionHandler :: ActionHandler -> IO (FunPtr ActionHandler)\n\n-- TODO: Figure out best resource-freeing strategy for HPX\nwithFunWrapper :: (a -> IO (FunPtr a)) -> a -> (FunPtr a -> IO b) -> IO b\nwithFunWrapper wrapper hFun f = wrapper hFun >>= f\n\n--------------------------------------------------------------------------------\n-- Initialization\n--------------------------------------------------------------------------------\n\n{-# INLINEABLE init #-}\ninit :: IO [String]\ninit = initWith =<< liftM2 (:) getProgName getArgs\n\ninitWith :: [String] -> IO [String]\ninitWith argv =\n withMany withCString argv $ \\argv' -> -- argv' :: [CString]\n withArray argv' $ \\argv'' -> -- argv'' :: Ptr CString\n with argv'' $ \\argv''' -> do -- argv''' :: Ptr (Ptr CString)\n\n (r, argc) <- hpxInit (length argv) argv'''\n unless (r == 0) $ printHelp >> exitFailure\n x <- peekArray argc =<< peek argv''' -- :: [Ptr CString]\n mapM peekCString x\n\n{#fun unsafe hpx_init as ^\n { withIntConv* `Int' peekIntConv*\n , id `Ptr (Ptr (Ptr CChar))'\n } -> `Int' cIntConv #}\n\n--------------------------------------------------------------------------------\n-- Action Registration\n--------------------------------------------------------------------------------\n\n--Different # of args:\n\n-- {#fun unsafe variadic hpx_register_action[??] as ^\n-- { alloca- `Action' peekAction*\n-- , withCString* `String'\n-- , id `Handler'\n-- } -> `Int' cIntConv #}\n-- where peekAction = fmap Action . peek\n\n{#enum hpx_action_type_t as ActionType\n { HPX_DEFAULT as Default\n , HPX_TASK as Task\n , HPX_INTERRUPT as Interrupt\n , HPX_FUNCTION as Function\n } deriving (Bounded, Eq, Ix, Ord, Read, Show) #}\n\n{#enum define HPXAttribute\n { HPX_ATTR_NONE as NoAttribute\n , HPX_MARSHALLED as Marshalled\n , HPX_PINNED as Pinned\n } deriving (Bounded, Eq, Ix, Ord, Read, Show) #}\n\n-- -- TODO: Convert Int into Enum\n-- {#fun unsafe variadic hpx_register_action[??] as ^\n-- {\n-- , cIntConv `Int'\n-- , withCString* `String'\n-- , alloca- `Action' peekAction*\n-- , id `Handler'\n-- } -> `Int' cIntConv #}\n-- where peekAction = fmap Action . peek\n\n-- foreign import ccall \"hpx.h &hpx_register_action\"\n-- hpx_register_action_fun :: FunPtr ()\n--\n-- foreign import ccall \"hpx.h &_hpx_run\"\n-- hpx_run_fun :: FunPtr ()\n--\n-- hpx_register_action :: forall f.\n-- ( All FFIType (HMap Proxy (ArgList f))\n-- , FFIFunction f\n-- , FunReturnType f ~ CInt\n-- , HVectSing (HMap Proxy (ArgList f))\n-- ) => ActionType -> Int -> String -> f -> IO (CInt, Action f)\n-- hpx_register_action actionType attr key actionHandler = alloca $ \\(idPtr :: Ptr CAction) -> do\n-- let hArgs = hSing :: HVect (HMap Proxy (ArgList f))\n-- numArgs = fromIntegral . sNatToInt $ HVect.length hArgs\n-- h <- wrapFunPtr actionHandler\n-- rc <- callFFI hpx_register_action_fun retCInt $\n-- [ toArg (fromIntegral $ fromEnum actionType :: {#type hpx_action_type_t #})\n-- , argCUInt (fromIntegral attr)\n-- , argString key\n-- , argPtr idPtr\n-- , argFunPtr h\n-- , argCInt numArgs\n-- ] ++ map argPtr (toFFITypeList hArgs)\n-- -- actionID <- fmap Action $ peek idPtr\n-- return (rc, Action idPtr)\n--\n-- registerAction :: forall f.\n-- ( All FFIType (HMap Proxy (ArgList f))\n-- , FFIFunction f\n-- , FunReturnType f ~ CInt\n-- , HVectSing (HMap Proxy (ArgList f))\n-- ) => ActionType -> Int -> String -> f -> IO (Action f)\n-- registerAction actionType attr key = fmap snd . hpx_register_action actionType attr key\n\n{#fun pure wr_hpx_pointer as hpxPointer {} -> `Ptr ()' #}\n{#fun pure wr_hpx_size as hpxSize {} -> `Ptr ()' #}\n\n{#fun unsafe variadic hpx_register_action[hpx_type_t, hpx_type_t] as ^\n { `ActionType'\n , `HPXAttribute'\n , `String'\n , alloca- `Action a' Action\n , withHandler* `ActionHandler'\n , two- `Int'\n , pointerT- `Ptr ()'\n , sizeT- `Ptr ()'\n } -> `Int' #}\n where\n pointerT, sizeT :: Consumer (Ptr ())\n pointerT = (hpxPointer &)\n sizeT = (hpxSize &)\n\n withHandler :: ActionHandler -> (FunPtr ActionHandler -> IO a) -> IO a\n withHandler = withFunWrapper newActionHandler\n\n-- TODO: Remove the need to pass an explicit String ID\nregisterAction :: Binary a\n => ActionType\n -> HPXAttribute\n -> String\n -> StaticPtr (a -> IO ())\n -> IO (Action a)\nregisterAction actionT attr key clbk = do\n -- TODO: Figure out what error codes can be produced here\n (_r, a) <- hpxRegisterAction actionT attr key c_callback\n return a\n where\n c_callback :: ActionHandler\n c_callback cstr len = do\n bs <- unsafePackCStringLen (castPtr cstr, fromIntegral len)\n 0 <$ deRefStaticPtr clbk (decode (BL.fromStrict bs))\n\n-- {-# INLINEABLE registerAction#-}\n-- registerAction :: String -> (Ptr () -> IO CInt) -> IO ()\n-- registerAction s p = do\n-- ptr <- wrap p\n-- (_r, act) <- hpxRegisterAction s ptr\n-- -- TODO throw exception on '_r'\n-- modifyIORef hpxActionTable (M.insert ptr act)\n-- putStrLn $ \"Registered action pointer: \" ++ show ptr ++ \" with key: \" ++ show s\n\n--------------------------------------------------------------------------------\n-- Runtime Calls\n--------------------------------------------------------------------------------\n\n-- {#fun _hpx_run as ^\n-- { withAction* `Action'\n-- , cIntConv `Int'\n-- -- , id `Ptr ()'\n-- } -> `Int' cIntConv #}\n-- where\n-- withAction = with . useAction\n\n-- run :: (Ptr () -> IO CInt) -> Ptr () -> Int -> IO Int\n-- run p _args size = do\n-- tbl <- readIORef hpxActionTable\n-- ptr <- wrap p\n-- case M.lookup ptr tbl of\n-- Nothing -> error $ \"ERROR: Invalid action pointer: \" ++ show ptr\n-- Just action -> hpxRun action size -- _args\n\n{#fun variadic _hpx_run[const char*, const int] as ^\n { useAction `Action a' Action\n , two- `Int'\n , withCStringLenConv* `BS.ByteString'&\n } -> `Int' #}\n where\n withCStringLenConv :: BS.ByteString -> Consumer (CString, CInt)\n withCStringLenConv bs f = unsafeUseAsCStringLen bs $ \\(cstr, len) -> f (cstr, fromIntegral len)\n\nrun :: Binary a => Action a -> a -> IO (Int, Action a)\nrun action = fmap (first fromIntegral) . hpxRun action . BL.toStrict . encode\n\n-- hpx_run :: ( ToHVect args\n-- , All ToArg (HVectOf args)\n-- , ArgList f ~ HVectOf args\n-- ) => Action f -> args -> IO CInt\n-- hpx_run action args =\n-- let hArgs = hFromTuple args\n-- numArgs = fromIntegral . sNatToInt $ HVect.length hArgs\n-- in callFFI hpx_run_fun retCInt $ [argPtr (useAction action), argCInt numArgs] ++ toArgList hArgs\n--\n-- run :: ( ToHVect args\n-- , All ToArg (HVectOf args)\n-- , ArgList f ~ HVectOf args\n-- ) => Action f -> args -> IO ()\n-- run action = void . hpx_run action\n\n{#fun unsafe hpx_print_help as ^ {} -> `()' #}\n\nprintHelp :: IO ()\nprintHelp = hpxPrintHelp\n\n{#fun unsafe hpx_finalize as ^ {} -> `()' #}\n\nfinalize :: IO ()\nfinalize = hpxFinalize\n\n{#fun hpx_exit as ^\n { cIntConv `Int'\n } -> `()' #}\n\nexit :: Int -> IO ()\nexit = hpxExit\n\ntwo :: Num n => Consumer n\ntwo = (2 &)\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE StaticPointers #-}\n{-# LANGUAGE TypeFamilies #-}\n\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.HPX\n-- Copyright :\n-- License : BSD\n--\n-- Haskell Bindings for HPX.\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.HPX {-\n(\n Action(..),\n Foreign.HPX.init, initWith,\n registerAction,\n run, shutdown\n)\n -} where\n\nimport Control.Monad (liftM2, unless)\n\nimport Data.Bifunctor (first)\nimport Data.Binary (Binary(..), decode, encode)\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BL\nimport Data.ByteString.Unsafe (unsafePackCStringLen, unsafeUseAsCStringLen)\n-- import qualified Data.HVect as HVect (length)\n-- import Data.HVect (HVect, sNatToInt)\nimport Data.Function ((&))\nimport Data.Ix (Ix)\nimport qualified Data.Map as M\nimport Data.Map (Map)\nimport Data.IORef\nimport Data.Proxy\n\nimport Foreign\nimport Foreign.C\nimport Foreign.C2HS\n-- import Foreign.HPX.Classes\n-- import Foreign.LibFFI\n\nimport GHC.StaticPtr\n\nimport System.Environment (getProgName, getArgs)\nimport System.Exit (exitFailure)\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport Debug.Trace (traceShowM)\n\n#include \n#include \"wr_hpx_types.h\"\n\n--------------------------------------------------------------------------------\n-- Global Mutable Structures\n--------------------------------------------------------------------------------\n\n-- {-# NOINLINE hpxActionTable #-}\n-- hpxActionTable :: IORef (Map (FunPtr a) Action)\n-- hpxActionTable = unsafePerformIO $ newIORef M.empty\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\ntype Consumer a = forall b. (a -> IO b) -> IO b\n\nnewtype Action a = Action { useAction :: Ptr CAction }\n deriving (Eq, Show)\ntype CAction = {#type hpx_action_t #}\n\ntype ActionHandler = Ptr () -> {# type size_t #} -> IO CInt\n\nforeign import ccall unsafe \"wrapper\"\n newActionHandler :: ActionHandler -> IO (FunPtr ActionHandler)\n\n-- TODO: Figure out best resource-freeing strategy for HPX\nwithFunWrapper :: (a -> IO (FunPtr a)) -> a -> (FunPtr a -> IO b) -> IO b\nwithFunWrapper wrapper hFun f = wrapper hFun >>= f\n\n--------------------------------------------------------------------------------\n-- Initialization\n--------------------------------------------------------------------------------\n\n{-# INLINEABLE init #-}\ninit :: IO [String]\ninit = initWith =<< liftM2 (:) getProgName getArgs\n\ninitWith :: [String] -> IO [String]\ninitWith argv =\n withMany withCString argv $ \\argv' -> -- argv' :: [CString]\n withArray argv' $ \\argv'' -> -- argv'' :: Ptr CString\n with argv'' $ \\argv''' -> do -- argv''' :: Ptr (Ptr CString)\n\n (r, argc) <- hpxInit (length argv) argv'''\n unless (r == 0) $ printHelp >> exitFailure\n x <- peekArray argc =<< peek argv''' -- :: [Ptr CString]\n mapM peekCString x\n\n{#fun unsafe hpx_init as ^\n { withIntConv* `Int' peekIntConv*\n , id `Ptr (Ptr (Ptr CChar))'\n } -> `Int' cIntConv #}\n\n--------------------------------------------------------------------------------\n-- Action Registration\n--------------------------------------------------------------------------------\n\n--Different # of args:\n\n-- {#fun unsafe variadic hpx_register_action[??] as ^\n-- { alloca- `Action' peekAction*\n-- , withCString* `String'\n-- , id `Handler'\n-- } -> `Int' cIntConv #}\n-- where peekAction = fmap Action . peek\n\n{#enum hpx_action_type_t as ActionType\n { HPX_DEFAULT as Default\n , HPX_TASK as Task\n , HPX_INTERRUPT as Interrupt\n , HPX_FUNCTION as Function\n } deriving (Bounded, Eq, Ix, Ord, Read, Show) #}\n\n{#enum define HPXAttribute\n { HPX_ATTR_NONE as NoAttribute\n , HPX_MARSHALLED as Marshalled\n , HPX_PINNED as Pinned\n } deriving (Bounded, Eq, Ix, Ord, Read, Show) #}\n\n-- -- TODO: Convert Int into Enum\n-- {#fun unsafe variadic hpx_register_action[??] as ^\n-- {\n-- , cIntConv `Int'\n-- , withCString* `String'\n-- , alloca- `Action' peekAction*\n-- , id `Handler'\n-- } -> `Int' cIntConv #}\n-- where peekAction = fmap Action . peek\n\n-- foreign import ccall \"hpx.h &hpx_register_action\"\n-- hpx_register_action_fun :: FunPtr ()\n--\n-- foreign import ccall \"hpx.h &_hpx_run\"\n-- hpx_run_fun :: FunPtr ()\n--\n-- hpx_register_action :: forall f.\n-- ( All FFIType (HMap Proxy (ArgList f))\n-- , FFIFunction f\n-- , FunReturnType f ~ CInt\n-- , HVectSing (HMap Proxy (ArgList f))\n-- ) => ActionType -> Int -> String -> f -> IO (CInt, Action f)\n-- hpx_register_action actionType attr key actionHandler = alloca $ \\(idPtr :: Ptr CAction) -> do\n-- let hArgs = hSing :: HVect (HMap Proxy (ArgList f))\n-- numArgs = fromIntegral . sNatToInt $ HVect.length hArgs\n-- h <- wrapFunPtr actionHandler\n-- rc <- callFFI hpx_register_action_fun retCInt $\n-- [ toArg (fromIntegral $ fromEnum actionType :: {#type hpx_action_type_t #})\n-- , argCUInt (fromIntegral attr)\n-- , argString key\n-- , argPtr idPtr\n-- , argFunPtr h\n-- , argCInt numArgs\n-- ] ++ map argPtr (toFFITypeList hArgs)\n-- -- actionID <- fmap Action $ peek idPtr\n-- return (rc, Action idPtr)\n--\n-- registerAction :: forall f.\n-- ( All FFIType (HMap Proxy (ArgList f))\n-- , FFIFunction f\n-- , FunReturnType f ~ CInt\n-- , HVectSing (HMap Proxy (ArgList f))\n-- ) => ActionType -> Int -> String -> f -> IO (Action f)\n-- registerAction actionType attr key = fmap snd . hpx_register_action actionType attr key\n\n{#fun pure wr_hpx_pointer as hpxPointer {} -> `Ptr ()' #}\n{#fun pure wr_hpx_size as hpxSize {} -> `Ptr ()' #}\n\n{#fun unsafe variadic hpx_register_action[hpx_type_t, hpx_type_t] as ^\n { `ActionType'\n , `HPXAttribute'\n , `String'\n , alloca- `Action a' Action\n , withHandler* `ActionHandler'\n , two- `Int'\n , pointerT- `Ptr ()'\n , sizeT- `Ptr ()'\n } -> `Int' #}\n where\n pointerT, sizeT :: Consumer (Ptr ())\n pointerT = (hpxPointer &)\n sizeT = (hpxSize &)\n\n withHandler :: ActionHandler -> (FunPtr ActionHandler -> IO a) -> IO a\n withHandler = withFunWrapper newActionHandler\n\n-- TODO: Remove the need to pass an explicit String ID\nregisterAction :: Binary a\n => ActionType\n -> HPXAttribute\n -> String\n -> StaticPtr (a -> IO ())\n -> IO (Action a)\nregisterAction actionT attr key clbk = do\n -- TODO: Figure out what error codes can be produced here\n (_r, a) <- hpxRegisterAction actionT attr key c_callback\n return a\n where\n c_callback :: ActionHandler\n c_callback cstr len = do\n bs <- unsafePackCStringLen (castPtr cstr, fromIntegral len)\n 0 <$ deRefStaticPtr clbk (decode (BL.fromStrict bs))\n\n-- {-# INLINEABLE registerAction#-}\n-- registerAction :: String -> (Ptr () -> IO CInt) -> IO ()\n-- registerAction s p = do\n-- ptr <- wrap p\n-- (_r, act) <- hpxRegisterAction s ptr\n-- -- TODO throw exception on '_r'\n-- modifyIORef hpxActionTable (M.insert ptr act)\n-- putStrLn $ \"Registered action pointer: \" ++ show ptr ++ \" with key: \" ++ show s\n\n--------------------------------------------------------------------------------\n-- Runtime Calls\n--------------------------------------------------------------------------------\n\n-- {#fun _hpx_run as ^\n-- { withAction* `Action'\n-- , cIntConv `Int'\n-- -- , id `Ptr ()'\n-- } -> `Int' cIntConv #}\n-- where\n-- withAction = with . useAction\n\n-- run :: (Ptr () -> IO CInt) -> Ptr () -> Int -> IO Int\n-- run p _args size = do\n-- tbl <- readIORef hpxActionTable\n-- ptr <- wrap p\n-- case M.lookup ptr tbl of\n-- Nothing -> error $ \"ERROR: Invalid action pointer: \" ++ show ptr\n-- Just action -> hpxRun action size -- _args\n\n{#fun variadic _hpx_run[const char*, const int] as ^\n { useAction `Action a' Action\n , two- `Int'\n , withCStringLenConv* `BS.ByteString'&\n } -> `Int' #}\n where\n withCStringLenConv :: BS.ByteString -> Consumer (CString, CInt)\n withCStringLenConv bs f = unsafeUseAsCStringLen bs $ \\(cstr, len) -> f (cstr, fromIntegral len)\n\nrun :: Binary a => Action a -> a -> IO (Int, Action a)\nrun action = fmap (first fromIntegral) . hpxRun action . BL.toStrict . encode\n\n-- hpx_run :: ( ToHVect args\n-- , All ToArg (HVectOf args)\n-- , ArgList f ~ HVectOf args\n-- ) => Action f -> args -> IO CInt\n-- hpx_run action args =\n-- let hArgs = hFromTuple args\n-- numArgs = fromIntegral . sNatToInt $ HVect.length hArgs\n-- in callFFI hpx_run_fun retCInt $ [argPtr (useAction action), argCInt numArgs] ++ toArgList hArgs\n--\n-- run :: ( ToHVect args\n-- , All ToArg (HVectOf args)\n-- , ArgList f ~ HVectOf args\n-- ) => Action f -> args -> IO ()\n-- run action = void . hpx_run action\n\n{#fun unsafe hpx_print_help as ^ {} -> `()' #}\n\nprintHelp :: IO ()\nprintHelp = hpxPrintHelp\n\n{#fun unsafe hpx_finalize as ^ {} -> `()' #}\n\nfinalize :: IO ()\nfinalize = hpxFinalize\n\n{#fun hpx_exit as ^\n { cIntConv `Int'\n } -> `()' #}\n\nexit :: Int -> IO ()\nexit = hpxExit\n\ntwo :: Num n => Consumer n\ntwo = (2 &)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"44128d347001968fd8ba0cd0ea694401a719b2d7","subject":"gio: S.G.File: specify module exports","message":"gio: S.G.File: specify module exports\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/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":"e8f2ec5537dd9676a36f978f753b941ea41398f1","subject":"Retain the ByteBuffer in toLazyByteString.","message":"Retain the ByteBuffer in toLazyByteString.\n\nThe GHC does not know about the relationship of the ByteBuffer and the\nByteBufferReader. We need to explicitly retain the ByteBuffer while\nwe're reading its slices.\n\nIf we don't retain the ByteBuffer it may be GCed while or before we read\nits data.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Lib\/ByteBuffer.chs","new_file":"src\/Network\/Grpc\/Lib\/ByteBuffer.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 ForeignFunctionInterface #-}\nmodule Network.Grpc.Lib.ByteBuffer\n ( CByteBuffer\n , fromByteString\n , addBBFinalizer\n , toLazyByteString\n\n , CByteBufferReader\n ) where\n\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\n\nimport Control.Exception (bracket)\n\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport qualified Data.ByteString.Lazy as L\n\n#include \n#include \n#include \"hs_byte_buffer.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata CByteBuffer\n{#pointer *byte_buffer as ByteBuffer foreign -> CByteBuffer#}\ndata CByteBufferReader\n{#pointer *byte_buffer_reader as ByteBufferReader -> CByteBufferReader#}\n\ndata CSlice\n{#pointer *gpr_slice as Slice -> CSlice#}\n\nfromByteString :: ByteString -> IO ByteBuffer\nfromByteString = hsRawByteBufferCreate\n\nwithByteString :: ByteString -> ((Ptr CChar, CULong) -> IO a) -> IO a\nwithByteString bs act = do\n let (fPtr, offset, len) = B.toForeignPtr bs\n withForeignPtr fPtr $ \\ptr -> act (ptr `plusPtr` offset, fromIntegral len)\n\n{#fun unsafe hs_raw_byte_buffer_create as ^\n {withByteString* `ByteString'&} -> `ByteBuffer' addBBFinalizer* #}\n\naddBBFinalizer :: Ptr CByteBuffer -> IO ByteBuffer\naddBBFinalizer bb = newForeignPtr grpc_byte_buffer_destroy bb\n\nforeign import ccall \"Network\/Grpc\/Core\/ByteBuffer.chs.h &grpc_byte_buffer_destroy\"\n grpc_byte_buffer_destroy :: FinalizerPtr CByteBuffer\n\ntoByteString :: Slice -> IO ByteString\ntoByteString slice = do\n refcount <- {#get gpr_slice->refcount#} slice\n if refcount == nullPtr\n then fromInlined\n else fromRefcounted\n where\n fromInlined = do\n len <- {#get gpr_slice->data.inlined.length#} slice\n ptr <- {#get gpr_slice->data.inlined.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n fromRefcounted = do\n len <- {#get gpr_slice->data.refcounted.length#} slice\n ptr <- {#get gpr_slice->data.refcounted.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n\ntoLazyByteString :: ByteBuffer -> IO L.ByteString\ntoLazyByteString bb = withForeignPtr bb $ \\_ -> do\n bracket\n (byteBufferReaderInit bb)\n (byteBufferReaderDestroy)\n (\\bbr -> fmap L.fromChunks (go bbr []))\n where\n go bbr acc = do\n (tag, slice) <- byteBufferReaderNext bbr\n case tag of\n 0 -> return $ reverse acc\n _ -> do\n bs <- toByteString slice\n go bbr (bs:acc)\n\n{#fun unsafe byte_buffer_reader_init as ^\n {allocaByteBufferReader- `ByteBufferReader' id, `ByteBuffer'} -> `()' #}\n\nallocaSlice :: (Slice -> IO a) -> IO a\nallocaSlice act = do\n allocaBytes {#sizeof gpr_slice#} $ \\p -> act p\n\nallocaByteBufferReader :: (ByteBufferReader -> IO a) -> IO a\nallocaByteBufferReader act = do\n allocaBytes {#sizeof grpc_byte_buffer_reader#} $ \\p -> act p\n\n{#fun unsafe byte_buffer_reader_next as ^\n {`ByteBufferReader', allocaSlice- `Slice' id} -> `Int' fromIntegral#}\n\n{#fun unsafe byte_buffer_reader_destroy as ^\n {`ByteBufferReader'} -> `()'#}\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 ForeignFunctionInterface #-}\nmodule Network.Grpc.Lib.ByteBuffer\n ( CByteBuffer\n , fromByteString\n , addBBFinalizer\n , toLazyByteString\n\n , CByteBufferReader\n ) where\n\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\n\nimport Control.Exception (bracket)\n\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Internal as B\nimport qualified Data.ByteString.Lazy as L\n\n#include \n#include \n#include \"hs_byte_buffer.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata CByteBuffer\n{#pointer *byte_buffer as ByteBuffer foreign -> CByteBuffer#}\ndata CByteBufferReader\n{#pointer *byte_buffer_reader as ByteBufferReader -> CByteBufferReader#}\n\ndata CSlice\n{#pointer *gpr_slice as Slice -> CSlice#}\n\nfromByteString :: ByteString -> IO ByteBuffer\nfromByteString = hsRawByteBufferCreate\n\nwithByteString :: ByteString -> ((Ptr CChar, CULong) -> IO a) -> IO a\nwithByteString bs act = do\n let (fPtr, offset, len) = B.toForeignPtr bs\n withForeignPtr fPtr $ \\ptr -> act (ptr `plusPtr` offset, fromIntegral len)\n\n{#fun unsafe hs_raw_byte_buffer_create as ^\n {withByteString* `ByteString'&} -> `ByteBuffer' addBBFinalizer* #}\n\naddBBFinalizer :: Ptr CByteBuffer -> IO ByteBuffer\naddBBFinalizer bb = newForeignPtr grpc_byte_buffer_destroy bb\n\nforeign import ccall \"Network\/Grpc\/Core\/ByteBuffer.chs.h &grpc_byte_buffer_destroy\"\n grpc_byte_buffer_destroy :: FinalizerPtr CByteBuffer\n\ntoByteString :: Slice -> IO ByteString\ntoByteString slice = do\n refcount <- {#get gpr_slice->refcount#} slice\n if refcount == nullPtr\n then fromInlined\n else fromRefcounted\n where\n fromInlined = do\n len <- {#get gpr_slice->data.inlined.length#} slice\n ptr <- {#get gpr_slice->data.inlined.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n fromRefcounted = do\n len <- {#get gpr_slice->data.refcounted.length#} slice\n ptr <- {#get gpr_slice->data.refcounted.bytes#} slice\n B.packCStringLen (castPtr ptr, fromIntegral len)\n\ntoLazyByteString :: ByteBuffer -> IO L.ByteString\ntoLazyByteString bb =\n bracket\n (byteBufferReaderInit bb)\n (byteBufferReaderDestroy)\n (\\bbr -> fmap L.fromChunks (go bbr []))\n where\n go bbr acc = do\n (tag, slice) <- byteBufferReaderNext bbr\n case tag of\n 0 -> return $ reverse acc\n _ -> do\n bs <- toByteString slice\n go bbr (bs:acc)\n\n{#fun unsafe byte_buffer_reader_init as ^\n {allocaByteBufferReader- `ByteBufferReader' id, `ByteBuffer'} -> `()' #}\n\nallocaSlice :: (Slice -> IO a) -> IO a\nallocaSlice act = do\n allocaBytes {#sizeof gpr_slice#} $ \\p -> act p\n\nallocaByteBufferReader :: (ByteBufferReader -> IO a) -> IO a\nallocaByteBufferReader act = do\n allocaBytes {#sizeof grpc_byte_buffer_reader#} $ \\p -> act p\n\n{#fun unsafe byte_buffer_reader_next as ^\n {`ByteBufferReader', allocaSlice- `Slice' id} -> `Int' fromIntegral#}\n\n{#fun unsafe byte_buffer_reader_destroy as ^\n {`ByteBufferReader'} -> `()'#}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"2f453d9ea967e8a58f72850345bcc4e16b626b15","subject":"[project @ 2003-01-18 17:44:07 by as49] Move Plug.chs to ..\/embedding. It makes more sense and makes building on Windows easier.","message":"[project @ 2003-01-18 17:44:07 by as49]\nMove Plug.chs to ..\/embedding. It makes more sense and makes building on\nWindows easier.\n\n","repos":"gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gstreamer","old_file":"gtk\/windows\/Plug.chs","new_file":"gtk\/windows\/Plug.chs","new_contents":"","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Plug@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/08\/05 16:41:35 $\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-- * Plug is a window that is to be attached to the window of another\n-- application. If you have managed to receive the @ref type XID@ from\n-- the inviting application you can construct the Plug and add your widgets\n-- to it.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Plug(\n Plug,\n PlugClass,\n castToPlug,\n XID,\n plugNew\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs\t(XID)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\nplugNew :: XID -> IO Plug\nplugNew nw = makeNewObject mkPlug $ liftM castPtr $\n {#call unsafe plug_new#} nw\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"bea1936480a02964bd27954c44517bf2b01b65be","subject":"Converted Comm to abstract datatype","message":"Converted Comm to abstract datatype\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 #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\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,\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare,\n isend, ibsend, issend, irecv, 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 (..),\n Group(MkGroup), 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 (..), StatusPtr,\n Tag, toTag, fromTag, tagVal, anyTag,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\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\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\ninitialized = {# call unsafe Initialized as initialized_ #}\nfinalized = {# call unsafe Finalized as finalized_ #}\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_ #}\ngetProcessorName = {# call unsafe Get_processor_name as getProcessorName_ #}\ngetVersion = {# call unsafe Get_version as getVersion_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #} <$> fromComm\ncommRank = {# call unsafe Comm_rank as commRank_ #} <$> fromComm\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #} <$> fromComm\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #} <$> fromComm\ncommCompare c1 c2 = {# call unsafe Comm_compare as commCompare_ #} (fromComm c1) (fromComm c2)\nprobe s t c = {# call Probe as probe_ #} s t (fromComm c)\nsend b cnt d r t c = {# call unsafe Send as send_ #} b cnt d r t (fromComm c)\nbsend b cnt d r t c = {# call unsafe Bsend as bsend_ #} b cnt d r t (fromComm c)\nssend b cnt d r t c = {# call unsafe Ssend as ssend_ #} b cnt d r t (fromComm c)\nrsend b cnt d r t c = {# call unsafe Rsend as rsend_ #} b cnt d r t (fromComm c)\nrecv b cnt d r t c = {# call unsafe Recv as recv_ #} b cnt d r t (fromComm c)\nisend b cnt d r t c = {# call unsafe Isend as isend_ #} b cnt d r t (fromComm c)\nibsend b cnt d r t c = {# call unsafe Ibsend as ibsend_ #} b cnt d r t (fromComm c)\nissend b cnt d r t c = {# call unsafe Issend as issend_ #} b cnt d r t (fromComm c)\nirecv b cnt d r t c = {# call Irecv as irecv_ #} b cnt d r t (fromComm c)\nbcast b cnt d r c = {# call unsafe Bcast as bcast_ #} b cnt d r (fromComm c)\nbarrier = {# call unsafe Barrier as barrier_ #} <$> fromComm\nwait = {# call unsafe Wait as wait_ #}\nwaitall = {# call unsafe Waitall as waitall_ #}\ntest = {# call unsafe Test as test_ #}\ncancel = {# call unsafe Cancel as cancel_ #}\nscatter sb se st rb re rt r c = {# call unsafe Scatter as scatter_ #} sb se st rb re rt r (fromComm c)\ngather sb se st rb re rt r c = {# call unsafe Gather as gather_ #} sb se st rb re rt r (fromComm c)\nscatterv sb sc sd st rb re rt r c = {# call unsafe Scatterv as scatterv_ #} sb sc sd st rb re rt r (fromComm c)\ngatherv sb se st rb rc rd rt r c = {# call unsafe Gatherv as gatherv_ #} sb se st rb rc rd rt r (fromComm c)\nallgather sb se st rb re rt c = {# call unsafe Allgather as allgather_ #} sb se st rb re rt (fromComm c)\nallgatherv sb se st rb rc rd rt c = {# call unsafe Allgatherv as allgatherv_ #} sb se st rb rc rd rt (fromComm c)\nalltoall sb sc st rb rc rt c = {# call unsafe Alltoall as alltoall_ #} sb sc st rb rc rt (fromComm c)\nalltoallv sb sc sd st rb rc rd rt c = {# call unsafe Alltoallv as alltoallv_ #} sb sc sd st rb rc rd rt (fromComm c)\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce sb rb se st o r c = {# call Reduce as reduce_ #} sb rb se st o r (fromComm c)\nallreduce sb rb se st o c = {# call Allreduce as allreduce_ #} sb rb se st o (fromComm c)\nreduceScatter sb rb cnt t o c = {# call Reduce_scatter as reduceScatter_ #} sb rb cnt t o (fromComm c)\nopCreate = {# call unsafe Op_create as opCreate_ #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\ncommGroup = {# call unsafe Comm_group as commGroup_ #} <$> fromComm\ngroupRank = {# call unsafe Group_rank as groupRank_ #} <$> fromGroup\ngroupSize = {# call unsafe Group_size as groupSize_ #} <$> fromGroup\ngroupUnion g1 g2 = {# call unsafe Group_union as groupUnion_ #} (fromGroup g1) (fromGroup g2)\ngroupIntersection g1 g2 = {# call unsafe Group_intersection as groupIntersection_ #} (fromGroup g1) (fromGroup g2)\ngroupDifference g1 g2 = {# call unsafe Group_difference as groupDifference_ #} (fromGroup g1) (fromGroup g2)\ngroupCompare g1 g2 = {# call unsafe Group_compare as groupCompare_ #} (fromGroup g1) (fromGroup g2)\ngroupExcl g = {# call unsafe Group_excl as groupExcl_ #} (fromGroup g)\ngroupIncl g = {# call unsafe Group_incl as groupIncl_ #} (fromGroup g)\ngroupTranslateRanks g1 s r g2 = {# call unsafe Group_translate_ranks as groupTranslateRanks_ #} (fromGroup g1) s r (fromGroup g2)\ntypeSize = {# call unsafe Type_size as typeSize_ #}\nerrorClass = {# call unsafe Error_class as errorClass_ #}\nerrorString = {# call unsafe Error_string as errorString_ #}\ncommSetErrhandler = {# call unsafe Comm_set_errhandler as commSetErrhandler_ #} <$> fromComm\ncommGetErrhandler = {# call unsafe Comm_get_errhandler as commGetErrhandler_ #} <$> fromComm\nabort = {# call unsafe Abort as abort_ #} <$> fromComm\n\n\ntype Datatype = {# type MPI_Datatype #}\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr Datatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = unsafePerformIO $ peek char_\nwchar = unsafePerformIO $ peek wchar_\nshort = unsafePerformIO $ peek short_\nint = unsafePerformIO $ peek int_\nlong = unsafePerformIO $ peek long_\nlongLong = unsafePerformIO $ peek longLong_\nunsignedChar = unsafePerformIO $ peek unsignedChar_\nunsignedShort = unsafePerformIO $ peek unsignedShort_\nunsigned = unsafePerformIO $ peek unsigned_\nunsignedLong = unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = unsafePerformIO $ peek unsignedLongLong_\nfloat = unsafePerformIO $ peek float_\ndouble = unsafePerformIO $ peek double_\nlongDouble = unsafePerformIO $ peek longDouble_\nbyte = unsafePerformIO $ peek byte_\npacked = unsafePerformIO $ peek packed_\n\n\ntype Errhandler = {# type MPI_Errhandler #}\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr Errhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr Errhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = 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 #}\n\nnewtype Group = MkGroup { fromGroup :: MPIGroup }\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 Operation = {# type MPI_Op #}\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr Operation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: Operation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: Operation\n-- foreign import ccall \"mpi_replace\" replaceOp :: Operation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = unsafePerformIO $ peek maxOp_\nminOp = unsafePerformIO $ peek minOp_\nsumOp = unsafePerformIO $ peek sumOp_\nprodOp = unsafePerformIO $ peek prodOp_\nlandOp = unsafePerformIO $ peek landOp_\nbandOp = unsafePerformIO $ peek bandOp_\nlorOp = unsafePerformIO $ peek lorOp_\nborOp = unsafePerformIO $ peek borOp_\nlxorOp = unsafePerformIO $ peek lxorOp_\nbxorOp = unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\n-- TODO: actually, this should be 32-bit int\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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 Request = {# type MPI_Request #}\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\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#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\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\n-- TODO: actually, this is a 32-bit int, and even less than that.\n-- See section 8 of MPI report about extracting MPI_TAG_UB\n-- and using it here\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\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,\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare,\n isend, ibsend, issend, irecv, 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 (..),\n Group(MkGroup), 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 (..), StatusPtr,\n Tag, toTag, fromTag, tagVal, anyTag,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\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 Comm = {# type MPI_Comm #} \nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr Comm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr Comm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = 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\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\ninitialized = {# call unsafe Initialized as initialized_ #}\nfinalized = {# call unsafe Finalized as finalized_ #}\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_ #}\ngetProcessorName = {# call unsafe Get_processor_name as getProcessorName_ #}\ngetVersion = {# call unsafe Get_version as getVersion_ #}\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_ #}\nwaitall = {# call unsafe Waitall as waitall_ #}\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_ #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce = {# call Reduce as reduce_ #}\nallreduce = {# call Allreduce as allreduce_ #}\nreduceScatter = {# call Reduce_scatter as reduceScatter_ #}\nopCreate = {# call unsafe Op_create as opCreate_ #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\ncommGroup = {# call unsafe Comm_group as commGroup_ #}\ngroupRank = {# call unsafe Group_rank as groupRank_ #} <$> fromGroup\ngroupSize = {# call unsafe Group_size as groupSize_ #} <$> fromGroup\ngroupUnion g1 g2 = {# call unsafe Group_union as groupUnion_ #} (fromGroup g1) (fromGroup g2)\ngroupIntersection g1 g2 = {# call unsafe Group_intersection as groupIntersection_ #} (fromGroup g1) (fromGroup g2)\ngroupDifference g1 g2 = {# call unsafe Group_difference as groupDifference_ #} (fromGroup g1) (fromGroup g2)\ngroupCompare g1 g2 = {# call unsafe Group_compare as groupCompare_ #} (fromGroup g1) (fromGroup g2)\ngroupExcl g = {# call unsafe Group_excl as groupExcl_ #} (fromGroup g)\ngroupIncl g = {# call unsafe Group_incl as groupIncl_ #} (fromGroup g)\ngroupTranslateRanks g1 s r g2 = {# call unsafe Group_translate_ranks as groupTranslateRanks_ #} (fromGroup g1) s r (fromGroup g2)\ntypeSize = {# call unsafe Type_size as typeSize_ #}\nerrorClass = {# call unsafe Error_class as errorClass_ #}\nerrorString = {# call unsafe Error_string as errorString_ #}\ncommSetErrhandler = {# call unsafe Comm_set_errhandler as commSetErrhandler_ #}\ncommGetErrhandler = {# call unsafe Comm_get_errhandler as commGetErrhandler_ #}\nabort = {# call unsafe Abort as abort_ #}\n\n\ntype Datatype = {# type MPI_Datatype #}\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr Datatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr Datatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = unsafePerformIO $ peek char_\nwchar = unsafePerformIO $ peek wchar_\nshort = unsafePerformIO $ peek short_\nint = unsafePerformIO $ peek int_\nlong = unsafePerformIO $ peek long_\nlongLong = unsafePerformIO $ peek longLong_\nunsignedChar = unsafePerformIO $ peek unsignedChar_\nunsignedShort = unsafePerformIO $ peek unsignedShort_\nunsigned = unsafePerformIO $ peek unsigned_\nunsignedLong = unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = unsafePerformIO $ peek unsignedLongLong_\nfloat = unsafePerformIO $ peek float_\ndouble = unsafePerformIO $ peek double_\nlongDouble = unsafePerformIO $ peek longDouble_\nbyte = unsafePerformIO $ peek byte_\npacked = unsafePerformIO $ peek packed_\n\n\ntype Errhandler = {# type MPI_Errhandler #}\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr Errhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr Errhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = 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 #}\n\nnewtype Group = MkGroup { fromGroup :: MPIGroup }\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 Operation = {# type MPI_Op #}\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr Operation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr Operation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: Operation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: Operation\n-- foreign import ccall \"mpi_replace\" replaceOp :: Operation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = unsafePerformIO $ peek maxOp_\nminOp = unsafePerformIO $ peek minOp_\nsumOp = unsafePerformIO $ peek sumOp_\nprodOp = unsafePerformIO $ peek prodOp_\nlandOp = unsafePerformIO $ peek landOp_\nbandOp = unsafePerformIO $ peek bandOp_\nlorOp = unsafePerformIO $ peek lorOp_\nborOp = unsafePerformIO $ peek borOp_\nlxorOp = unsafePerformIO $ peek lxorOp_\nbxorOp = unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\n-- TODO: actually, this should be 32-bit int\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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 Request = {# type MPI_Request #}\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\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#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\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\n-- TODO: actually, this is a 32-bit int, and even less than that.\n-- See section 8 of MPI report about extracting MPI_TAG_UB\n-- and using it here\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Num, Integral, Real)\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9d9119e9e2db701c49ac919e0615defa688a6c96","subject":"Fix ref counting bug in sourceBufferCreateMarker (reported by bwwx in #haskell) The docs say that gtk_source_buffer_create_marker returns a new GtkSourceMarker, owned by the buffer. So we need to ref the object, so we should use makeGObject rather than constructNewGObject.","message":"Fix ref counting bug in sourceBufferCreateMarker\n(reported by bwwx in #haskell)\nThe docs say that gtk_source_buffer_create_marker returns a new\nGtkSourceMarker, owned by the buffer. So we need to ref the object, so we\nshould use makeGObject rather than constructNewGObject.\n","repos":"vincenthz\/webkit","old_file":"sourceview\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"sourceview\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 15 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetCheckBrackets,\n sourceBufferGetCheckBrackets,\n sourceBufferSetBracketsMatchStyle,\n sourceBufferSetHighlight,\n sourceBufferGetHighlight,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetEscapeChar,\n sourceBufferGetEscapeChar,\n sourceBufferCanUndo,\n sourceBufferCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateMarker,\n sourceBufferMoveMarker,\n sourceBufferDeleteMarker,\n sourceBufferGetMarker,\n sourceBufferGetMarkersInRegion,\n sourceBufferGetFirstMarker,\n sourceBufferGetLastMarker,\n sourceBufferGetIterAtMarker,\n sourceBufferGetNextMarker,\n sourceBufferGetPrevMarker\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\t\t(fromGSList)\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.SourceView.SourceTagStyle\nimport Graphics.UI.Gtk.SourceView.SourceMarker\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'SourceTagTable'.\n--\nsourceBufferNew :: Maybe SourceTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkSourceTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetCheckBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetCheckBrackets sb newVal =\n {#call unsafe source_buffer_set_check_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetCheckBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetCheckBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_check_brackets#} sb\n\n-- | \n--\nsourceBufferSetBracketsMatchStyle :: SourceBuffer -> SourceTagStyle -> IO () \nsourceBufferSetBracketsMatchStyle sb ts =\n alloca $ \\tsPtr -> do\n poke tsPtr ts\n {#call unsafe source_buffer_set_bracket_match_style#} sb (castPtr tsPtr)\n\n-- | \n--\nsourceBufferSetHighlight :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlight sb newVal =\n {#call unsafe source_buffer_set_highlight#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlight :: SourceBuffer -> IO Bool \nsourceBufferGetHighlight sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetEscapeChar :: SourceBuffer -> Char -> IO ()\nsourceBufferSetEscapeChar sb char =\n {#call unsafe source_buffer_set_escape_char#} sb ((toEnum . fromEnum) char)\n \n-- | \n--\nsourceBufferGetEscapeChar :: SourceBuffer -> IO Char\nsourceBufferGetEscapeChar sb = liftM (toEnum . fromEnum) $\n {#call unsafe source_buffer_get_escape_char#} sb\n\n-- | \n--\nsourceBufferCanUndo :: SourceBuffer -> IO Bool\nsourceBufferCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferCanRedo :: SourceBuffer -> IO Bool\nsourceBufferCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateMarker :: SourceBuffer -- the buffer\n\t\t\t -> Maybe String -- the name of the marker\n\t\t\t -> String -- the type of the marker\n\t\t\t -> TextIter -> IO SourceMarker\nsourceBufferCreateMarker sb name markerType iter =\n makeNewGObject mkSourceMarker $\n maybeWith withCString name $ \\strPtr1 ->\n withCString markerType $ \\strPtr2 ->\n {#call source_buffer_create_marker#} sb strPtr1 strPtr2 iter\n\n-- | \n--\nsourceBufferMoveMarker :: SourceBuffer -> SourceMarker -> TextIter -> IO ()\nsourceBufferMoveMarker sb mark iter =\n {#call source_buffer_move_marker#} sb mark iter\n\n-- | \n--\nsourceBufferDeleteMarker :: SourceBuffer -> SourceMarker -> IO ()\nsourceBufferDeleteMarker sb mark =\n {#call source_buffer_delete_marker#} sb mark\n\n-- | \n--\nsourceBufferGetMarker :: SourceBuffer -> String -> IO (Maybe SourceMarker)\nsourceBufferGetMarker sb name =\n maybeNull (makeNewGObject mkSourceMarker) $\n withCString name $ \\strPtr1 ->\n {#call unsafe source_buffer_get_marker#} sb strPtr1\n\n-- | Returns an \/ordered\/ (by position) list of 'SourceMarker's inside the\n-- region delimited by the two 'TextIter's. The iterators may be in any\n-- order.\n--\nsourceBufferGetMarkersInRegion :: SourceBuffer -> TextIter -> TextIter -> IO [SourceMarker]\nsourceBufferGetMarkersInRegion sb begin end = do\n gList <- {#call unsafe source_buffer_get_markers_in_region#} sb begin end\n wList <- fromGSList gList\n mapM (makeNewGObject mkSourceMarker) (map return wList)\n\n-- | Returns the first (nearest to the top of the buffer) marker.\n--\nsourceBufferGetFirstMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetFirstMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_first_marker#} sb\n\n-- | Returns the last (nearest to the bottom of the buffer) marker.\n--\nsourceBufferGetLastMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetLastMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_last_marker#} sb\n\n-- | \n--\nsourceBufferGetIterAtMarker :: SourceBuffer -> SourceMarker -> IO TextIter\nsourceBufferGetIterAtMarker sb mark = do\n iter <- makeEmptyTextIter\n {#call unsafe source_buffer_get_iter_at_marker#} sb iter mark\n return iter\n\n-- | Returns the nearest marker to the right of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the first one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerNext'.\n--\nsourceBufferGetNextMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetNextMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_next_marker#} sb iter\n\n-- | Returns the nearest marker to the left of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the last one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerPrev'.\n--\nsourceBufferGetPrevMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetPrevMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_prev_marker#} sb iter\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 15 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetCheckBrackets,\n sourceBufferGetCheckBrackets,\n sourceBufferSetBracketsMatchStyle,\n sourceBufferSetHighlight,\n sourceBufferGetHighlight,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetEscapeChar,\n sourceBufferGetEscapeChar,\n sourceBufferCanUndo,\n sourceBufferCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateMarker,\n sourceBufferMoveMarker,\n sourceBufferDeleteMarker,\n sourceBufferGetMarker,\n sourceBufferGetMarkersInRegion,\n sourceBufferGetFirstMarker,\n sourceBufferGetLastMarker,\n sourceBufferGetIterAtMarker,\n sourceBufferGetNextMarker,\n sourceBufferGetPrevMarker\n) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\t\t(fromGSList)\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.SourceView.SourceTagStyle\nimport Graphics.UI.Gtk.SourceView.SourceMarker\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'SourceTagTable'.\n--\nsourceBufferNew :: Maybe SourceTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkSourceTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetCheckBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetCheckBrackets sb newVal =\n {#call unsafe source_buffer_set_check_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetCheckBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetCheckBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_check_brackets#} sb\n\n-- | \n--\nsourceBufferSetBracketsMatchStyle :: SourceBuffer -> SourceTagStyle -> IO () \nsourceBufferSetBracketsMatchStyle sb ts =\n alloca $ \\tsPtr -> do\n poke tsPtr ts\n {#call unsafe source_buffer_set_bracket_match_style#} sb (castPtr tsPtr)\n\n-- | \n--\nsourceBufferSetHighlight :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlight sb newVal =\n {#call unsafe source_buffer_set_highlight#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlight :: SourceBuffer -> IO Bool \nsourceBufferGetHighlight sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetEscapeChar :: SourceBuffer -> Char -> IO ()\nsourceBufferSetEscapeChar sb char =\n {#call unsafe source_buffer_set_escape_char#} sb ((toEnum . fromEnum) char)\n \n-- | \n--\nsourceBufferGetEscapeChar :: SourceBuffer -> IO Char\nsourceBufferGetEscapeChar sb = liftM (toEnum . fromEnum) $\n {#call unsafe source_buffer_get_escape_char#} sb\n\n-- | \n--\nsourceBufferCanUndo :: SourceBuffer -> IO Bool\nsourceBufferCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferCanRedo :: SourceBuffer -> IO Bool\nsourceBufferCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateMarker :: SourceBuffer -- the buffer\n\t\t\t -> Maybe String -- the name of the marker\n\t\t\t -> String -- the type of the marker\n\t\t\t -> TextIter -> IO SourceMarker\nsourceBufferCreateMarker sb name markerType iter =\n constructNewGObject mkSourceMarker $\n maybeWith withCString name $ \\strPtr1 ->\n withCString markerType $ \\strPtr2 ->\n {#call source_buffer_create_marker#} sb strPtr1 strPtr2 iter\n\n-- | \n--\nsourceBufferMoveMarker :: SourceBuffer -> SourceMarker -> TextIter -> IO ()\nsourceBufferMoveMarker sb mark iter =\n {#call source_buffer_move_marker#} sb mark iter\n\n-- | \n--\nsourceBufferDeleteMarker :: SourceBuffer -> SourceMarker -> IO ()\nsourceBufferDeleteMarker sb mark =\n {#call source_buffer_delete_marker#} sb mark\n\n-- | \n--\nsourceBufferGetMarker :: SourceBuffer -> String -> IO (Maybe SourceMarker)\nsourceBufferGetMarker sb name =\n maybeNull (makeNewGObject mkSourceMarker) $\n withCString name $ \\strPtr1 ->\n {#call unsafe source_buffer_get_marker#} sb strPtr1\n\n-- | Returns an \/ordered\/ (by position) list of 'SourceMarker's inside the\n-- region delimited by the two 'TextIter's. The iterators may be in any\n-- order.\n--\nsourceBufferGetMarkersInRegion :: SourceBuffer -> TextIter -> TextIter -> IO [SourceMarker]\nsourceBufferGetMarkersInRegion sb begin end = do\n gList <- {#call unsafe source_buffer_get_markers_in_region#} sb begin end\n wList <- fromGSList gList\n mapM (makeNewGObject mkSourceMarker) (map return wList)\n\n-- | Returns the first (nearest to the top of the buffer) marker.\n--\nsourceBufferGetFirstMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetFirstMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_first_marker#} sb\n\n-- | Returns the last (nearest to the bottom of the buffer) marker.\n--\nsourceBufferGetLastMarker :: SourceBuffer -> IO (Maybe SourceMarker)\nsourceBufferGetLastMarker sb =\n maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_last_marker#} sb\n\n-- | \n--\nsourceBufferGetIterAtMarker :: SourceBuffer -> SourceMarker -> IO TextIter\nsourceBufferGetIterAtMarker sb mark = do\n iter <- makeEmptyTextIter\n {#call unsafe source_buffer_get_iter_at_marker#} sb iter mark\n return iter\n\n-- | Returns the nearest marker to the right of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the first one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerNext'.\n--\nsourceBufferGetNextMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetNextMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_next_marker#} sb iter\n\n-- | Returns the nearest marker to the left of the given iterator.\n-- If there are\n-- multiple markers at the same position, this function will always\n-- return the last one (from the internal linked list), even if\n-- starting the search exactly at its location. You can get the\n-- others using 'sourceMarkerPrev'.\n--\nsourceBufferGetPrevMarker :: SourceBuffer -> TextIter -> IO (Maybe SourceMarker)\nsourceBufferGetPrevMarker sb iter = maybeNull (makeNewGObject mkSourceMarker) $\n {#call unsafe source_buffer_get_prev_marker#} sb iter\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"58fbb4e571017ded0b871270d7755b5051b84132","subject":"Add real Show instances for the C enumeration types","message":"Add real Show instances for the C enumeration types\n","repos":"travitch\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/llvm-analysis,wangxiayang\/llvm-analysis","old_file":"src\/Data\/LLVM\/Private\/Types\/Attributes.chs","new_file":"src\/Data\/LLVM\/Private\/Types\/Attributes.chs","new_contents":"module Data.LLVM.Private.Types.Attributes (\n -- * Types\n ArithFlags(..),\n CmpPredicate(..),\n CallingConvention(..),\n LinkageType(..),\n VisibilityStyle(..),\n ParamAttribute(..),\n FunctionAttribute(..),\n Endian(..),\n DataLayout(..),\n TargetTriple(..),\n AlignSpec(..),\n Assembly(..),\n -- * Values\n defaultDataLayout\n ) where\n\n#include \"c++\/marshal.h\"\n\nimport Control.DeepSeq\nimport Data.ByteString.Char8 ( ByteString, 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\n\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\n\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\n\n\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\n\n\n -- Representing Assembly\ndata Assembly = Assembly !ByteString\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 Endian = EBig\n | ELittle\n deriving (Eq, Ord)\n\ninstance NFData Endian\n\ninstance Show Endian where\n show EBig = \"E\"\n show ELittle = \"e\"\n\n-- Track the ABI alignment and preferred alignment\ndata AlignSpec = AlignSpec !Int !Int\n deriving (Show, Eq, Ord)\n\ninstance NFData AlignSpec where\n rnf a@(AlignSpec i1 i2) = i1 `seq` i2 `seq` a `seq` ()\n\ndata TargetTriple = TargetTriple ByteString\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\ndata DataLayout = DataLayout { endianness :: Endian\n , pointerAlign :: (Int, AlignSpec)\n , intAlign :: [ (Int, AlignSpec) ]\n , vectorAlign :: [ (Int, AlignSpec) ]\n , floatAlign :: [ (Int, AlignSpec) ]\n , aggregateAlign :: [ (Int, AlignSpec) ]\n , stackAlign :: [ (Int, AlignSpec) ]\n , nativeWidths :: [ Int ]\n }\n deriving (Show, Eq)\n\ninstance NFData DataLayout where\n rnf d = endianness d `deepseq` pointerAlign d `deepseq`\n intAlign d `deepseq` vectorAlign d `deepseq`\n floatAlign d `deepseq` aggregateAlign d `deepseq`\n stackAlign d `deepseq` nativeWidths d `deepseq` d `seq` ()\n\n-- Defaults specified by LLVM. I think there can only be one pointer\n-- align specification, though it isn't explicitly stated\ndefaultDataLayout :: DataLayout\ndefaultDataLayout = DataLayout { endianness = EBig\n , pointerAlign = (64, AlignSpec 64 64)\n , intAlign = [ (1, AlignSpec 8 8)\n , (8, AlignSpec 8 8)\n , (16, AlignSpec 16 16)\n , (32, AlignSpec 32 32)\n , (64, AlignSpec 32 64)\n ]\n , vectorAlign = [ (64, AlignSpec 64 64)\n , (128, AlignSpec 128 128)\n ]\n , floatAlign = [ (32, AlignSpec 32 32)\n , (64, AlignSpec 64 64)\n ]\n , aggregateAlign = [ (0, AlignSpec 0 1) ]\n , stackAlign = [ (0, AlignSpec 64 64) ]\n , nativeWidths = [] -- Set.empty\n }\n\n","old_contents":"module Data.LLVM.Private.Types.Attributes (\n -- * Types\n ArithFlags(..),\n CmpPredicate(..),\n CallingConvention(..),\n LinkageType(..),\n VisibilityStyle(..),\n ParamAttribute(..),\n FunctionAttribute(..),\n Endian(..),\n DataLayout(..),\n TargetTriple(..),\n AlignSpec(..),\n Assembly(..),\n -- * Values\n defaultDataLayout\n ) where\n\n#include \"c++\/marshal.h\"\n\nimport Control.DeepSeq\nimport Data.ByteString.Char8 ( ByteString, unpack )\n\n{#enum ArithFlags {} deriving (Show, Eq) #}\n{#enum CmpPredicate {underscoreToCase} deriving (Show, Eq) #}\n{#enum CallingConvention {} deriving (Show, Eq) #}\n{#enum LinkageType {} deriving (Show, Eq) #}\n{#enum VisibilityStyle {} deriving (Show, Eq) #}\n\ninstance NFData ArithFlags\ninstance NFData CmpPredicate\ninstance NFData CallingConvention\ninstance NFData LinkageType\ninstance NFData VisibilityStyle\n\n\n -- Representing Assembly\ndata Assembly = Assembly !ByteString\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 Endian = EBig\n | ELittle\n deriving (Eq, Ord)\n\ninstance NFData Endian\n\ninstance Show Endian where\n show EBig = \"E\"\n show ELittle = \"e\"\n\n-- Track the ABI alignment and preferred alignment\ndata AlignSpec = AlignSpec !Int !Int\n deriving (Show, Eq, Ord)\n\ninstance NFData AlignSpec where\n rnf a@(AlignSpec i1 i2) = i1 `seq` i2 `seq` a `seq` ()\n\ndata TargetTriple = TargetTriple ByteString\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\ndata DataLayout = DataLayout { endianness :: Endian\n , pointerAlign :: (Int, AlignSpec)\n , intAlign :: [ (Int, AlignSpec) ]\n , vectorAlign :: [ (Int, AlignSpec) ]\n , floatAlign :: [ (Int, AlignSpec) ]\n , aggregateAlign :: [ (Int, AlignSpec) ]\n , stackAlign :: [ (Int, AlignSpec) ]\n , nativeWidths :: [ Int ]\n }\n deriving (Show, Eq)\n\ninstance NFData DataLayout where\n rnf d = endianness d `deepseq` pointerAlign d `deepseq`\n intAlign d `deepseq` vectorAlign d `deepseq`\n floatAlign d `deepseq` aggregateAlign d `deepseq`\n stackAlign d `deepseq` nativeWidths d `deepseq` d `seq` ()\n\n-- Defaults specified by LLVM. I think there can only be one pointer\n-- align specification, though it isn't explicitly stated\ndefaultDataLayout :: DataLayout\ndefaultDataLayout = DataLayout { endianness = EBig\n , pointerAlign = (64, AlignSpec 64 64)\n , intAlign = [ (1, AlignSpec 8 8)\n , (8, AlignSpec 8 8)\n , (16, AlignSpec 16 16)\n , (32, AlignSpec 32 32)\n , (64, AlignSpec 32 64)\n ]\n , vectorAlign = [ (64, AlignSpec 64 64)\n , (128, AlignSpec 128 128)\n ]\n , floatAlign = [ (32, AlignSpec 32 32)\n , (64, AlignSpec 64 64)\n ]\n , aggregateAlign = [ (0, AlignSpec 0 1) ]\n , stackAlign = [ (0, AlignSpec 64 64) ]\n , nativeWidths = [] -- Set.empty\n }\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"90b8c684db0922f1531163b1f1ec88fee316fb5e","subject":"Implement annotGetName, annotGetPageIndex, annotGetColor, annotSetColor, annotGetContents, annotSetContents and annotGetModified","message":"Implement annotGetName, annotGetPageIndex, annotGetColor, annotSetColor, annotGetContents, annotSetContents and annotGetModified\n","repos":"YoEight\/poppler_bak","old_file":"Graphics\/UI\/Gtk\/Poppler\/Annotation.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Annotation.chs","new_contents":"module Graphics.UI.Gtk.Poppler.Annotation (\n Annot,\n AnnotClass,\n AnnotType (..),\n AnnotFlag (..),\n annotGetAnnotType,\n annotGetAnnotFlags,\n annotGetName,\n annotGetPageIndex,\n annotGetColor,\n annotSetColor,\n annotGetContents,\n annotSetContents,\n annotGetModified,\n annotTextNew\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\nannotGetAnnotType :: AnnotClass annot => annot -> IO AnnotType\nannotGetAnnotType annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_annot_type #} (toAnnot annot)\n\nannotGetAnnotFlags :: AnnotClass annot => annot -> IO AnnotFlag\nannotGetAnnotFlags annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_flags #} (toAnnot annot)\n\nannotGetName :: AnnotClass annot => annot -> IO String\nannotGetName annot =\n {# call poppler_annot_get_name #} (toAnnot annot) >>= peekUTFString\n\nannotGetPageIndex :: AnnotClass annot => annot -> IO Int\nannotGetPageIndex annot =\n liftM fromIntegral $\n {# call poppler_annot_get_page_index #} (toAnnot annot)\n\nannotGetColor :: AnnotClass annot => annot -> IO PopplerColor\nannotGetColor annot =\n (peekPopplerColor . castPtr) =<<\n {# call poppler_annot_get_color #} (toAnnot annot)\n\nannotSetColor :: AnnotClass annot => annot -> PopplerColor -> IO ()\nannotSetColor annot color =\n with color $ \\colorPtr ->\n {# call poppler_annot_set_color #} (toAnnot annot) (castPtr colorPtr)\n\nannotGetContents :: AnnotClass annot => annot -> IO String\nannotGetContents annot =\n {# call poppler_annot_get_contents #} (toAnnot annot) >>= peekUTFString\n\nannotSetContents :: AnnotClass annot => annot -> String -> IO ()\nannotSetContents annot content =\n withUTFString content $ \\contentPtr ->\n {# call poppler_annot_set_contents #} (toAnnot annot) contentPtr\n\nannotGetModified :: AnnotClass annot => annot -> IO String\nannotGetModified annot =\n {# call poppler_annot_get_modified #} (toAnnot annot) >>= peekUTFString\n\nannotTextNew :: DocumentClass doc => doc -> PopplerRectangle -> IO Annot\nannotTextNew doc selection =\n wrapNewGObject mkAnnot $\n with selection $ \\selectionPtr ->\n {# call poppler_annot_text_new #} (toDocument doc) (castPtr selectionPtr)\n","old_contents":"module Graphics.UI.Gtk.Poppler.Annotation (\n Annot,\n AnnotClass,\n AnnotType (..),\n AnnotFlag (..),\n annotGetAnnotType,\n annotGetAnnotFlag,\n annotTextNew\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\nannotGetAnnotType :: AnnotClass annot => annot -> IO AnnotType\nannotGetAnnotType annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_annot_type #} (toAnnot annot)\n\nannotGetAnnotFlag :: AnnotClass annot => annot -> IO AnnotFlag\nannotGetAnnotFlag annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_flags #} (toAnnot annot)\n\nannotTextNew :: DocumentClass doc => doc -> PopplerRectangle -> IO Annot\nannotTextNew doc selection =\n wrapNewGObject mkAnnot $\n with selection $ \\selectionPtr ->\n {# call poppler_annot_text_new #} (toDocument doc) (castPtr selectionPtr)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"62e0ba4d81d164b25b0af4039b04c3caaacf24ab","subject":"Add device resources for compute 3.2 (Jetson K1)","message":"Add device resources for compute 3.2 (Jetson K1)\n\nSomewhat speculative, check when 6.5 is released. Fixes #15.\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 2 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Jetson TK1 (speculative)\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: Unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n#if CUDA_VERSION >= 4000\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8b48833089059d0aa8c00645e582a354c710723f","subject":"Export ContourFunctionUS","message":"Export ContourFunctionUS\n","repos":"TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV,aleator\/CV","old_file":"CV\/ConnectedComponents.chs","new_file":"CV\/ConnectedComponents.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n-- | This module contains functions for extracting features from connected components\n-- of black and white images as well as extracting other shape related features. \nmodule CV.ConnectedComponents\n (\n -- * Working with connected components\n fillConnectedComponents\n ,maskConnectedComponent\n ,selectSizedComponents\n ,countBlobs\n -- * Working with Image moments\n -- |Note that these functions should probably go to a different module, since\n -- they deal with entire moments of entire images.\n ,spatialMoments\n ,centralMoments\n ,normalizedCentralMoments\n ,huMoments\n -- * Working with component contours aka. object boundaries.\n -- |This part is really old code and probably could be improved a lot.\n ,Contours\n ,ContourFunctionUS\n ,getContours\n ,contourArea\n ,contourPerimeter\n ,contourPoints\n ,mapContours\n ,contourHuMoments) \nwhere\n#include \"cvWrapLEO.h\"\n\nimport CV.Bindings.ImgProc\nimport CV.Bindings.Types\nimport Control.Monad ((>=>))\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Ptr\nimport Foreign.Storable\nimport System.IO.Unsafe\n{#import CV.Image#}\n\nimport CV.ImageOp\n\nfillConnectedComponents :: Image GrayScale D8 -> (Image GrayScale D8, Int)\nfillConnectedComponents image = unsafePerformIO $ do\n let\n count :: CInt\n count = 0\n withCloneValue image $ \\clone ->\n withImage clone $ \\pclone ->\n with count $ \\pcount -> do\n c'fillConnectedComponents (castPtr pclone) pcount\n c <- peek pcount\n return (clone, fromIntegral c)\n\nmaskConnectedComponent :: Image GrayScale D8 -> Int -> Image GrayScale D8\nmaskConnectedComponent image index = unsafePerformIO $\n withCloneValue image $ \\clone ->\n withImage image $ \\pimage ->\n withImage clone $ \\pclone -> do\n c'maskConnectedComponent (castPtr pimage) (castPtr pclone) (fromIntegral index)\n return clone\n\n-- |Count the number of connected components in the image\ncountBlobs :: Image GrayScale D8 -> Int \ncountBlobs image = fromIntegral $\u00a0unsafePerformIO $ do\n withGenImage image $ \\i ->\n {#call blobCount#} i\n\n-- |Remove all connected components that fall outside of given size range from the image.\nselectSizedComponents :: Double -> Double -> Image GrayScale D8 -> Image GrayScale D8\nselectSizedComponents minSize maxSize image = unsafePerformIO $ do\n withGenImage image $ \\i ->\n creatingImage ({#call sizeFilter#} i (realToFrac minSize) (realToFrac maxSize))\n\n-- * Working with Image moments. \n\n-- Utility function for getting the moments\ngetMoments :: (Ptr C'CvMoments -> CInt -> CInt -> IO (CDouble)) -> Image GrayScale D32 -> Bool -> [Double]\ngetMoments f image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments :: C'CvMoments\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n ms <- sequence [ f pmoments i j\n | i <- [0..3], j <- [0..3], i+j <= 3 ]\n return (map realToFrac ms)\n\n-- | Extract raw spatial moments of the image.\nspatialMoments = getMoments c'cvGetSpatialMoment\n\n-- | Extract central moments of the image. These are useful for describing the\n-- object shape for a classifier system.\ncentralMoments = getMoments c'cvGetCentralMoment\n\n-- | Extract normalized central moments of the image.\nnormalizedCentralMoments = getMoments c'cvGetNormalizedCentralMoment\n\n{-\ncentralMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n ms <- sequence [{#call cvGetCentralMoment#} moments i j\n | i <- [0..3], j<-[0..3], i+j <= 3]\n {#call freeCvMoments#} moments\n return (map realToFrac ms)\n-}\n\n-- |Extract Hu-moments of the image. These features are rotation invariant.\nhuMoments :: Image GrayScale D32 -> Bool -> [Double]\nhuMoments image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n hu = C'CvHuMoments 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n with hu $ \\phu -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n c'cvGetHuMoments pmoments phu\n (C'CvHuMoments hu1 hu2 hu3 hu4 hu5 hu6 hu7) <- peek phu\n return (map realToFrac [hu1,hu2,hu3,hu4,hu5,hu6,hu7])\n\n{-\nhuMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n hu <- readHu moments\n {#call freeCvMoments#} moments\n return (map realToFrac hu)\n-}\n\n-- read stuff out of hu-moments structure.. This could be done way better.\nreadHu m = do\n hu <- mallocArray 7\n {#call getHuMoments#} m hu\n hu' <- peekArray 7 hu\n free hu\n return hu'\n\n-- |Structure that contains the opencv sequence holding the contour data.\n{#pointer *FoundContours as Contours foreign newtype#}\nforeign import ccall \"& free_found_contours\" releaseContours \n :: FinalizerPtr Contours\n\n-- | This function maps an opencv contour calculation over all\n-- contours of the image. \nmapContours :: ContourFunctionUS a -> Contours -> [a]\nmapContours (CFUS op) contours = unsafePerformIO $ do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n-- |Extract contours of connected components of the image.\ngetContours :: Image GrayScale D8 -> Contours\ngetContours img = unsafePerformIO $ do\n withImage img $ \\i -> do\n ptr <- {#call get_contours#} i\n fptr <- newForeignPtr releaseContours ptr\n return $ Contours fptr \n\nnewtype ContourFunctionUS a = CFUS (Contours -> IO a)\nnewtype ContourFunctionIO a = CFIO (Contours -> IO a)\n\nrawContourOpUS op = CFUS $ \\c -> withContours c op\nrawContourOp op = CFIO $ \\c -> withContours c op\n\nprintContour = rawContourOp {#call print_contour#}\n\ncontourArea :: ContourFunctionUS Double\ncontourArea = rawContourOpUS ({#call contour_area#} >=> return.realToFrac)\n-- ^The area of a contour.\n\ncontourPerimeter :: ContourFunctionUS Double\ncontourPerimeter = rawContourOpUS $ {#call contour_perimeter#} >=> return.realToFrac\n-- ^Get the perimeter of a contour.\n\n-- |Get a list of the points in the contour.\ncontourPoints :: ContourFunctionUS [(Double,Double)]\ncontourPoints = rawContourOpUS getContourPoints'\ngetContourPoints' f = do\n count <- {#call cur_contour_size#} f\n let count' = fromIntegral count \n ----print count\n xs <- mallocArray count' \n ys <- mallocArray count'\n {#call contour_points#} f xs ys\n xs' <- peekArray count' xs\n ys' <- peekArray count' ys\n free xs\n free ys\n return $ zip (map fromIntegral xs') (map fromIntegral ys')\n\n-- |\u00a0Operation for extracting Hu-moments from a contour\ncontourHuMoments :: ContourFunctionUS [Double]\ncontourHuMoments = rawContourOpUS $ getContourHuMoments' >=> return.map realToFrac\ngetContourHuMoments' f = do\n m <- {#call contour_moments#} f \n hu <- readHu m \n {#call freeCvMoments#} m\n return hu\n\n\nmapContoursIO :: ContourFunctionIO a -> Contours -> IO [a]\nmapContoursIO (CFIO op) contours = do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n{#pointer *CvMoments as Moments foreign newtype#}\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n-- | This module contains functions for extracting features from connected components\n-- of black and white images as well as extracting other shape related features. \nmodule CV.ConnectedComponents\n (\n -- * Working with connected components\n fillConnectedComponents\n ,maskConnectedComponent\n ,selectSizedComponents\n ,countBlobs\n -- * Working with Image moments\n -- |Note that these functions should probably go to a different module, since\n -- they deal with entire moments of entire images.\n ,spatialMoments\n ,centralMoments\n ,normalizedCentralMoments\n ,huMoments\n -- * Working with component contours aka. object boundaries.\n -- |This part is really old code and probably could be improved a lot.\n ,Contours\n ,getContours\n ,contourArea\n ,contourPerimeter\n ,contourPoints\n ,mapContours\n ,contourHuMoments) \nwhere\n#include \"cvWrapLEO.h\"\n\nimport CV.Bindings.ImgProc\nimport CV.Bindings.Types\nimport Control.Monad ((>=>))\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Ptr\nimport Foreign.Storable\nimport System.IO.Unsafe\n{#import CV.Image#}\n\nimport CV.ImageOp\n\nfillConnectedComponents :: Image GrayScale D8 -> (Image GrayScale D8, Int)\nfillConnectedComponents image = unsafePerformIO $ do\n let\n count :: CInt\n count = 0\n withCloneValue image $ \\clone ->\n withImage clone $ \\pclone ->\n with count $ \\pcount -> do\n c'fillConnectedComponents (castPtr pclone) pcount\n c <- peek pcount\n return (clone, fromIntegral c)\n\nmaskConnectedComponent :: Image GrayScale D8 -> Int -> Image GrayScale D8\nmaskConnectedComponent image index = unsafePerformIO $\n withCloneValue image $ \\clone ->\n withImage image $ \\pimage ->\n withImage clone $ \\pclone -> do\n c'maskConnectedComponent (castPtr pimage) (castPtr pclone) (fromIntegral index)\n return clone\n\n-- |Count the number of connected components in the image\ncountBlobs :: Image GrayScale D8 -> Int \ncountBlobs image = fromIntegral $\u00a0unsafePerformIO $ do\n withGenImage image $ \\i ->\n {#call blobCount#} i\n\n-- |Remove all connected components that fall outside of given size range from the image.\nselectSizedComponents :: Double -> Double -> Image GrayScale D8 -> Image GrayScale D8\nselectSizedComponents minSize maxSize image = unsafePerformIO $ do\n withGenImage image $ \\i ->\n creatingImage ({#call sizeFilter#} i (realToFrac minSize) (realToFrac maxSize))\n\n-- * Working with Image moments. \n\n-- Utility function for getting the moments\ngetMoments :: (Ptr C'CvMoments -> CInt -> CInt -> IO (CDouble)) -> Image GrayScale D32 -> Bool -> [Double]\ngetMoments f image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments :: C'CvMoments\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n ms <- sequence [ f pmoments i j\n | i <- [0..3], j <- [0..3], i+j <= 3 ]\n return (map realToFrac ms)\n\n-- | Extract raw spatial moments of the image.\nspatialMoments = getMoments c'cvGetSpatialMoment\n\n-- | Extract central moments of the image. These are useful for describing the\n-- object shape for a classifier system.\ncentralMoments = getMoments c'cvGetCentralMoment\n\n-- | Extract normalized central moments of the image.\nnormalizedCentralMoments = getMoments c'cvGetNormalizedCentralMoment\n\n{-\ncentralMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n ms <- sequence [{#call cvGetCentralMoment#} moments i j\n | i <- [0..3], j<-[0..3], i+j <= 3]\n {#call freeCvMoments#} moments\n return (map realToFrac ms)\n-}\n\n-- |Extract Hu-moments of the image. These features are rotation invariant.\nhuMoments :: Image GrayScale D32 -> Bool -> [Double]\nhuMoments image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n hu = C'CvHuMoments 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n with hu $ \\phu -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n c'cvGetHuMoments pmoments phu\n (C'CvHuMoments hu1 hu2 hu3 hu4 hu5 hu6 hu7) <- peek phu\n return (map realToFrac [hu1,hu2,hu3,hu4,hu5,hu6,hu7])\n\n{-\nhuMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n hu <- readHu moments\n {#call freeCvMoments#} moments\n return (map realToFrac hu)\n-}\n\n-- read stuff out of hu-moments structure.. This could be done way better.\nreadHu m = do\n hu <- mallocArray 7\n {#call getHuMoments#} m hu\n hu' <- peekArray 7 hu\n free hu\n return hu'\n\n-- |Structure that contains the opencv sequence holding the contour data.\n{#pointer *FoundContours as Contours foreign newtype#}\nforeign import ccall \"& free_found_contours\" releaseContours \n :: FinalizerPtr Contours\n\n-- | This function maps an opencv contour calculation over all\n-- contours of the image. \nmapContours :: ContourFunctionUS a -> Contours -> [a]\nmapContours (CFUS op) contours = unsafePerformIO $ do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n-- |Extract contours of connected components of the image.\ngetContours :: Image GrayScale D8 -> Contours\ngetContours img = unsafePerformIO $ do\n withImage img $ \\i -> do\n ptr <- {#call get_contours#} i\n fptr <- newForeignPtr releaseContours ptr\n return $ Contours fptr \n\nnewtype ContourFunctionUS a = CFUS (Contours -> IO a)\nnewtype ContourFunctionIO a = CFIO (Contours -> IO a)\n\nrawContourOpUS op = CFUS $ \\c -> withContours c op\nrawContourOp op = CFIO $ \\c -> withContours c op\n\nprintContour = rawContourOp {#call print_contour#}\n\ncontourArea :: ContourFunctionUS Double\ncontourArea = rawContourOpUS ({#call contour_area#} >=> return.realToFrac)\n-- ^The area of a contour.\n\ncontourPerimeter :: ContourFunctionUS Double\ncontourPerimeter = rawContourOpUS $ {#call contour_perimeter#} >=> return.realToFrac\n-- ^Get the perimeter of a contour.\n\n-- |Get a list of the points in the contour.\ncontourPoints :: ContourFunctionUS [(Double,Double)]\ncontourPoints = rawContourOpUS getContourPoints'\ngetContourPoints' f = do\n count <- {#call cur_contour_size#} f\n let count' = fromIntegral count \n ----print count\n xs <- mallocArray count' \n ys <- mallocArray count'\n {#call contour_points#} f xs ys\n xs' <- peekArray count' xs\n ys' <- peekArray count' ys\n free xs\n free ys\n return $ zip (map fromIntegral xs') (map fromIntegral ys')\n\n-- |\u00a0Operation for extracting Hu-moments from a contour\ncontourHuMoments :: ContourFunctionUS [Double]\ncontourHuMoments = rawContourOpUS $ getContourHuMoments' >=> return.map realToFrac\ngetContourHuMoments' f = do\n m <- {#call contour_moments#} f \n hu <- readHu m \n {#call freeCvMoments#} m\n return hu\n\n\nmapContoursIO :: ContourFunctionIO a -> Contours -> IO [a]\nmapContoursIO (CFIO op) contours = do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n{#pointer *CvMoments as Moments foreign newtype#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"adacef25ccae8f5d03faea3bdfde9c3f9876bf2f","subject":"openRepoObjDir","message":"openRepoObjDir\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\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 if res == 0\n then fmap (Right . Index) $ peek idx\n else return . Left . toEnum . fromIntegral $ res\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\n-- TODO: Refactor some bits\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else 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","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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\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 if res == 0\n then fmap (Right . Index) $ peek idx\n else return . Left . toEnum . fromIntegral $ res\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\n-- TODO: Refactor some bits\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"b09f7c778b375fa484efdcddcc1aee39391e948a","subject":"no need to register finalizer for warp options since gdal clones them","message":"no need to register finalizer for warp options since gdal clones them\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/Warper.chs","new_file":"src\/GDAL\/Internal\/Warper.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.Warper (\n ResampleAlg (..)\n , WarpOptions (..)\n , BandOptions (..)\n , GDALWarpException (..)\n , reprojectImage\n , setTransformer\n , createWarpedVRT\n , def\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (when, void, forM_, forM)\nimport Control.Monad.IO.Class (liftIO)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..), bracket)\nimport Data.Maybe (isJust, fromMaybe)\nimport Data.Typeable (Typeable)\nimport Data.Default (Default(..))\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (\n Ptr\n , FunPtr\n , nullPtr\n , castPtr\n , castFunPtr\n , nullFunPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Storable (Storable(..))\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.CPLConv\n{#import GDAL.Internal.Algorithms #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.CPLString #}\n{#import GDAL.Internal.CPLProgress #}\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.GDAL #}\n\n#include \"gdal.h\"\n#include \"gdalwarper.h\"\n\ndata GDALWarpException\n = WarpStopped\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALWarpException where\n rnf a = a `seq` ()\n\ninstance Exception GDALWarpException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n{# enum GDALResampleAlg as ResampleAlg {upcaseFirstLetter} with prefix = \"GRA_\"\n deriving (Eq,Read,Show,Bounded) #}\n\ndata BandOptions a b\n = BandOptions {\n biSrc :: !Int\n , biDst :: !Int\n , biSrcNoData :: !(Maybe a)\n , biDstNoData :: !(Maybe b)\n } deriving Show\n\n\ndata WarpOptions s a b\n = forall t. (Transformer t, GDALType a, GDALType b)\n => WarpOptions {\n woResampleAlg :: ResampleAlg\n , woWarpOptions :: OptionList\n , woMemoryLimit :: Double\n , woWorkingDatatype :: Datatype\n , woBands :: [BandOptions a b]\n , woTransfomer :: Maybe (t s a b)\n , woProgressFun :: Maybe ProgressFun\n }\n\ninstance (GDALType a, GDALType b) => Default (WarpOptions s a b) where\n def = WarpOptions {\n woResampleAlg = NearestNeighbour\n , woWarpOptions = []\n , woMemoryLimit = 0\n , woWorkingDatatype = GDT_Unknown\n , woBands = []\n , woTransfomer = Nothing :: Maybe (GenImgProjTransformer s a b)\n , woProgressFun = Nothing\n }\n\n-- Avoids \"Record update for insufficiently polymorphic field\" when doigs\n-- opts { woTransfomer = Just ...}\nsetTransformer\n :: forall t s a b. (Transformer t, GDALType a, GDALType b)\n => t s a b -> WarpOptions s a b -> WarpOptions s a b\nsetTransformer t opts = WarpOptions {\n woResampleAlg = woResampleAlg opts\n , woWarpOptions = woWarpOptions opts\n , woMemoryLimit = woMemoryLimit opts\n , woWorkingDatatype = woWorkingDatatype opts\n , woBands = woBands opts\n , woTransfomer = Just t\n , woProgressFun = woProgressFun opts\n }\n\n\n\nsetOptionDefaults\n :: (GDALType a, GDALType b)\n => RODataset s a -> Maybe (Dataset s t b) -> WarpOptions s a b\n -> GDAL s (WarpOptions s a b)\nsetOptionDefaults ds moDs wo@WarpOptions{..} = do\n bands <- if null woBands\n then forM [1..datasetBandCount ds] $ \\i -> do\n srcNd <- getBand i ds >>= bandNodataValue\n dstNd <- case moDs of\n Just oDs -> getBand i oDs >>= bandNodataValue\n Nothing -> return (fmap (fromNodata . toNodata) srcNd)\n return (BandOptions i i srcNd dstNd)\n else return woBands\n let warpOptions\n | any (isJust . biDstNoData) bands\n = (\"INIT_DEST\",\"NO_DATA\") : woWarpOptions\n | otherwise = woWarpOptions\n return (wo { woWarpOptions = warpOptions, woBands = bands})\n\nanyBandHasNoData :: WarpOptions s a b -> Bool\nanyBandHasNoData wo\n = any (\\BandOptions{..} -> isJust biSrcNoData || isJust biDstNoData) (woBands wo)\n\nanyBandHasDstNoData :: WarpOptions s a b -> Bool\nanyBandHasDstNoData wo = any (\\BandOptions{..} -> isJust biDstNoData) (woBands wo)\n\nwithWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => RODataset s a -> WarpOptions s a b -> (Ptr (WarpOptions s a b) -> IO c)\n -> IO c\nwithWarpOptionsPtr ds wo@WarpOptions{..}\n = bracket createWarpOptions destroyWarpOptions\n where\n dsPtr = unDataset ds\n createWarpOptions = do\n p <- c_createWarpOptions\n {#set GDALWarpOptions.hSrcDS #} p (castPtr dsPtr)\n {#set GDALWarpOptions.eResampleAlg #} p (fromEnumC woResampleAlg)\n oListPtr <- toOptionListPtr woWarpOptions\n {#set GDALWarpOptions.papszWarpOptions #} p oListPtr\n {#set GDALWarpOptions.dfWarpMemoryLimit #} p (realToFrac woMemoryLimit)\n {#set GDALWarpOptions.eWorkingDataType #} p (fromEnumC woWorkingDatatype)\n {#set GDALWarpOptions.nBandCount #} p (fromIntegral (length woBands))\n {#set GDALWarpOptions.panSrcBands #} p =<<\n listToPtr (map (fromIntegral . biSrc) woBands)\n {#set GDALWarpOptions.panDstBands #} p =<<\n listToPtr (map (fromIntegral . biDst) woBands)\n case woTransfomer of\n Just t -> do\n {#set GDALWarpOptions.pfnTransformer #} p\n (castFunPtr (transformerFunc t))\n tArg <- fmap castPtr (createTransformer dsPtr t)\n {#set GDALWarpOptions.pTransformerArg #} p tArg\n Nothing -> do\n {#set GDALWarpOptions.pfnTransformer #} p nullFunPtr\n {#set GDALWarpOptions.pTransformerArg #} p nullPtr\n when (anyBandHasNoData wo) $ do\n vPtrSrcR <- listToPtr\n (map (toNodata . fromMaybe nodata . biSrcNoData) woBands)\n vPtrSrcI <- listToPtr (replicate (length woBands) 0)\n vPtrDstR <- listToPtr\n (map (toNodata . fromMaybe nodata . biDstNoData) woBands)\n vPtrDstI <- listToPtr (replicate (length woBands) 0)\n {#set GDALWarpOptions.padfDstNoDataReal #} p vPtrDstR\n {#set GDALWarpOptions.padfDstNoDataImag #} p vPtrDstI\n {#set GDALWarpOptions.padfSrcNoDataReal #} p vPtrSrcR\n {#set GDALWarpOptions.padfSrcNoDataImag #} p vPtrSrcI\n return p\n\n destroyWarpOptions = c_destroyWarpOptions\n\n listToPtr [] = return nullPtr\n listToPtr l = do\n ptr <- cplMallocArray (length l)\n mapM_ (\\(i,v) -> pokeElemOff ptr i v) (zip [0..] l)\n return ptr\n\nforeign import ccall unsafe \"gdalwarper.h GDALCreateWarpOptions\"\n c_createWarpOptions :: IO (Ptr (WarpOptions s a b))\n\nforeign import ccall unsafe \"gdalwarper.h GDALDestroyWarpOptions\"\n c_destroyWarpOptions :: Ptr (WarpOptions s a b) -> IO ()\n\nreprojectImage\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> Maybe SpatialReference\n -> RWDataset s b\n -> Maybe SpatialReference\n -> ResampleAlg\n -> Double\n -> Double\n -> Maybe ProgressFun\n -> OptionList\n -> GDAL s ()\nreprojectImage srcDs srcSrs dstDs dstSrs algo memLimit maxError progressFun opts\n = do options' <- setOptionDefaults srcDs (Just dstDs)\n (def {woWarpOptions=opts})\n ret <- liftIO $\n withProgressFun progressFun $ \\pFun ->\n throwIfError \"reprojectImage\" $\n withLockedDatasetPtr srcDs $ \\srcPtr ->\n withLockedDatasetPtr dstDs $ \\dstPtr ->\n withMaybeSRAsCString srcSrs $ \\srcSrs' ->\n withMaybeSRAsCString dstSrs $ \\dstSrs' ->\n withWarpOptionsPtr srcDs options' $ \\wopts ->\n void $ c_reprojectImage srcPtr srcSrs' dstPtr dstSrs' algo'\n memLimit' maxError' pFun nullPtr wopts\n maybe (throwBindingException WarpStopped) return ret\n where\n algo' = fromEnumC algo\n maxError' = realToFrac maxError\n memLimit' = realToFrac memLimit\n\nforeign import ccall safe \"gdalwarper.h GDALReprojectImage\" c_reprojectImage\n :: Ptr (Dataset s t a) -- ^Source dataset\n -> CString -- ^Source proj (WKT)\n -> Ptr (RWDataset s b) -- ^Dest dataset\n -> CString -- ^Dest proj (WKT)\n -> CInt -- ^Resample alg\n -> CDouble -- ^Memory limit\n -> CDouble -- ^Max error\n -> ProgressFunPtr -- ^Progress func\n -> Ptr () -- ^Progress arg (unused)\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO CInt\n\ncreateWarpedVRT\n :: forall s a b. (GDALType a, GDALType b)\n => RODataset s a\n -> Size\n -> Geotransform\n -> WarpOptions s a b\n -> GDAL s (RODataset s b)\ncreateWarpedVRT srcDs (XY nPixels nLines) geotransform wo@WarpOptions{..} = do\n options'' <- setOptionDefaults srcDs Nothing options'\n newDsPtr <- liftIO $\n withWarpOptionsPtr srcDs options'' $ \\opts ->\n alloca $ \\gt -> do\n poke (castPtr gt) geotransform\n pArg <- {#get GDALWarpOptions.pTransformerArg #} opts\n when (pArg \/= nullPtr) $\n {#call GDALSetGenImgProjTransformerDstGeoTransform as ^#} pArg gt\n c_createWarpedVRT dsPtr nPixels' nLines' gt opts\n oDs <- newDerivedDatasetHandle srcDs newDsPtr\n setDstNodata oDs options''\n unsafeToReadOnly oDs\n where\n nPixels' = fromIntegral nPixels\n nLines' = fromIntegral nLines\n dsPtr = unDataset srcDs\n options' = case woTransfomer of\n Nothing -> setTransformer (def :: GenImgProjTransformer s a b)\n wo\n Just _ -> wo\n\nsetDstNodata :: GDALType b => RWDataset s b -> WarpOptions s a b -> GDAL s ()\nsetDstNodata oDs options\n = when (anyBandHasDstNoData options) $\n forM_ (woBands options) $ \\BandOptions{..} ->\n case biDstNoData of\n Just nd -> do\n b <- getBand biDst oDs\n setBandNodataValue b nd\n Nothing -> return ()\n\nforeign import ccall safe \"gdalwarper.h GDALCreateWarpedVRT\" c_createWarpedVRT\n :: Ptr (RODataset s a) -- ^Source dataset\n -> CInt -- ^nPixels\n -> CInt -- ^nLines\n -> Ptr CDouble -- ^geotransform\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO (Ptr (RWDataset s b))\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.Warper (\n ResampleAlg (..)\n , WarpOptions (..)\n , BandOptions (..)\n , GDALWarpException (..)\n , reprojectImage\n , setTransformer\n , createWarpedVRT\n , def\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (when, void, forM_, forM)\nimport Control.Monad.IO.Class (liftIO)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..), bracket)\nimport Data.Maybe (isJust, fromMaybe)\nimport Data.Typeable (Typeable)\nimport Data.Default (Default(..))\nimport Foreign.C.String (CString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (\n Ptr\n , FunPtr\n , nullPtr\n , castPtr\n , castFunPtr\n , nullFunPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Storable (Storable(..))\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.CPLConv\n{#import GDAL.Internal.Algorithms #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.CPLString #}\n{#import GDAL.Internal.CPLProgress #}\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.GDAL #}\n\n#include \"gdal.h\"\n#include \"gdalwarper.h\"\n\ndata GDALWarpException\n = WarpStopped\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALWarpException where\n rnf a = a `seq` ()\n\ninstance Exception GDALWarpException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n{# enum GDALResampleAlg as ResampleAlg {upcaseFirstLetter} with prefix = \"GRA_\"\n deriving (Eq,Read,Show,Bounded) #}\n\ndata BandOptions a b\n = BandOptions {\n biSrc :: !Int\n , biDst :: !Int\n , biSrcNoData :: !(Maybe a)\n , biDstNoData :: !(Maybe b)\n } deriving Show\n\n\ndata WarpOptions s a b\n = forall t. (Transformer t, GDALType a, GDALType b)\n => WarpOptions {\n woResampleAlg :: ResampleAlg\n , woWarpOptions :: OptionList\n , woMemoryLimit :: Double\n , woWorkingDatatype :: Datatype\n , woBands :: [BandOptions a b]\n , woTransfomer :: Maybe (t s a b)\n , woProgressFun :: Maybe ProgressFun\n }\n\ninstance (GDALType a, GDALType b) => Default (WarpOptions s a b) where\n def = WarpOptions {\n woResampleAlg = NearestNeighbour\n , woWarpOptions = []\n , woMemoryLimit = 0\n , woWorkingDatatype = GDT_Unknown\n , woBands = []\n , woTransfomer = Nothing :: Maybe (GenImgProjTransformer s a b)\n , woProgressFun = Nothing\n }\n\n-- Avoids \"Record update for insufficiently polymorphic field\" when doigs\n-- opts { woTransfomer = Just ...}\nsetTransformer\n :: forall t s a b. (Transformer t, GDALType a, GDALType b)\n => t s a b -> WarpOptions s a b -> WarpOptions s a b\nsetTransformer t opts = WarpOptions {\n woResampleAlg = woResampleAlg opts\n , woWarpOptions = woWarpOptions opts\n , woMemoryLimit = woMemoryLimit opts\n , woWorkingDatatype = woWorkingDatatype opts\n , woBands = woBands opts\n , woTransfomer = Just t\n , woProgressFun = woProgressFun opts\n }\n\n\n\nsetOptionDefaults\n :: (GDALType a, GDALType b)\n => RODataset s a -> Maybe (Dataset s t b) -> WarpOptions s a b\n -> GDAL s (WarpOptions s a b)\nsetOptionDefaults ds moDs wo@WarpOptions{..} = do\n bands <- if null woBands\n then forM [1..datasetBandCount ds] $ \\i -> do\n srcNd <- getBand i ds >>= bandNodataValue\n dstNd <- case moDs of\n Just oDs -> getBand i oDs >>= bandNodataValue\n Nothing -> return (fmap (fromNodata . toNodata) srcNd)\n return (BandOptions i i srcNd dstNd)\n else return woBands\n let warpOptions\n | any (isJust . biDstNoData) bands\n = (\"INIT_DEST\",\"NO_DATA\") : woWarpOptions\n | otherwise = woWarpOptions\n return (wo { woWarpOptions = warpOptions, woBands = bands})\n\nanyBandHasNoData :: WarpOptions s a b -> Bool\nanyBandHasNoData wo\n = any (\\BandOptions{..} -> isJust biSrcNoData || isJust biDstNoData) (woBands wo)\n\nanyBandHasDstNoData :: WarpOptions s a b -> Bool\nanyBandHasDstNoData wo = any (\\BandOptions{..} -> isJust biDstNoData) (woBands wo)\n\nwithWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => RODataset s a -> WarpOptions s a b -> (Ptr (WarpOptions s a b) -> IO c)\n -> IO c\nwithWarpOptionsPtr ds wo f = do\n (opts, finalize) <- mkWarpOptionsPtr ds wo\n bracket (return opts) (const finalize) f\n\nmkWarpOptionsPtr\n :: (GDALType a, GDALType b)\n => RODataset s a -> WarpOptions s a b\n -> IO (Ptr (WarpOptions s a b), IO ())\nmkWarpOptionsPtr ds wo@WarpOptions{..} = do\n p <- createWarpOptions\n return (p, destroyWarpOptions p)\n where\n dsPtr = unDataset ds\n createWarpOptions = do\n p <- c_createWarpOptions\n {#set GDALWarpOptions.hSrcDS #} p (castPtr dsPtr)\n {#set GDALWarpOptions.eResampleAlg #} p (fromEnumC woResampleAlg)\n oListPtr <- toOptionListPtr woWarpOptions\n {#set GDALWarpOptions.papszWarpOptions #} p oListPtr\n {#set GDALWarpOptions.dfWarpMemoryLimit #} p (realToFrac woMemoryLimit)\n {#set GDALWarpOptions.eWorkingDataType #} p (fromEnumC woWorkingDatatype)\n {#set GDALWarpOptions.nBandCount #} p (fromIntegral (length woBands))\n {#set GDALWarpOptions.panSrcBands #} p =<<\n listToPtr (map (fromIntegral . biSrc) woBands)\n {#set GDALWarpOptions.panDstBands #} p =<<\n listToPtr (map (fromIntegral . biDst) woBands)\n case woTransfomer of\n Just t -> do\n {#set GDALWarpOptions.pfnTransformer #} p\n (castFunPtr (transformerFunc t))\n tArg <- fmap castPtr (createTransformer dsPtr t)\n {#set GDALWarpOptions.pTransformerArg #} p tArg\n Nothing -> do\n {#set GDALWarpOptions.pfnTransformer #} p nullFunPtr\n {#set GDALWarpOptions.pTransformerArg #} p nullPtr\n when (anyBandHasNoData wo) $ do\n vPtrSrcR <- listToPtr\n (map (toNodata . fromMaybe nodata . biSrcNoData) woBands)\n vPtrSrcI <- listToPtr (replicate (length woBands) 0)\n vPtrDstR <- listToPtr\n (map (toNodata . fromMaybe nodata . biDstNoData) woBands)\n vPtrDstI <- listToPtr (replicate (length woBands) 0)\n {#set GDALWarpOptions.padfDstNoDataReal #} p vPtrDstR\n {#set GDALWarpOptions.padfDstNoDataImag #} p vPtrDstI\n {#set GDALWarpOptions.padfSrcNoDataReal #} p vPtrSrcR\n {#set GDALWarpOptions.padfSrcNoDataImag #} p vPtrSrcI\n return p\n\n destroyWarpOptions = c_destroyWarpOptions\n\n listToPtr [] = return nullPtr\n listToPtr l = do\n ptr <- cplMallocArray (length l)\n mapM_ (\\(i,v) -> pokeElemOff ptr i v) (zip [0..] l)\n return ptr\n\nforeign import ccall unsafe \"gdalwarper.h GDALCreateWarpOptions\"\n c_createWarpOptions :: IO (Ptr (WarpOptions s a b))\n\nforeign import ccall unsafe \"gdalwarper.h GDALDestroyWarpOptions\"\n c_destroyWarpOptions :: Ptr (WarpOptions s a b) -> IO ()\n\nreprojectImage\n :: (GDALType a, GDALType b)\n => RODataset s a\n -> Maybe SpatialReference\n -> RWDataset s b\n -> Maybe SpatialReference\n -> ResampleAlg\n -> Double\n -> Double\n -> Maybe ProgressFun\n -> OptionList\n -> GDAL s ()\nreprojectImage srcDs srcSrs dstDs dstSrs algo memLimit maxError progressFun opts\n = do options' <- setOptionDefaults srcDs (Just dstDs)\n (def {woWarpOptions=opts})\n ret <- liftIO $\n withProgressFun progressFun $ \\pFun ->\n throwIfError \"reprojectImage\" $\n withLockedDatasetPtr srcDs $ \\srcPtr ->\n withLockedDatasetPtr dstDs $ \\dstPtr ->\n withMaybeSRAsCString srcSrs $ \\srcSrs' ->\n withMaybeSRAsCString dstSrs $ \\dstSrs' ->\n withWarpOptionsPtr srcDs options' $ \\wopts ->\n void $ c_reprojectImage srcPtr srcSrs' dstPtr dstSrs' algo'\n memLimit' maxError' pFun nullPtr wopts\n maybe (throwBindingException WarpStopped) return ret\n where\n algo' = fromEnumC algo\n maxError' = realToFrac maxError\n memLimit' = realToFrac memLimit\n\nforeign import ccall safe \"gdalwarper.h GDALReprojectImage\" c_reprojectImage\n :: Ptr (Dataset s t a) -- ^Source dataset\n -> CString -- ^Source proj (WKT)\n -> Ptr (RWDataset s b) -- ^Dest dataset\n -> CString -- ^Dest proj (WKT)\n -> CInt -- ^Resample alg\n -> CDouble -- ^Memory limit\n -> CDouble -- ^Max error\n -> ProgressFunPtr -- ^Progress func\n -> Ptr () -- ^Progress arg (unused)\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO CInt\n\ncreateWarpedVRT\n :: forall s a b. (GDALType a, GDALType b)\n => RODataset s a\n -> Size\n -> Geotransform\n -> WarpOptions s a b\n -> GDAL s (RODataset s b)\ncreateWarpedVRT srcDs (XY nPixels nLines) geotransform wo@WarpOptions{..} = do\n let dsPtr = unDataset srcDs\n options'' <- setOptionDefaults srcDs Nothing options'\n (opts,finalizeOpts) <- liftIO (mkWarpOptionsPtr srcDs options'')\n registerFinalizer finalizeOpts\n newDsPtr <- liftIO $ alloca $ \\gt -> do\n poke (castPtr gt) geotransform\n pArg <- {#get GDALWarpOptions.pTransformerArg #} opts\n when (pArg \/= nullPtr) $\n {#call GDALSetGenImgProjTransformerDstGeoTransform as ^#} pArg gt\n c_createWarpedVRT dsPtr (fromIntegral nPixels) (fromIntegral nLines) gt opts\n oDs <- newDerivedDatasetHandle srcDs newDsPtr\n setDstNodata oDs options''\n unsafeToReadOnly oDs\n where\n options' = case woTransfomer of\n Nothing -> setTransformer (def :: GenImgProjTransformer s a b)\n wo\n Just _ -> wo\n\nsetDstNodata :: GDALType b => RWDataset s b -> WarpOptions s a b -> GDAL s ()\nsetDstNodata oDs options\n = when (anyBandHasDstNoData options) $\n forM_ (woBands options) $ \\BandOptions{..} ->\n case biDstNoData of\n Just nd -> do\n b <- getBand biDst oDs\n setBandNodataValue b nd\n Nothing -> return ()\n\nforeign import ccall safe \"gdalwarper.h GDALCreateWarpedVRT\" c_createWarpedVRT\n :: Ptr (RODataset s a) -- ^Source dataset\n -> CInt -- ^nPixels\n -> CInt -- ^nLines\n -> Ptr CDouble -- ^geotransform\n -> Ptr (WarpOptions s a b) -- ^warp options\n -> IO (Ptr (RWDataset s b))\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"38199abcbbebf9532cd9c940b72cb06175ac0763","subject":"BUGFIX: Compile on 32bit","message":"BUGFIX: Compile on 32bit\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(..), CUInt(..), 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\ntype CSizeT = {# type size_t #}\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, CSizeT) -> 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 -> CSizeT -> IO ()\ntype NewEnDeCryptFun =\n Ptr ShonkyCryptKey -> Ptr CChar -> CSizeT -> 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":"f8f79e3cf02651475a09ec1a78bb27d95cab0ce6","subject":"Handle AnnotFlag bytemask","message":"Handle AnnotFlag bytemask\n","repos":"YoEight\/poppler_bak","old_file":"Graphics\/UI\/Gtk\/Poppler\/Annotation.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Annotation.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\nmodule Graphics.UI.Gtk.Poppler.Annotation (\n Annot,\n AnnotClass,\n PopplerAnnotType (..),\n AnnotFlag (..),\n AnnotMarkup,\n AnnotMarkupClass,\n AnnotText,\n AnnotTextClass,\n castToAnnotText,\n annotGetAnnotType,\n annotGetAnnotFlags,\n annotSetAnnotFlags,\n annotGetName,\n annotGetPageIndex,\n annotGetColor,\n annotSetColor,\n annotGetContents,\n annotSetContents,\n annotGetModified,\n annotMarkupGetLabel,\n annotMarkupSetLabel,\n annotMarkupGetSubject,\n annotMarkupGetOpacity,\n annotMarkupSetOpacity,\n annotMarkupHasPopup,\n annotMarkupSetPopup,\n annotMarkupGetPopupIsOpen,\n annotMarkupSetPopupIsOpen,\n annotTextNew,\n annotTextGetIsOpen,\n annotTextSetIsOpen\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport Data.Bits\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\ntoByteMask :: [AnnotFlag] -> Int\ntoByteMask = foldr (.|.) 0 . fmap fromEnum\n\nfromByteMask :: Int -> [AnnotFlag]\nfromByteMask mask = foldr go [] (enumFrom minBound)\n where\n go x xs\n | AnnotFlagUnknown == x = xs\n | fromEnum x == fromEnum x .&. mask = x:xs\n | otherwise = xs\n\nannotGetAnnotType :: AnnotClass annot => annot -> IO PopplerAnnotType\nannotGetAnnotType annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_annot_type #} (toAnnot annot)\n\nannotGetAnnotFlags :: AnnotClass annot => annot -> IO [AnnotFlag]\nannotGetAnnotFlags annot =\n liftM (fromByteMask . fromIntegral) $\n {# call poppler_annot_get_flags #} (toAnnot annot)\n\nannotSetAnnotFlags :: AnnotClass annot => annot -> [AnnotFlag] -> IO ()\nannotSetAnnotFlags annot flags =\n {# call poppler_annot_set_flags #}\n (toAnnot annot)\n (fromIntegral $ toByteMask flags)\n\nannotGetName :: AnnotClass annot => annot -> IO String\nannotGetName annot =\n {# call poppler_annot_get_name #} (toAnnot annot) >>= peekUTFString\n\nannotGetPageIndex :: AnnotClass annot => annot -> IO Int\nannotGetPageIndex annot =\n liftM fromIntegral $\n {# call poppler_annot_get_page_index #} (toAnnot annot)\n\nannotGetColor :: AnnotClass annot => annot -> IO PopplerColor\nannotGetColor annot =\n (peekPopplerColor . castPtr) =<<\n {# call poppler_annot_get_color #} (toAnnot annot)\n\nannotSetColor :: AnnotClass annot => annot -> PopplerColor -> IO ()\nannotSetColor annot color =\n with color $ \\colorPtr ->\n {# call poppler_annot_set_color #} (toAnnot annot) (castPtr colorPtr)\n\nannotGetContents :: AnnotClass annot => annot -> IO String\nannotGetContents annot =\n {# call poppler_annot_get_contents #} (toAnnot annot) >>= peekUTFString\n\nannotSetContents :: AnnotClass annot => annot -> String -> IO ()\nannotSetContents annot content =\n withUTFString content $ \\contentPtr ->\n {# call poppler_annot_set_contents #} (toAnnot annot) contentPtr\n\nannotGetModified :: AnnotClass annot => annot -> IO String\nannotGetModified annot =\n {# call poppler_annot_get_modified #} (toAnnot annot) >>= peekUTFString\n\nannotMarkupGetLabel :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetLabel mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_label #} (toAnnotMarkup mark)\n\nannotMarkupSetLabel :: AnnotMarkupClass mark => mark -> String -> IO ()\nannotMarkupSetLabel mark label =\n withUTFString label $ \\labelPtr ->\n {# call poppler_annot_markup_set_label #}\n (toAnnotMarkup mark)\n (castPtr labelPtr)\n\nannotMarkupGetSubject :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetSubject mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_subject #} (toAnnotMarkup mark)\n\nannotMarkupGetOpacity :: AnnotMarkupClass mark => mark -> IO Double\nannotMarkupGetOpacity mark =\n liftM realToFrac $\n {# call poppler_annot_markup_get_opacity #} (toAnnotMarkup mark)\n\nannotMarkupSetOpacity :: AnnotMarkupClass mark => mark -> Double -> IO ()\nannotMarkupSetOpacity mark opacity =\n {# call poppler_annot_markup_set_opacity #}\n (toAnnotMarkup mark)\n (realToFrac opacity)\n\nannotMarkupHasPopup :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupHasPopup mark =\n liftM toBool $\n {# call poppler_annot_markup_has_popup #} (toAnnotMarkup mark)\n\nannotMarkupSetPopup :: AnnotMarkupClass mark\n => mark\n -> PopplerRectangle\n -> IO ()\nannotMarkupSetPopup mark rect =\n with rect $ \\rectPtr ->\n {# call poppler_annot_markup_set_popup #} (toAnnotMarkup mark) (castPtr rectPtr)\n\nannotMarkupGetPopupIsOpen :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupGetPopupIsOpen mark =\n liftM toBool $\n {# call poppler_annot_markup_get_popup_is_open #} (toAnnotMarkup mark)\n\nannotMarkupSetPopupIsOpen :: AnnotMarkupClass mark => mark -> Bool -> IO ()\nannotMarkupSetPopupIsOpen mark bool =\n {# call poppler_annot_markup_set_popup_is_open #}\n (toAnnotMarkup mark)\n (fromBool bool)\n\nannotTextNew :: DocumentClass doc => doc -> PopplerRectangle -> IO AnnotText\nannotTextNew doc selection =\n wrapNewGObject mkAnnotText $\n with selection $ \\selectionPtr ->\n liftM castPtr $\n {# call poppler_annot_text_new #} (toDocument doc) (castPtr selectionPtr)\n\nannotTextGetIsOpen :: AnnotTextClass annot => annot -> IO Bool\nannotTextGetIsOpen annot =\n liftM toBool $\n {# call poppler_annot_text_get_is_open #} (toAnnotText annot)\n\nannotTextSetIsOpen :: AnnotTextClass annot => annot -> Bool -> IO ()\nannotTextSetIsOpen annot bool =\n {# call poppler_annot_text_set_is_open #}\n (toAnnotText annot)\n (fromBool bool)\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\nmodule Graphics.UI.Gtk.Poppler.Annotation (\n Annot,\n AnnotClass,\n PopplerAnnotType (..),\n AnnotFlag (..),\n AnnotMarkup,\n AnnotMarkupClass,\n AnnotText,\n AnnotTextClass,\n castToAnnotText,\n annotGetAnnotType,\n annotGetAnnotFlags,\n annotSetAnnotFlags,\n annotGetName,\n annotGetPageIndex,\n annotGetColor,\n annotSetColor,\n annotGetContents,\n annotSetContents,\n annotGetModified,\n annotMarkupGetLabel,\n annotMarkupSetLabel,\n annotMarkupGetSubject,\n annotMarkupGetOpacity,\n annotMarkupSetOpacity,\n annotMarkupHasPopup,\n annotMarkupSetPopup,\n annotMarkupGetPopupIsOpen,\n annotMarkupSetPopupIsOpen,\n annotTextNew,\n annotTextGetIsOpen,\n annotTextSetIsOpen\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.GList\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\nimport Graphics.UI.Gtk.Abstract.Widget (Rectangle (..), Color (..))\n{#import Graphics.UI.GtkInternals#}\n{#import Graphics.Rendering.Cairo.Types#}\n{#import Graphics.UI.Gtk.Poppler.Types#}\nimport Graphics.UI.Gtk.Poppler.Structs\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\nannotGetAnnotType :: AnnotClass annot => annot -> IO PopplerAnnotType\nannotGetAnnotType annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_annot_type #} (toAnnot annot)\n\nannotGetAnnotFlags :: AnnotClass annot => annot -> IO AnnotFlag\nannotGetAnnotFlags annot =\n liftM (toEnum . fromIntegral) $\n {# call poppler_annot_get_flags #} (toAnnot annot)\n\nannotSetAnnotFlags :: AnnotClass annot => annot -> AnnotFlag -> IO ()\nannotSetAnnotFlags annot flag =\n {# call poppler_annot_set_flags #}\n (toAnnot annot)\n (fromIntegral $ fromEnum flag)\n\nannotGetName :: AnnotClass annot => annot -> IO String\nannotGetName annot =\n {# call poppler_annot_get_name #} (toAnnot annot) >>= peekUTFString\n\nannotGetPageIndex :: AnnotClass annot => annot -> IO Int\nannotGetPageIndex annot =\n liftM fromIntegral $\n {# call poppler_annot_get_page_index #} (toAnnot annot)\n\nannotGetColor :: AnnotClass annot => annot -> IO PopplerColor\nannotGetColor annot =\n (peekPopplerColor . castPtr) =<<\n {# call poppler_annot_get_color #} (toAnnot annot)\n\nannotSetColor :: AnnotClass annot => annot -> PopplerColor -> IO ()\nannotSetColor annot color =\n with color $ \\colorPtr ->\n {# call poppler_annot_set_color #} (toAnnot annot) (castPtr colorPtr)\n\nannotGetContents :: AnnotClass annot => annot -> IO String\nannotGetContents annot =\n {# call poppler_annot_get_contents #} (toAnnot annot) >>= peekUTFString\n\nannotSetContents :: AnnotClass annot => annot -> String -> IO ()\nannotSetContents annot content =\n withUTFString content $ \\contentPtr ->\n {# call poppler_annot_set_contents #} (toAnnot annot) contentPtr\n\nannotGetModified :: AnnotClass annot => annot -> IO String\nannotGetModified annot =\n {# call poppler_annot_get_modified #} (toAnnot annot) >>= peekUTFString\n\nannotMarkupGetLabel :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetLabel mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_label #} (toAnnotMarkup mark)\n\nannotMarkupSetLabel :: AnnotMarkupClass mark => mark -> String -> IO ()\nannotMarkupSetLabel mark label =\n withUTFString label $ \\labelPtr ->\n {# call poppler_annot_markup_set_label #}\n (toAnnotMarkup mark)\n (castPtr labelPtr)\n\nannotMarkupGetSubject :: AnnotMarkupClass mark => mark -> IO String\nannotMarkupGetSubject mark =\n peekUTFString =<<\n {# call poppler_annot_markup_get_subject #} (toAnnotMarkup mark)\n\nannotMarkupGetOpacity :: AnnotMarkupClass mark => mark -> IO Double\nannotMarkupGetOpacity mark =\n liftM realToFrac $\n {# call poppler_annot_markup_get_opacity #} (toAnnotMarkup mark)\n\nannotMarkupSetOpacity :: AnnotMarkupClass mark => mark -> Double -> IO ()\nannotMarkupSetOpacity mark opacity =\n {# call poppler_annot_markup_set_opacity #}\n (toAnnotMarkup mark)\n (realToFrac opacity)\n\nannotMarkupHasPopup :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupHasPopup mark =\n liftM toBool $\n {# call poppler_annot_markup_has_popup #} (toAnnotMarkup mark)\n\nannotMarkupSetPopup :: AnnotMarkupClass mark\n => mark\n -> PopplerRectangle\n -> IO ()\nannotMarkupSetPopup mark rect =\n with rect $ \\rectPtr ->\n {# call poppler_annot_markup_set_popup #} (toAnnotMarkup mark) (castPtr rectPtr)\n\nannotMarkupGetPopupIsOpen :: AnnotMarkupClass mark => mark -> IO Bool\nannotMarkupGetPopupIsOpen mark =\n liftM toBool $\n {# call poppler_annot_markup_get_popup_is_open #} (toAnnotMarkup mark)\n\nannotMarkupSetPopupIsOpen :: AnnotMarkupClass mark => mark -> Bool -> IO ()\nannotMarkupSetPopupIsOpen mark bool =\n {# call poppler_annot_markup_set_popup_is_open #}\n (toAnnotMarkup mark)\n (fromBool bool)\n\nannotTextNew :: DocumentClass doc => doc -> PopplerRectangle -> IO AnnotText\nannotTextNew doc selection =\n wrapNewGObject mkAnnotText $\n with selection $ \\selectionPtr ->\n liftM castPtr $\n {# call poppler_annot_text_new #} (toDocument doc) (castPtr selectionPtr)\n\nannotTextGetIsOpen :: AnnotTextClass annot => annot -> IO Bool\nannotTextGetIsOpen annot =\n liftM toBool $\n {# call poppler_annot_text_get_is_open #} (toAnnotText annot)\n\nannotTextSetIsOpen :: AnnotTextClass annot => annot -> Bool -> IO ()\nannotTextSetIsOpen annot bool =\n {# call poppler_annot_text_set_is_open #}\n (toAnnotText annot)\n (fromBool bool)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"5430f59aab46a7a7643444a7c10a63128505540d","subject":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)","message":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)","repos":"vincenthz\/webkit","old_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7cf12ee86ca70fa65d4893e18403ba9d0b08dd34","subject":"Explicitly type and comment some Morphology funcs.","message":"Explicitly type and comment some Morphology funcs.\n","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/Morphology.chs","new_file":"CV\/Morphology.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, UnicodeSyntax, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\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\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 (Int, Int) -> KernelShape -> StructuringElement\nstructuringElement s d | isGoodSE s d = createSE s d \n | otherwise = error \"Bad values in structuring element\"\n\n-- Create SE with custom shape that is taken from flat list shape.\ncreateSE :: (Int, Int) -> (Int, Int) -> KernelShape -> StructuringElement\ncreateSE (fromIntegral -> w,fromIntegral -> h) (fromIntegral -> x,fromIntegral -> y) shape = unsafePerformIO $ do\n iptr <- {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ shape) nullPtr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\ncustomSE :: (CInt, CInt) -> (CInt, CInt) -> [CInt] -> ConvKernel\ncustomSE s@(w,h) o shape | isGoodSE s o \n && length shape == fromIntegral (w*h)\n = createCustomSE s o shape\n\ncreateCustomSE (w,h) (x,y) shape = unsafePerformIO $ do\n iptr <- withArray shape $ \\arr ->\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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, UnicodeSyntax, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\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\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"87daedeca671b736136425a78f7f685c3d371112","subject":"doc additions","message":"doc additions\n","repos":"aslatter\/xcb-core","old_file":"Foreign\/IOVec.chs","new_file":"Foreign\/IOVec.chs","new_contents":"-- -*-haskell-*-\n\n{-# LANGUAGE ForeignFunctionInterface, BangPatterns #-}\n\n{- |\n I reserve the right to make this module private at any time.\n Specifically, this module will become private once I can do\n so without breaking c2hs preprocessing.\n -}\nmodule Foreign.IOVec\n (IOVec()\n ,withLazyByteString\n ,withByteString\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-- | The IOVev type is a newtype around\n-- an FFI `Ptr`, so you can pass it as is\n-- to FFI calls.\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. Don't do that.\n--\n-- The number passed to the callback is the number of blocks\n-- in the `IOVec`.\n--\n-- The spin of the lazy bytestring is forced prior to traversal.\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.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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bdbdc334213674f1167108d34b3369ee483ac583","subject":"Fix the get side of all container child attributes. It was accidentally calling 'set' rather than 'get'. doh! :-)","message":"Fix the get side of all container child attributes.\nIt was accidentally calling 'set' rather than 'get'. doh! :-)\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"acb42208580390430247c3c181aa4163c5238acd","subject":"added read mode phantom type to Band. Can now safely (as long as no other process is modifying a file) implement lazy IO","message":"added read mode phantom type to Band. Can now safely (as long as no other process is modifying a file) implement lazy IO\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 DeriveDataTypeable #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE EmptyDataDecls #-}\n\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , MaybeIOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , ColorTable\n , RasterAttributeTable\n\n , setQuietErrorHandler\n\n , registerAllDrivers\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\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.Concurrent (newMVar, takeMVar, putMVar, MVar)\nimport Control.Exception (finally, bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\nimport Data.Maybe (isJust)\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\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\nforeign import ccall \"wrapper\"\n wrapErrorHandler :: 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{# 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\ndata ReadOnly\ndata ReadWrite\nnewtype Dataset a = Dataset (ForeignPtr (Dataset a), Mutex)\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\n\nwithDataset, withDataset' :: (Dataset a) -> (Ptr (Dataset a) -> 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 = Band (Ptr (Band a))\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\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 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\ncreate :: String -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO RWDataset\ncreate drv path nx ny bands dtype options = do\n d <- driverByName drv\n create' d path nx ny bands dtype options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO RWDataset\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n opts <- toOptionList options\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\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 (Dataset a))\n\nopenReadOnly :: String -> IO RODataset\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO RWDataset\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))\n\n\ncreateCopy' :: Driver -> String -> (Dataset a) -> Bool -> DriverOptions\n -> ProgressFun -> IO (Dataset a)\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 createCopy_ driver p ds s o pFunc (castPtr nullPtr) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (Dataset a))\n\n\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ncreateCopy :: String -> String -> (Dataset a) -> Bool -> DriverOptions\n -> IO (Dataset a)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n 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 a) -> IO (Dataset a)\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) -> IO ())\n\ncreateMem:: Int -> Int -> Int -> Datatype -> DriverOptions -> IO RWDataset\ncreateMem = create \"MEM\" \"\"\n\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: (Ptr (Dataset a)) -> (IO ())\n\n\ndatasetProjection :: Dataset a -> 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)) -> (IO (Ptr CChar))\n\n\nsetDatasetProjection :: RWDataset -> 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)) -> ((Ptr CChar) -> (IO CInt))\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a -> 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)) -> ((Ptr CDouble) -> (IO CInt))\n\nsetDatasetGeotransform :: RWDataset -> 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)) -> ((Ptr CDouble) -> (IO CInt))\n\n\nwithBand :: Dataset a -> Int -> ((Band a) -> 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)) -> (CInt -> (IO ((Band a))))\n\n\nbandDatatype :: Band a -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: Band a -> CInt\n\n\nbandBlockSize :: Band a -> (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 -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: Band a -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: Band a -> (Int, Int)\nbandSize band\n = (fromIntegral . getXSize_ $ band, fromIntegral . getYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getXSize_\n :: Band a -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getYSize_\n :: Band a -> CInt\n\n\nbandNodataValue :: Band a -> 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 -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: RWBand -> 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 -> CDouble -> IO CInt\n\n\nfillBand :: RWBand -> 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 -> CDouble -> CDouble -> IO CInt\n\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 => Band b\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 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 (fromEnumC (datatype ptr))\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 (fromEnumC (datatype ptr))\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Band a -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: (Storable a, HasDatatype (Ptr a))\n => RWBand\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 ptr))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Band a -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ndata Block where\n Block :: (Typeable a, Storable a) => Vector a -> Block\n\ntype MaybeIOVector a = IO (Maybe (Vector a))\n\nreadBandBlock :: (Storable a, Typeable a)\n => Band b -> Int -> Int -> MaybeIOVector a\nreadBandBlock b x y =\n liftM (maybe Nothing (\\(Block a) -> cast a)) $ readBandBlock' b x y\n\n\nreadBandBlock' :: Band b -> Int -> Int -> IO (Maybe Block)\nreadBandBlock' b x y = \n case bandDatatype b of\n GDT_Byte -> Just . Block <$> (readIt b x y :: IOVector Word8)\n GDT_Int16 -> Just . Block <$> (readIt b x y :: IOVector Int16)\n GDT_Int32 -> Just . Block <$> (readIt b x y :: IOVector Int32)\n GDT_Float32 -> Just . Block <$> (readIt b x y :: IOVector Float)\n GDT_Float64 -> Just . Block <$> (readIt b x y :: IOVector Double)\n GDT_CInt16 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CInt32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n GDT_CFloat32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CFloat64 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n _ -> return Nothing\n where\n readIt :: Storable a => Band b -> Int -> Int -> IOVector a\n readIt b x y = 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 -> CInt -> CInt -> Ptr () -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nwriteBandBlock :: (Storable a, Typeable a)\n => RWBand\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBandBlock 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 typeOf vec \/= typeOfBand b\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) (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: RWBand -> CInt -> CInt -> Ptr () -> IO CInt\n\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 DeriveDataTypeable #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE EmptyDataDecls #-}\n\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , MaybeIOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , Band\n , Driver\n , ColorTable\n , RasterAttributeTable\n\n , setQuietErrorHandler\n\n , registerAllDrivers\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\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.Concurrent (newMVar, takeMVar, putMVar, MVar)\nimport Control.Exception (finally, bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\nimport Data.Maybe (isJust)\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\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\nforeign import ccall \"wrapper\"\n wrapErrorHandler :: 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{# 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\ndata ReadOnly\ndata ReadWrite\nnewtype (Dataset a) = Dataset (ForeignPtr (Dataset a), Mutex)\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\n\nwithDataset, withDataset' :: (Dataset a) -> (Ptr (Dataset a) -> 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#}\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 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\ncreate :: String -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO RWDataset\ncreate drv path nx ny bands dtype options = do\n d <- driverByName drv\n create' d path nx ny bands dtype options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO RWDataset\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n opts <- toOptionList options\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\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 (Dataset a))\n\nopenReadOnly :: String -> IO RODataset\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO RWDataset\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))\n\n\ncreateCopy' :: Driver -> String -> (Dataset a) -> Bool -> DriverOptions\n -> ProgressFun -> IO (Dataset a)\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 createCopy_ driver p ds s o pFunc (castPtr nullPtr) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (Dataset a))\n\n\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ncreateCopy :: String -> String -> (Dataset a) -> Bool -> DriverOptions\n -> IO (Dataset a)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n 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 a) -> IO (Dataset a)\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) -> IO ())\n\ncreateMem:: Int -> Int -> Int -> Datatype -> DriverOptions -> IO RWDataset\ncreateMem = create \"MEM\" \"\"\n\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: (Ptr (Dataset a)) -> (IO ())\n\n\ndatasetProjection :: Dataset a -> 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)) -> (IO (Ptr CChar))\n\n\nsetDatasetProjection :: RWDataset -> 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)) -> ((Ptr CChar) -> (IO CInt))\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a -> 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)) -> ((Ptr CDouble) -> (IO CInt))\n\nsetDatasetGeotransform :: RWDataset -> 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)) -> ((Ptr CDouble) -> (IO CInt))\n\n\nwithBand :: Dataset a -> Int -> (Band -> 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)) -> (CInt -> (IO (Band)))\n\n\n{# fun pure unsafe GDALGetRasterDataType as bandDatatype\n { id `Band'} -> `Datatype' toEnumC #}\n\nbandBlockSize :: Band -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr ->\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n {#call unsafe GDALGetBlockSize as ^#} band xPtr yPtr >>\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nbandBlockLen :: Band -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: Band -> (Int, Int)\nbandSize band\n = ( fromIntegral . {# call pure unsafe GDALGetRasterBandXSize as ^#} $ band\n , fromIntegral . {# call pure unsafe GDALGetRasterBandYSize as ^#} $ band\n )\n\nbandNodataValue :: Band -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ {#call unsafe GDALGetRasterNoDataValue as ^#} b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \n{# fun GDALSetRasterNoDataValue as setBandNodataValue\n { id `Band', `Double'} -> `Error' toEnumC #}\n\n{# fun GDALFillRaster as fillBand\n { id `Band', `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 => Band\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 withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\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 throwIfError \"could not read band\" $\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 return $ unsafeFromForeignPtr0 fp (bx * by)\n \nwriteBand :: (Storable a, HasDatatype (Ptr a))\n => Band\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 {#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\n\ndata Block where\n Block :: (Typeable a, Storable a) => Vector a -> Block\n\ntype MaybeIOVector a = IO (Maybe (Vector a))\n\nreadBandBlock :: (Storable a, Typeable a)\n => Band -> Int -> Int -> MaybeIOVector a\nreadBandBlock b x y = do\n block <- readBandBlock' b x y\n liftM (maybe Nothing (\\(Block a) -> cast a)) $ readBandBlock' b x y\n\n\nreadBandBlock' :: Band -> Int -> Int -> IO (Maybe Block)\nreadBandBlock' b x y = \n case bandDatatype b of\n GDT_Byte -> Just . Block <$> (readIt b x y :: IOVector Word8)\n GDT_Int16 -> Just . Block <$> (readIt b x y :: IOVector Int16)\n GDT_Int32 -> Just . Block <$> (readIt b x y :: IOVector Int32)\n GDT_Float32 -> Just . Block <$> (readIt b x y :: IOVector Float)\n GDT_Float64 -> Just . Block <$> (readIt b x y :: IOVector Double)\n GDT_CInt16 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CInt32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n GDT_CFloat32 -> Just . Block <$> (readIt b x y :: IOVector (Complex Float))\n GDT_CFloat64 -> Just . Block <$> (readIt b x y :: IOVector (Complex Double))\n _ -> return Nothing\n where\n readIt :: Storable a => Band -> Int -> Int -> IOVector a\n readIt b x y = do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n {#call GDALReadBlock as ^#}\n b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\ntype IOVector a = IO (Vector a)\n\nwriteBandBlock :: (Storable a, Typeable a)\n => Band\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBandBlock 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 typeOf vec \/= typeOfBand b\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n {#call GDALWriteBlock as ^#}\n b (fromIntegral x) (fromIntegral y) (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":"8b0dc0b0839124fab03e651127bec5b6953810e1","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\/DataType.chs","new_file":"src\/GDAL\/Internal\/DataType.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.DataType (\n GDALType (..)\n , KnownDataType\n , DataType (..)\n , GType\n\n , dataType\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n) where\n\n#include \"gdal.h\"\n#include \"bindings.h\"\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Data.Int (Int8, Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (Coercible, coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\n\nimport Foreign.C.Types\nimport Foreign.C.String (withCString)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (toEnumC, fromEnumC)\n\n\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\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\n------------------------------------------------------------------------------\n-- GDALType\n------------------------------------------------------------------------------\n\nclass (\n Eq a\n , Storable a\n -- Make sure we can safely castPtr in RasterIO, etc..\n , Coercible a (GType (DataTypeT a))\n , KnownDataType (DataTypeT a)\n ) => GDALType a where\n type DataTypeT a :: DataType\n toGType :: a -> GType (DataTypeT a)\n fromGType :: GType (DataTypeT a) -> a\n\n toCDouble :: a -> CDouble\n fromCDouble :: CDouble -> a\n\ntype family GType (k :: DataType) where\n GType 'GDT_Byte = CUChar\n GType 'GDT_UInt16 = CUShort\n GType 'GDT_UInt32 = CUInt\n GType 'GDT_Int16 = CShort\n GType 'GDT_Int32 = CInt\n GType 'GDT_Float32 = CFloat\n GType 'GDT_Float64 = CDouble\n GType 'GDT_CInt16 = CComplex CShort\n GType 'GDT_CInt32 = CComplex CInt\n GType 'GDT_CFloat32 = CComplex CFloat\n GType 'GDT_CFloat64 = CComplex CDouble\n\nnewtype CComplex a = CComplex (Complex a)\n deriving (Eq, Show)\n\nclass KnownDataType (k :: DataType) where\n dataTypeVal :: Proxy (k :: DataType) -> DataType\n\ndataType :: forall a. GDALType a => Proxy a -> DataType\ndataType _ = dataTypeVal (Proxy :: Proxy (DataTypeT a))\n{-# INLINE dataType #-}\n\ninstance KnownDataType 'GDT_Byte where dataTypeVal _ = GDT_Byte\ninstance KnownDataType 'GDT_UInt16 where dataTypeVal _ = GDT_UInt16\ninstance KnownDataType 'GDT_UInt32 where dataTypeVal _ = GDT_UInt32\ninstance KnownDataType 'GDT_Int16 where dataTypeVal _ = GDT_Int16\ninstance KnownDataType 'GDT_Int32 where dataTypeVal _ = GDT_Int32\ninstance KnownDataType 'GDT_Float32 where dataTypeVal _ = GDT_Float32\ninstance KnownDataType 'GDT_Float64 where dataTypeVal _ = GDT_Float64\ninstance KnownDataType 'GDT_CInt16 where dataTypeVal _ = GDT_CInt16\ninstance KnownDataType 'GDT_CInt32 where dataTypeVal _ = GDT_CInt32\ninstance KnownDataType 'GDT_CFloat32 where dataTypeVal _ = GDT_CFloat32\ninstance KnownDataType 'GDT_CFloat64 where dataTypeVal _ = GDT_CFloat64\n\n\ninstance GDALType Word8 where\n type DataTypeT Word8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n type DataTypeT Word16 = 'GDT_UInt16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n type DataTypeT Word32 = 'GDT_UInt32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n type DataTypeT Int16 = 'GDT_Int16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n type DataTypeT Int32 = 'GDT_Int32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n type DataTypeT Float = 'GDT_Float32\n fromCDouble = realToFrac\n toCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n type DataTypeT Double = 'GDT_Float64\n toCDouble = realToFrac\n fromCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\n\nderiving instance Storable a => Storable (CComplex a)\n\ninstance GDALType (Complex Int16) where\n type DataTypeT (Complex Int16) = 'GDT_CInt16\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n type DataTypeT (Complex Int32) = 'GDT_CInt32\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n type DataTypeT (Complex Float) = 'GDT_CFloat32\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n type DataTypeT (Complex Double) = 'GDT_CFloat64\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule GDAL.Internal.DataType (\n GDALType (..)\n , KnownDataType\n , DataType (..)\n , GType\n\n , dataType\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n) where\n\n#include \"gdal.h\"\n#include \"bindings.h\"\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Data.Int (Int8, Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (Coercible, coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\n\nimport Foreign.C.Types\nimport Foreign.C.String (withCString)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (toEnumC, fromEnumC)\n\n\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\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\n------------------------------------------------------------------------------\n-- GDALType\n------------------------------------------------------------------------------\n\nclass (\n Eq a\n , Storable a\n -- Make sure we can safely castPtr in RasterIO, etc..\n , Coercible a (GType (DataTypeT a))\n , KnownDataType (DataTypeT a)\n ) => GDALType a where\n type DataTypeT a :: DataType\n toGType :: a -> GType (DataTypeT a)\n fromGType :: GType (DataTypeT a) -> a\n\n toCDouble :: a -> CDouble\n fromCDouble :: CDouble -> a\n\ntype family GType (k :: DataType) where\n GType 'GDT_Byte = CUChar\n GType 'GDT_UInt16 = CUShort\n GType 'GDT_UInt32 = CUInt\n GType 'GDT_Int16 = CShort\n GType 'GDT_Int32 = CInt\n GType 'GDT_Float32 = CFloat\n GType 'GDT_Float64 = CDouble\n GType 'GDT_CInt16 = CComplex CShort\n GType 'GDT_CInt32 = CComplex CInt\n GType 'GDT_CFloat32 = CComplex CFloat\n GType 'GDT_CFloat64 = CComplex CDouble\n\nnewtype CComplex a = CComplex (Complex a)\n deriving (Eq, Storable, Show)\n\nclass KnownDataType (k :: DataType) where\n dataTypeVal :: Proxy (k :: DataType) -> DataType\n\ndataType :: forall a. GDALType a => Proxy a -> DataType\ndataType _ = dataTypeVal (Proxy :: Proxy (DataTypeT a))\n{-# INLINE dataType #-}\n\ninstance KnownDataType 'GDT_Byte where dataTypeVal _ = GDT_Byte\ninstance KnownDataType 'GDT_UInt16 where dataTypeVal _ = GDT_UInt16\ninstance KnownDataType 'GDT_UInt32 where dataTypeVal _ = GDT_UInt32\ninstance KnownDataType 'GDT_Int16 where dataTypeVal _ = GDT_Int16\ninstance KnownDataType 'GDT_Int32 where dataTypeVal _ = GDT_Int32\ninstance KnownDataType 'GDT_Float32 where dataTypeVal _ = GDT_Float32\ninstance KnownDataType 'GDT_Float64 where dataTypeVal _ = GDT_Float64\ninstance KnownDataType 'GDT_CInt16 where dataTypeVal _ = GDT_CInt16\ninstance KnownDataType 'GDT_CInt32 where dataTypeVal _ = GDT_CInt32\ninstance KnownDataType 'GDT_CFloat32 where dataTypeVal _ = GDT_CFloat32\ninstance KnownDataType 'GDT_CFloat64 where dataTypeVal _ = GDT_CFloat64\n\n\ninstance GDALType Word8 where\n type DataTypeT Word8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n type DataTypeT Word16 = 'GDT_UInt16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n type DataTypeT Word32 = 'GDT_UInt32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n type DataTypeT Int16 = 'GDT_Int16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n type DataTypeT Int32 = 'GDT_Int32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n type DataTypeT Float = 'GDT_Float32\n fromCDouble = realToFrac\n toCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n type DataTypeT Double = 'GDT_Float64\n toCDouble = realToFrac\n fromCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\ninstance GDALType (Complex Int16) where\n type DataTypeT (Complex Int16) = 'GDT_CInt16\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n type DataTypeT (Complex Int32) = 'GDT_CInt32\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n type DataTypeT (Complex Float) = 'GDT_CFloat32\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n type DataTypeT (Complex Double) = 'GDT_CFloat64\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"13f36a1a24b89065607a086eb053ac0a15f8d123","subject":"Fix ref counting bug in sourceBufferCreateMarker","message":"Fix ref counting bug in sourceBufferCreateMarker\n\n(reported by bwwx in #haskell)\nThe docs say that gtk_source_buffer_create_marker returns a new\nGtkSourceMarker, owned by the buffer. So we need to ref the object, so we\nshould use makeGObject rather than constructNewGObject.\n\ndarcs-hash:20070814182814-adfee-a352692adb9570322a39243e19dace4b50eb0f94.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"sourceview\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"sourceview\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0f92f648018fbad3f7c0f47d66c306671d568448","subject":"Export TableRowSelectFlag.","message":"Export TableRowSelectFlag.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/TableRow.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/TableRow.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.TableRow\n (\n tableRowNew,\n TableRowSelectFlag(..)\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Table_RowC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Widget\nimport Graphics.UI.FLTK.LowLevel.Table\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\n\ndata TableRowSelectFlag = TableRowSelect | TableRowDeselect | TableRowToggle\n\n{# fun Fl_OverriddenTable_Row_New as tableRowNew' { `Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenTable_Row_New_WithLabel as tableRowNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String', id `Ptr ()'} -> `Ptr ()' id #}\ntableRowNew :: Rectangle -> Maybe String -> Maybe (Ref TableRow -> IO ()) -> (Ref TableRow -> TableContext -> TableCoordinate -> Rectangle -> IO ()) -> CustomWidgetFuncs TableRow -> CustomTableFuncs TableRow -> IO (Ref TableRow)\ntableRowNew rectangle label' draw' drawCell' customWidgetFuncs' customTableFuncs' =\n do\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n ptr <- tableCustomFunctionStruct draw' (Just drawCell') customWidgetFuncs' customTableFuncs'\n case label' of\n (Just l') -> tableRowNewWithLabel' x_pos y_pos width height l' ptr >>= toRef\n Nothing -> tableRowNew' x_pos y_pos width height ptr >>= toRef\n\n{# fun Fl_Table_Row_Destroy as tableRowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) TableRow orig impl where\n runOp _ _ tableRow = withRef tableRow $ \\tableRowPtr -> tableRowDestroy' tableRowPtr\n{# fun Fl_Table_Row_rows as rows' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetRows ()) TableRow orig impl where\n runOp _ _ tableRow = withRef tableRow $ \\tableRowPtr -> rows' tableRowPtr\n{# fun Fl_Table_Row_set_type as tableRowSetType' { id `Ptr ()', cFromEnum `TableRowSelectMode'} -> `()' #}\ninstance (impl ~ (TableRowSelectMode -> IO ())) => Op (SetType ()) TableRow orig impl where\n runOp _ _ tableRow selectionMode = withRef tableRow $ \\tableRowPtr' -> tableRowSetType' tableRowPtr' selectionMode\n{# fun Fl_Table_Row_type as tableRowType { id `Ptr ()' } -> `TableRowSelectMode' cToEnum #}\ninstance (impl ~ (IO TableRowSelectMode)) => Op (GetType_ ()) TableRow orig impl where\n runOp _ _ tableRow = withRef tableRow $ \\tableRowPtr' -> tableRowType tableRowPtr'\n{# fun Fl_Table_Row_set_rows as setRows' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetRows ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setRows' tablePtr val\n{# fun Fl_Table_Row_set_cols as setCols' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetCols ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setCols' tablePtr val\n{# fun Fl_Table_Row_clear_super as clearSuper' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (ClearSuper ()) TableRow orig impl where\n runOp _ _ table = withRef table $ \\tablePtr -> clearSuper' tablePtr\n{# fun Fl_Table_Row_clear as clear' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (Clear ()) TableRow orig impl where\n runOp _ _ table = withRef table $ \\tablePtr -> clear' tablePtr\n{# fun Fl_Table_Row_set_rows_super as setRowsSuper' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetRowsSuper ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setRowsSuper' tablePtr val\n{# fun Fl_Table_Row_set_cols_super as setColsSuper' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetColsSuper ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setColsSuper' tablePtr val\n{# fun Fl_Table_Row_handle_super as handleSuper' { id `Ptr ()', cFromEnum `Event' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Int))) => Op (HandleSuper ()) TableRow orig impl where\n runOp _ _ table event = withRef table $ \\tablePtr -> handleSuper' tablePtr event\n{# fun Fl_Table_Row_handle as handle' { id `Ptr ()', cFromEnum `Event' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Int))) => Op (Handle ()) TableRow orig impl where\n runOp _ _ table event = withRef table $ \\tablePtr -> handle' tablePtr event\n{# fun Fl_Table_Row_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (ResizeSuper ()) TableRow orig impl where\n runOp _ _ table rectangle = let (x_pos', y_pos', width', height') = fromRectangle rectangle in withRef table $ \\tablePtr -> resizeSuper' tablePtr x_pos' y_pos' width' height'\n{# fun Fl_Table_Row_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) TableRow orig impl where\n runOp _ _ table rectangle = let (x_pos', y_pos', width', height') = fromRectangle rectangle in withRef table $ \\tablePtr -> resize' tablePtr x_pos' y_pos' width' height'\n{# fun Fl_Table_Row_row_selected as rowSelected' { id `Ptr ()', `Int'} -> `CInt' id #}\ninstance (impl ~ ( Int -> IO (Either OutOfRange Bool))) => Op (GetRowSelected ()) TableRow orig impl where\n runOp _ _ table idx' = withRef table $ \\tablePtr -> do\n ret' <- rowSelected' tablePtr idx'\n if ret' == -1 then (return $ Left OutOfRange) else (return $ Right $ cToBool ret')\n{# fun Fl_Table_Row_select_all_rows_with_flag as selectAllRows' {id `Ptr ()', `Int'} -> `()' #}\ninstance (impl ~ ( TableRowSelectFlag -> IO ())) => Op (SelectAllRows ()) TableRow orig impl where\n runOp _ _ table flag' = withRef table $\n \\tablePtr ->\n case flag' of\n TableRowSelect -> selectAllRows' tablePtr 1\n TableRowDeselect -> selectAllRows' tablePtr 0\n TableRowToggle -> selectAllRows' tablePtr 2\n\n-- $functions\n-- @\n-- clear :: 'Ref' 'TableRow' -> 'IO' ()\n--\n-- clearSuper :: 'Ref' 'TableRow' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'TableRow' -> 'IO' ()\n--\n-- getRowSelected :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ('Either' 'OutOfRange' 'Bool')\n--\n-- getRows :: 'Ref' 'TableRow' -> 'IO' ('Int')\n--\n-- getType_ :: 'Ref' 'TableRow' -> 'IO' 'TableRowSelectMode'\n--\n-- handle :: 'Ref' 'TableRow' -> 'Event' -> 'IO' ('Int')\n--\n-- handleSuper :: 'Ref' 'TableRow' -> 'Event' -> 'IO' ('Int')\n--\n-- resize :: 'Ref' 'TableRow' -> 'Rectangle' -> 'IO' ()\n--\n-- resizeSuper :: 'Ref' 'TableRow' -> 'Rectangle' -> 'IO' ()\n--\n-- selectAllRows :: 'Ref' 'TableRow' -> 'TableRowSelectFlag' -> 'IO' ()\n--\n-- setCols :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setColsSuper :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setRows :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setRowsSuper :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setType :: 'Ref' 'TableRow' -> 'TableRowSelectMode' -> 'IO' ()\n--\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Table\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.TableRow\"\n-- @\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.TableRow\n (\n tableRowNew,\n TableRowSelectFlag\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Table_RowC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Widget\nimport Graphics.UI.FLTK.LowLevel.Table\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\n\ndata TableRowSelectFlag = TableRowSelect | TableRowDeselect | TableRowToggle\n\n{# fun Fl_OverriddenTable_Row_New as tableRowNew' { `Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenTable_Row_New_WithLabel as tableRowNewWithLabel' { `Int',`Int',`Int',`Int', unsafeToCString `String', id `Ptr ()'} -> `Ptr ()' id #}\ntableRowNew :: Rectangle -> Maybe String -> Maybe (Ref TableRow -> IO ()) -> (Ref TableRow -> TableContext -> TableCoordinate -> Rectangle -> IO ()) -> CustomWidgetFuncs TableRow -> CustomTableFuncs TableRow -> IO (Ref TableRow)\ntableRowNew rectangle label' draw' drawCell' customWidgetFuncs' customTableFuncs' =\n do\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n ptr <- tableCustomFunctionStruct draw' (Just drawCell') customWidgetFuncs' customTableFuncs'\n case label' of\n (Just l') -> tableRowNewWithLabel' x_pos y_pos width height l' ptr >>= toRef\n Nothing -> tableRowNew' x_pos y_pos width height ptr >>= toRef\n\n{# fun Fl_Table_Row_Destroy as tableRowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) TableRow orig impl where\n runOp _ _ tableRow = withRef tableRow $ \\tableRowPtr -> tableRowDestroy' tableRowPtr\n{# fun Fl_Table_Row_rows as rows' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetRows ()) TableRow orig impl where\n runOp _ _ tableRow = withRef tableRow $ \\tableRowPtr -> rows' tableRowPtr\n{# fun Fl_Table_Row_set_type as tableRowSetType' { id `Ptr ()', cFromEnum `TableRowSelectMode'} -> `()' #}\ninstance (impl ~ (TableRowSelectMode -> IO ())) => Op (SetType ()) TableRow orig impl where\n runOp _ _ tableRow selectionMode = withRef tableRow $ \\tableRowPtr' -> tableRowSetType' tableRowPtr' selectionMode\n{# fun Fl_Table_Row_type as tableRowType { id `Ptr ()' } -> `TableRowSelectMode' cToEnum #}\ninstance (impl ~ (IO TableRowSelectMode)) => Op (GetType_ ()) TableRow orig impl where\n runOp _ _ tableRow = withRef tableRow $ \\tableRowPtr' -> tableRowType tableRowPtr'\n{# fun Fl_Table_Row_set_rows as setRows' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetRows ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setRows' tablePtr val\n{# fun Fl_Table_Row_set_cols as setCols' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetCols ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setCols' tablePtr val\n{# fun Fl_Table_Row_clear_super as clearSuper' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (ClearSuper ()) TableRow orig impl where\n runOp _ _ table = withRef table $ \\tablePtr -> clearSuper' tablePtr\n{# fun Fl_Table_Row_clear as clear' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (Clear ()) TableRow orig impl where\n runOp _ _ table = withRef table $ \\tablePtr -> clear' tablePtr\n{# fun Fl_Table_Row_set_rows_super as setRowsSuper' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetRowsSuper ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setRowsSuper' tablePtr val\n{# fun Fl_Table_Row_set_cols_super as setColsSuper' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (Int -> IO ())) => Op (SetColsSuper ()) TableRow orig impl where\n runOp _ _ table val = withRef table $ \\tablePtr -> setColsSuper' tablePtr val\n{# fun Fl_Table_Row_handle_super as handleSuper' { id `Ptr ()', cFromEnum `Event' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Int))) => Op (HandleSuper ()) TableRow orig impl where\n runOp _ _ table event = withRef table $ \\tablePtr -> handleSuper' tablePtr event\n{# fun Fl_Table_Row_handle as handle' { id `Ptr ()', cFromEnum `Event' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Int))) => Op (Handle ()) TableRow orig impl where\n runOp _ _ table event = withRef table $ \\tablePtr -> handle' tablePtr event\n{# fun Fl_Table_Row_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (ResizeSuper ()) TableRow orig impl where\n runOp _ _ table rectangle = let (x_pos', y_pos', width', height') = fromRectangle rectangle in withRef table $ \\tablePtr -> resizeSuper' tablePtr x_pos' y_pos' width' height'\n{# fun Fl_Table_Row_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) TableRow orig impl where\n runOp _ _ table rectangle = let (x_pos', y_pos', width', height') = fromRectangle rectangle in withRef table $ \\tablePtr -> resize' tablePtr x_pos' y_pos' width' height'\n{# fun Fl_Table_Row_row_selected as rowSelected' { id `Ptr ()', `Int'} -> `CInt' id #}\ninstance (impl ~ ( Int -> IO (Either OutOfRange Bool))) => Op (GetRowSelected ()) TableRow orig impl where\n runOp _ _ table idx' = withRef table $ \\tablePtr -> do\n ret' <- rowSelected' tablePtr idx'\n if ret' == -1 then (return $ Left OutOfRange) else (return $ Right $ cToBool ret')\n{# fun Fl_Table_Row_select_all_rows_with_flag as selectAllRows' {id `Ptr ()', `Int'} -> `()' #}\ninstance (impl ~ ( TableRowSelectFlag -> IO ())) => Op (SelectAllRows ()) TableRow orig impl where\n runOp _ _ table flag' = withRef table $\n \\tablePtr ->\n case flag' of\n TableRowSelect -> selectAllRows' tablePtr 1\n TableRowDeselect -> selectAllRows' tablePtr 0\n TableRowToggle -> selectAllRows' tablePtr 2\n\n-- $functions\n-- @\n-- clear :: 'Ref' 'TableRow' -> 'IO' ()\n--\n-- clearSuper :: 'Ref' 'TableRow' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'TableRow' -> 'IO' ()\n--\n-- getRowSelected :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ('Either' 'OutOfRange' 'Bool')\n--\n-- getRows :: 'Ref' 'TableRow' -> 'IO' ('Int')\n--\n-- getType_ :: 'Ref' 'TableRow' -> 'IO' 'TableRowSelectMode'\n--\n-- handle :: 'Ref' 'TableRow' -> 'Event' -> 'IO' ('Int')\n--\n-- handleSuper :: 'Ref' 'TableRow' -> 'Event' -> 'IO' ('Int')\n--\n-- resize :: 'Ref' 'TableRow' -> 'Rectangle' -> 'IO' ()\n--\n-- resizeSuper :: 'Ref' 'TableRow' -> 'Rectangle' -> 'IO' ()\n--\n-- selectAllRows :: 'Ref' 'TableRow' -> 'TableRowSelectFlag' -> 'IO' ()\n--\n-- setCols :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setColsSuper :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setRows :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setRowsSuper :: 'Ref' 'TableRow' -> 'Int' -> 'IO' ()\n--\n-- setType :: 'Ref' 'TableRow' -> 'TableRowSelectMode' -> 'IO' ()\n--\n-- @\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Table\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.TableRow\"\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"65f54313ca0c33bddbd8cf19e96bce68c84de00c","subject":"Make valueInit less conservative.","message":"Make valueInit less conservative.","repos":"vincenthz\/webkit","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 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","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@(GValue gvPtr) gt = 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 {# 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":"d2480e480aab24f026a815995d04d6f8ed9005bf","subject":"Correct matrix inversion.","message":"Correct matrix inversion.\n\nCalculating the determinant was incorrect. Pointed out by\nMaur\u00edcio .\n\ndarcs-hash:20060929082643-91c87-14e0697a0ed7104a155d35f39f0f4173f521c57e.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yx - xy*yy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"71e9f07c4fa0c4a12f950c747e508ba9681a4262","subject":"Add missing documentation","message":"Add missing documentation\n","repos":"A1kmm\/happindicator","old_file":"Graphics\/UI\/AppIndicator\/AppIndicator.chs","new_file":"Graphics\/UI\/AppIndicator\/AppIndicator.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- libappindicator widget AppIndicator\n--\n-- Author : Andrew Miller\n--\n-- Created: 1st October 2011\n--\n-- Copyright (C) 2011 Andrew Miller\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-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Create and manipulate menus and icons in the app indications area (as used in\n-- Unity). This code will fall back on using a status icon.\n--\nmodule Graphics.UI.AppIndicator.AppIndicator (\n\n-- * Detail\n--\n-- | The applications indication area is used for menus that provide some\n-- kind of status about the system; there are several predefined menus (for\n-- example, relating to sound, mail), and additional ones can be added. On\n-- platforms not supporting this functionality, the library will fallback\n-- to using a status icon (see Graphics.UI.Gtk.Display.StatusIcon in the\n-- gtk package).\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----AppIndicator\n-- @\n\n-- * Types\n AppIndicator,\n AppIndicatorClass,\n castToAppIndicator, gTypeAppIndicator,\n toAppIndicator,\n\n-- * Constructors\n appIndicatorNew,\n appIndicatorNewWithPath,\n\n-- * Methods\n appIndicatorBuildMenuFromDesktop,\n appIndicatorGetMenu,\n appIndicatorSetMenu,\n appIndicatorGetStatus,\n appIndicatorSetStatus,\n appIndicatorGetCategory,\n \n-- * Attributes\n appIndicatorAttentionIconDesc,\n appIndicatorAttentionIconName,\n appIndicatorCategory,\n appIndicatorConnected,\n appIndicatorIconDesc,\n appIndicatorIconName,\n appIndicatorIconThemePath,\n appIndicatorId,\n appIndicatorLabel,\n appIndicatorLabelGuide,\n appIndicatorOrderingIndex,\n appIndicatorStatus,\n\n-- * Signals\n appIndicatorNewIcon,\n appIndicatorNewAttentionIcon,\n appIndicatorNewStatus,\n appIndicatorNewLabel,\n appIndicatorConnectionChanged,\n appIndicatorNewIconThemePath,\n appIndicatorScrollEvent,\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 System.Glib.GObject\t\t(wrapNewGObject,makeNewGObject)\n{#import Graphics.UI.AppIndicator.Types#}\n{#import Graphics.UI.AppIndicator.Enums#}\n{#import Graphics.UI.AppIndicator.Signals#}\n{#import Graphics.UI.Gtk#}\n{#import Graphics.UI.GtkInternals#}\n\n{# context lib=\"appindicator\" prefix=\"app_indicator\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates an empty AppIndicator object, setting the properties: \"id\" with id,\n-- | \"category\" with category and \"icon-name\" with icon_name.\nappIndicatorNew :: String -> String -> AppIndicatorCategory -> IO AppIndicator\nappIndicatorNew id iconName cat =\n wrapNewGObject mkAppIndicator $ withUTFString id $ \\idPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call app_indicator_new #}\n idPtr iconNamePtr ((fromIntegral . fromEnum) cat)\n\n-- | Creates a new AppIndicator setting the properties: \"id\" with id, \"category\"\n-- | with category, \"icon-name\" with icon_name and \"icon-theme-path\" with\n-- | icon_theme_path. \nappIndicatorNewWithPath :: String -> String -> AppIndicatorCategory -> String -> IO AppIndicator\nappIndicatorNewWithPath id iconName category iconThemePath =\n wrapNewGObject mkAppIndicator $ withUTFString id $ \\idPtr ->\n withUTFString iconName $ \\iconNamePtr -> withUTFString iconThemePath $\n \\iconThemePathPtr ->\n {# call app_indicator_new_with_path #}\n idPtr iconNamePtr ((fromIntegral . fromEnum)category) iconThemePathPtr\n\n-- | This function allows for building the Application Indicator menu from a static\n-- | desktop file. \nappIndicatorBuildMenuFromDesktop :: AppIndicatorClass self => self -> String -> String -> IO ()\nappIndicatorBuildMenuFromDesktop self desktopFile desktopProfile =\n withUTFString desktopFile $ \\desktopFilePtr ->\n withUTFString desktopProfile $ \\desktopProfilePtr ->\n {# call app_indicator_build_menu_from_desktop #}\n (toAppIndicator self) desktopFilePtr desktopProfilePtr\n\n-- | This function retrieves the Application Indicator menu.\nappIndicatorGetMenu :: AppIndicatorClass self => self -> IO Menu\nappIndicatorGetMenu self =\n makeNewGObject mkMenu $ {# call app_indicator_get_menu #} (toAppIndicator self)\n\n-- | This function sets the Application Indicator menu.\nappIndicatorSetMenu :: (AppIndicatorClass self, MenuClass menu) => self -> menu -> IO ()\nappIndicatorSetMenu self menu =\n {# call app_indicator_set_menu #}\n (toAppIndicator self) (toMenu menu)\n\n-- | This function retrieves the current status of the Application Indicator.\nappIndicatorGetStatus :: AppIndicatorClass self => self -> IO AppIndicatorStatus\nappIndicatorGetStatus self =\n liftM (toEnum . fromIntegral) $ {# call app_indicator_get_status #} (toAppIndicator self)\n\n-- | This function set the status of the Application Indicator.\nappIndicatorSetStatus :: AppIndicatorClass self => self -> AppIndicatorStatus -> IO ()\nappIndicatorSetStatus self stat =\n {# call app_indicator_set_status #}\n (toAppIndicator self) ((fromIntegral . fromEnum) stat)\n\n-- | This function retrieves the category of the Application Indicator.\nappIndicatorGetCategory :: AppIndicatorClass self => self -> IO AppIndicatorCategory\nappIndicatorGetCategory self =\n liftM (toEnum . fromIntegral) $ {# call app_indicator_get_category #} (toAppIndicator self)\n\n-- * Attributes\n\n-- | If the indicator sets it's status to APP_INDICATOR_STATUS_ATTENTION then this textual description of the icon shown. \nappIndicatorAttentionIconDesc :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorAttentionIconDesc = newAttrFromMaybeStringProperty \"attention-icon-desc\"\n\n-- | If the indicator sets it's status to APP_INDICATOR_STATUS_ATTENTION then this icon is shown. \nappIndicatorAttentionIconName :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorAttentionIconName = newAttrFromMaybeStringProperty \"attention-icon-name\"\n\n-- | The type of indicator that this represents. Please don't use 'Other'. Defaults to 'ApplicationStatus'.\nappIndicatorCategory :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorCategory = newAttrFromMaybeStringProperty \"category\"\n\n-- | Pretty simple, TRUE if we have a reasonable expectation of being displayed through this object. You should hide your TrayIcon if so. \nappIndicatorConnected :: AppIndicatorClass self => ReadAttr self Bool\nappIndicatorConnected = readAttrFromBoolProperty \"connected\"\n\n-- | The description of the regular icon that is shown for the indicator. \nappIndicatorIconDesc :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorIconDesc = newAttrFromMaybeStringProperty \"icon-desc\"\n\n-- | The name of the regular icon that is shown for the indicator. \nappIndicatorIconName :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorIconName = newAttrFromMaybeStringProperty \"icon-name\"\n\n-- | An additional place to look for icon names that may be installed by the application.\nappIndicatorIconThemePath :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorIconThemePath = newAttrFromMaybeStringProperty \"icon-theme-path\"\n\n-- | The ID for this indicator, which should be unique, but used consistently by this program and its indicator.\nappIndicatorId :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorId = newAttrFromMaybeStringProperty \"id\"\n\n-- | A label that can be shown next to the string in the application indicator. The label will not be shown unless there is an icon as well. The label is useful for numerical and other frequently updated information. In general, it shouldn't be shown unless a user requests it as it can take up a significant amount of space on the user's panel. This may not be shown in all visualizations.\nappIndicatorLabel :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorLabel = newAttrFromMaybeStringProperty \"label\"\n\n-- | An optional string to provide guidance to the panel on how big the \"label\" string could get. If this is set correctly then the panel should never 'jiggle' as the string adjusts through out the range of options. For instance, if you were providing a percentage like \"54% thrust\" in \"label\" you'd want to set this string to \"100% thrust\" to ensure space when Scotty can get you enough power.\nappIndicatorLabelGuide :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorLabelGuide = newAttrFromMaybeStringProperty \"label-guide\"\n\n-- | The ordering index is an odd parameter, and if you think you don't need it you're probably right. In general, the application indicator try to place the applications in a recreatable place taking into account which category they're in to try and group them. But, there are some cases where you'd want to ensure indicators are next to each other. To do that you can override the generated ordering index and replace it with a new one. Again, you probably don't want to be doing this, but in case you do, this is the way.\nappIndicatorOrderingIndex :: AppIndicatorClass self => Attr self Int\nappIndicatorOrderingIndex = newAttrFromUIntProperty \"ordering-index\"\n\n-- | Whether the indicator is shown or requests attention. Defaults to 'Passive'.\nappIndicatorStatus :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorStatus = newAttrFromMaybeStringProperty \"status\"\n\n-- * Signals\n\n-- | Emitted when \"icon-name\" is changed \nappIndicatorNewIcon :: AppIndicatorClass self => Signal self (IO ())\nappIndicatorNewIcon = Signal (connect_NONE__NONE \"new-icon\")\n\n-- | Emitted when \"attention-icon-name\" is changed \nappIndicatorNewAttentionIcon :: AppIndicatorClass self => Signal self (IO ())\nappIndicatorNewAttentionIcon = Signal (connect_NONE__NONE \"new-attention-icon\")\n\n-- | Emitted when \"status\" is changed\nappIndicatorNewStatus :: AppIndicatorClass self => Signal self (String -> IO ())\nappIndicatorNewStatus = Signal (connect_STRING__NONE \"new-status\")\n\n-- | Emitted when either \"label\" or \"label-guide\" are changed. \nappIndicatorNewLabel :: AppIndicatorClass self => Signal self (String -> String -> IO ())\nappIndicatorNewLabel = Signal (connect_STRING_STRING__NONE \"new-label\")\n\n-- | Emitted when we connect to a watcher, or when it drops away. \nappIndicatorConnectionChanged :: AppIndicatorClass self => Signal self (Bool -> IO ())\nappIndicatorConnectionChanged = Signal (connect_BOOL__NONE \"connection-changed\")\n\n-- | Emitted when there is a new icon set for the object. \nappIndicatorNewIconThemePath :: AppIndicatorClass self => Signal self (String -> IO ())\nappIndicatorNewIconThemePath = Signal (connect_STRING__NONE \"new-icon-theme-path\")\n\n-- | Emitted when the AppIndicator receives a scroll event.\nappIndicatorScrollEvent :: AppIndicatorClass self => Signal self (Int -> Int -> IO ())\nappIndicatorScrollEvent = Signal (connect_INT_INT__NONE \"scroll-event\")\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- libappindicator widget AppIndicator\n--\n-- Author : Andrew Miller\n--\n-- Created: 1st October 2011\n--\n-- Copyright (C) 2011 Andrew Miller\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-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Create and manipulate menus and icons in the app indications area (as used in\n-- Unity). This code will fall back on using a status icon.\n--\nmodule Graphics.UI.AppIndicator.AppIndicator (\n\n-- * Detail\n--\n-- | The applications indication area is used for menus that provide some\n-- kind of status about the system; there are several predefined menus (for\n-- example, relating to sound, mail), and additional ones can be added. On\n-- platforms not supporting this functionality, the library will fallback\n-- to using a status icon (see Graphics.UI.Gtk.Display.StatusIcon in the\n-- gtk package).\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----AppIndicator\n-- @\n\n-- * Types\n AppIndicator,\n AppIndicatorClass,\n castToAppIndicator, gTypeAppIndicator,\n toAppIndicator,\n\n-- * Constructors\n appIndicatorNew,\n appIndicatorNewWithPath,\n\n-- * Methods\n appIndicatorBuildMenuFromDesktop,\n appIndicatorGetMenu,\n appIndicatorSetMenu,\n appIndicatorGetStatus,\n appIndicatorSetStatus,\n appIndicatorGetCategory,\n \n-- * Attributes\n appIndicatorAttentionIconDesc,\n appIndicatorAttentionIconName,\n appIndicatorCategory,\n appIndicatorConnected,\n appIndicatorIconDesc,\n appIndicatorIconName,\n appIndicatorIconThemePath,\n appIndicatorId,\n appIndicatorLabel,\n appIndicatorLabelGuide,\n appIndicatorOrderingIndex,\n appIndicatorStatus,\n\n-- * Signals\n appIndicatorNewIcon,\n appIndicatorNewAttentionIcon,\n appIndicatorNewStatus,\n appIndicatorNewLabel,\n appIndicatorConnectionChanged,\n appIndicatorNewIconThemePath,\n appIndicatorScrollEvent,\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 System.Glib.GObject\t\t(wrapNewGObject,makeNewGObject)\n{#import Graphics.UI.AppIndicator.Types#}\n{#import Graphics.UI.AppIndicator.Enums#}\n{#import Graphics.UI.AppIndicator.Signals#}\n{#import Graphics.UI.Gtk#}\n{#import Graphics.UI.GtkInternals#}\n\n{# context lib=\"appindicator\" prefix=\"app_indicator\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates an empty AppIndicator object, setting the properties: \"id\" with id,\n-- | \"category\" with category and \"icon-name\" with icon_name.\nappIndicatorNew :: String -> String -> AppIndicatorCategory -> IO AppIndicator\nappIndicatorNew id iconName cat =\n wrapNewGObject mkAppIndicator $ withUTFString id $ \\idPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call app_indicator_new #}\n idPtr iconNamePtr ((fromIntegral . fromEnum) cat)\n\n-- | Creates a new AppIndicator setting the properties: \"id\" with id, \"category\"\n-- | with category, \"icon-name\" with icon_name and \"icon-theme-path\" with\n-- | icon_theme_path. \nappIndicatorNewWithPath :: String -> String -> AppIndicatorCategory -> String -> IO AppIndicator\nappIndicatorNewWithPath id iconName category iconThemePath =\n wrapNewGObject mkAppIndicator $ withUTFString id $ \\idPtr ->\n withUTFString iconName $ \\iconNamePtr -> withUTFString iconThemePath $\n \\iconThemePathPtr ->\n {# call app_indicator_new_with_path #}\n idPtr iconNamePtr ((fromIntegral . fromEnum)category) iconThemePathPtr\n\n-- | This function allows for building the Application Indicator menu from a static\n-- | desktop file. \nappIndicatorBuildMenuFromDesktop :: AppIndicatorClass self => self -> String -> String -> IO ()\nappIndicatorBuildMenuFromDesktop self desktopFile desktopProfile =\n withUTFString desktopFile $ \\desktopFilePtr ->\n withUTFString desktopProfile $ \\desktopProfilePtr ->\n {# call app_indicator_build_menu_from_desktop #}\n (toAppIndicator self) desktopFilePtr desktopProfilePtr\n\n-- | This function retrieves the Application Indicator menu.\nappIndicatorGetMenu :: AppIndicatorClass self => self -> IO Menu\nappIndicatorGetMenu self =\n makeNewGObject mkMenu $ {# call app_indicator_get_menu #} (toAppIndicator self)\n\n-- | This function sets the Application Indicator menu.\nappIndicatorSetMenu :: (AppIndicatorClass self, MenuClass menu) => self -> menu -> IO ()\nappIndicatorSetMenu self menu =\n {# call app_indicator_set_menu #}\n (toAppIndicator self) (toMenu menu)\n\nappIndicatorGetStatus :: AppIndicatorClass self => self -> IO AppIndicatorStatus\nappIndicatorGetStatus self =\n liftM (toEnum . fromIntegral) $ {# call app_indicator_get_status #} (toAppIndicator self)\n\nappIndicatorSetStatus :: AppIndicatorClass self => self -> AppIndicatorStatus -> IO ()\nappIndicatorSetStatus self stat =\n {# call app_indicator_set_status #}\n (toAppIndicator self) ((fromIntegral . fromEnum) stat)\n\nappIndicatorGetCategory :: AppIndicatorClass self => self -> IO AppIndicatorCategory\nappIndicatorGetCategory self =\n liftM (toEnum . fromIntegral) $ {# call app_indicator_get_category #} (toAppIndicator self)\n\n-- * Attributes\n\n-- | If the indicator sets it's status to APP_INDICATOR_STATUS_ATTENTION then this textual description of the icon shown. \nappIndicatorAttentionIconDesc :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorAttentionIconDesc = newAttrFromMaybeStringProperty \"attention-icon-desc\"\n\n-- | If the indicator sets it's status to APP_INDICATOR_STATUS_ATTENTION then this icon is shown. \nappIndicatorAttentionIconName :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorAttentionIconName = newAttrFromMaybeStringProperty \"attention-icon-name\"\n\n-- | The type of indicator that this represents. Please don't use 'Other'. Defaults to 'ApplicationStatus'.\nappIndicatorCategory :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorCategory = newAttrFromMaybeStringProperty \"category\"\n\n-- | Pretty simple, TRUE if we have a reasonable expectation of being displayed through this object. You should hide your TrayIcon if so. \nappIndicatorConnected :: AppIndicatorClass self => ReadAttr self Bool\nappIndicatorConnected = readAttrFromBoolProperty \"connected\"\n\n-- | The description of the regular icon that is shown for the indicator. \nappIndicatorIconDesc :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorIconDesc = newAttrFromMaybeStringProperty \"icon-desc\"\n\n-- | The name of the regular icon that is shown for the indicator. \nappIndicatorIconName :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorIconName = newAttrFromMaybeStringProperty \"icon-name\"\n\n-- | An additional place to look for icon names that may be installed by the application.\nappIndicatorIconThemePath :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorIconThemePath = newAttrFromMaybeStringProperty \"icon-theme-path\"\n\n-- | The ID for this indicator, which should be unique, but used consistently by this program and its indicator.\nappIndicatorId :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorId = newAttrFromMaybeStringProperty \"id\"\n\n-- | A label that can be shown next to the string in the application indicator. The label will not be shown unless there is an icon as well. The label is useful for numerical and other frequently updated information. In general, it shouldn't be shown unless a user requests it as it can take up a significant amount of space on the user's panel. This may not be shown in all visualizations.\nappIndicatorLabel :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorLabel = newAttrFromMaybeStringProperty \"label\"\n\n-- | An optional string to provide guidance to the panel on how big the \"label\" string could get. If this is set correctly then the panel should never 'jiggle' as the string adjusts through out the range of options. For instance, if you were providing a percentage like \"54% thrust\" in \"label\" you'd want to set this string to \"100% thrust\" to ensure space when Scotty can get you enough power.\nappIndicatorLabelGuide :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorLabelGuide = newAttrFromMaybeStringProperty \"label-guide\"\n\n-- | The ordering index is an odd parameter, and if you think you don't need it you're probably right. In general, the application indicator try to place the applications in a recreatable place taking into account which category they're in to try and group them. But, there are some cases where you'd want to ensure indicators are next to each other. To do that you can override the generated ordering index and replace it with a new one. Again, you probably don't want to be doing this, but in case you do, this is the way.\nappIndicatorOrderingIndex :: AppIndicatorClass self => Attr self Int\nappIndicatorOrderingIndex = newAttrFromUIntProperty \"ordering-index\"\n\n-- | Whether the indicator is shown or requests attention. Defaults to 'Passive'.\nappIndicatorStatus :: AppIndicatorClass self => Attr self (Maybe String)\nappIndicatorStatus = newAttrFromMaybeStringProperty \"status\"\n\n-- * Signals\n\n-- | Emitted when \"icon-name\" is changed \nappIndicatorNewIcon :: AppIndicatorClass self => Signal self (IO ())\nappIndicatorNewIcon = Signal (connect_NONE__NONE \"new-icon\")\n\n-- | Emitted when \"attention-icon-name\" is changed \nappIndicatorNewAttentionIcon :: AppIndicatorClass self => Signal self (IO ())\nappIndicatorNewAttentionIcon = Signal (connect_NONE__NONE \"new-attention-icon\")\n\n-- | Emitted when \"status\" is changed\nappIndicatorNewStatus :: AppIndicatorClass self => Signal self (String -> IO ())\nappIndicatorNewStatus = Signal (connect_STRING__NONE \"new-status\")\n\n-- | Emitted when either \"label\" or \"label-guide\" are changed. \nappIndicatorNewLabel :: AppIndicatorClass self => Signal self (String -> String -> IO ())\nappIndicatorNewLabel = Signal (connect_STRING_STRING__NONE \"new-label\")\n\n-- | Emitted when we connect to a watcher, or when it drops away. \nappIndicatorConnectionChanged :: AppIndicatorClass self => Signal self (Bool -> IO ())\nappIndicatorConnectionChanged = Signal (connect_BOOL__NONE \"connection-changed\")\n\n-- | Emitted when there is a new icon set for the object. \nappIndicatorNewIconThemePath :: AppIndicatorClass self => Signal self (String -> IO ())\nappIndicatorNewIconThemePath = Signal (connect_STRING__NONE \"new-icon-theme-path\")\n\n-- | Emitted when the AppIndicator receives a scroll event.\nappIndicatorScrollEvent :: AppIndicatorClass self => Signal self (Int -> Int -> IO ())\nappIndicatorScrollEvent = Signal (connect_INT_INT__NONE \"scroll-event\")\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"4c589e986906a81450bc295296bb7fe1666f22dd","subject":"Tighten type constraints.","message":"Tighten type constraints.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Menu_Button.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Menu_Button.chs","new_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.FLTK.LowLevel.Fl_Menu_Button\n (\n -- * Constructor\n menuButtonNew,\n menuButtonDestroy,\n -- * Fl_Widget specific\n menuButtonHandle,\n menuButtonParent,\n menuButtonSetParent,\n menuButtonType_,\n menuButtonSetType,\n menuButtonAsWindow,\n menuButtonX,\n menuButtonY,\n menuButtonW,\n menuButtonH,\n menuButtonSetAlign,\n menuButtonAlign,\n menuButtonBox,\n menuButtonSetBox,\n menuButtonColor,\n menuButtonSetColor,\n menuButtonSetColorWithBgSel,\n menuButtonSelectionColor,\n menuButtonSetSelectionColor,\n menuButtonLabel,\n menuButtonCopyLabel,\n menuButtonSetLabel,\n menuButtonLabeltype,\n menuButtonSetLabeltype,\n menuButtonLabelcolor,\n menuButtonSetLabelcolor,\n menuButtonLabelfont,\n menuButtonSetLabelfont,\n menuButtonLabelsize,\n menuButtonSetLabelsize,\n menuButtonImage,\n menuButtonSetImage,\n menuButtonDeimage,\n menuButtonSetDeimage,\n menuButtonTooltip,\n menuButtonCopyTooltip,\n menuButtonSetTooltip,\n menuButtonWhen,\n menuButtonSetWhen,\n menuButtonVisible,\n menuButtonVisibleR,\n menuButtonShow,\n menuButtonHide,\n menuButtonSetVisible,\n menuButtonClearVisible,\n menuButtonActive,\n menuButtonActiveR,\n menuButtonActivate,\n menuButtonDeactivate,\n menuButtonOutput,\n menuButtonSetOutput,\n menuButtonClearOutput,\n menuButtonTakesevents,\n menuButtonSetChanged,\n menuButtonClearChanged,\n menuButtonTakeFocus,\n menuButtonSetVisibleFocus,\n menuButtonClearVisibleFocus,\n menuButtonModifyVisibleFocus,\n menuButtonVisibleFocus,\n menuButtonContains,\n menuButtonInside,\n menuButtonRedraw,\n menuButtonRedrawLabel,\n menuButtonDamage,\n menuButtonClearDamageWithBitmask,\n menuButtonClearDamage,\n menuButtonDamageWithText,\n menuButtonDamageInsideWidget,\n menuButtonMeasureLabel,\n menuButtonWindow,\n menuButtonTopWindow,\n menuButtonTopWindowOffset,\n menuButtonAsGroup,\n menuButtonAsGlWindow,\n menuButtonResize,\n menuButtonSetCallback,\n menuButtonDrawLabel,\n menuButtonValue,\n menuButtonSetValue,\n menuButtonClear,\n menuButtonSetShortcut,\n menuButtonDownBox,\n menuButtonSetDownBox,\n menuButtonDownColor,\n menuButtonSetDownColor,\n menuButtonDrawBox,\n menuButtonDrawBoxWithBoxtype,\n menuButtonDrawBackdrop,\n menuButtonDrawFocus,\n menuButtonItemPathnameWithFinditem,\n menuButtonItemPathname,\n menuButtonPicked,\n menuButtonFind,\n menuButtonTestShortcut,\n menuButtonGlobal,\n menuButtonMenu,\n menuButtonsetMenu,\n menuButtonCopy,\n menuButtonInsert,\n menuButtonAdd,\n menuButtonSize,\n menuButtonSetSize,\n menuButtonClearSubmenu,\n menuButtonReplace,\n menuButtonRemove,\n menuButtonSetMode,\n menuButtonMode,\n menuButtonMvalue,\n menuButtonText,\n menuButtonTextWithIndex,\n menuButtonTextfont,\n menuButtonSetTextfont,\n menuButtonTextsize,\n menuButtonSetTextsize,\n menuButtonTextcolor,\n menuButtonSetTextcolor,\n menuButtonPopup\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Menu_ButtonC.h\"\n#include \"Fl_WidgetC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Menu_\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n{# fun Fl_Menu_Button_New as menuButtonNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Menu_Button_New_WithLabel as menuButtonNewWithLabel' { `Int',`Int',`Int',`Int',`String'} -> `Ptr ()' id #}\nmenuButtonNew :: Rectangle -> Maybe String -> IO (ValueInput ())\nmenuButtonNew rectangle l'=\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case l' of\n Nothing -> menuButtonNew' x_pos y_pos width height >>=\n toObject\n Just l -> menuButtonNewWithLabel' x_pos y_pos width height l >>=\n toObject\n\n{# fun Fl_Menu_Button_Destroy as menuButtonDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nmenuButtonDestroy :: ValueInput a -> IO ()\nmenuButtonDestroy win = swapObject win $ \\winPtr -> do\n menuButtonDestroy' winPtr\n return nullPtr\n\nmenuButtonAsGroup :: MenuButton a -> IO (Group ())\nmenuButtonAsGroup = menu_AsGroup\nmenuButtonAsGlWindow :: MenuButton a -> IO (GlWindow())\nmenuButtonAsGlWindow = menu_AsGlWindow\nmenuButtonResize :: MenuButton a -> Rectangle -> IO (())\nmenuButtonResize = menu_Resize\nmenuButtonAsWindow :: MenuButton a -> IO (Window())\nmenuButtonAsWindow = menu_AsWindow\nmenuButtonHide :: MenuButton a -> IO (())\nmenuButtonHide = menu_Hide\nmenuButtonShow :: MenuButton a -> IO ()\nmenuButtonShow = menu_Show\nmenuButtonDrawBox :: MenuButton a -> IO ()\nmenuButtonDrawBox = menu_DrawBox\nmenuButtonDrawBoxWithBoxtype :: MenuButton a -> Boxtype -> Color -> Maybe Rectangle -> IO ()\nmenuButtonDrawBoxWithBoxtype = menu_DrawBoxWithBoxtype\nmenuButtonDrawBackdrop :: MenuButton a -> IO ()\nmenuButtonDrawBackdrop = menu_DrawBackdrop\nmenuButtonDrawFocus :: MenuButton a -> Maybe (Boxtype, Rectangle) -> IO ()\nmenuButtonDrawFocus = menu_DrawFocus\nmenuButtonSetCallback :: MenuButton a -> (MenuButton b -> IO ()) -> IO (())\nmenuButtonSetCallback = menu_SetCallback\nmenuButtonParent :: MenuButton a -> IO (Group ())\nmenuButtonParent = menu_Parent\nmenuButtonSetParent :: MenuButton a -> Group b -> IO ()\nmenuButtonSetParent = menu_SetParent\nmenuButtonType_ :: MenuButton a -> IO (Word8)\nmenuButtonType_ = menu_Type_\nmenuButtonSetType :: MenuButton a -> Word8 -> IO (())\nmenuButtonSetType = menu_SetType\nmenuButtonDrawLabel :: MenuButton a -> Maybe (Rectangle,AlignType)-> IO (())\nmenuButtonDrawLabel = menu_DrawLabel\nmenuButtonX :: MenuButton a -> IO (Int)\nmenuButtonX = menu_X\nmenuButtonY :: MenuButton a -> IO (Int)\nmenuButtonY = menu_Y\nmenuButtonW :: MenuButton a -> IO (Int)\nmenuButtonW = menu_W\nmenuButtonH :: MenuButton a -> IO (Int)\nmenuButtonH = menu_H\nmenuButtonSetAlign :: MenuButton a -> AlignType -> IO (())\nmenuButtonSetAlign = menu_SetAlign\nmenuButtonAlign :: MenuButton a -> IO (AlignType)\nmenuButtonAlign = menu_Align\nmenuButtonBox :: MenuButton a -> IO (Boxtype)\nmenuButtonBox = menu_Box\nmenuButtonSetBox :: MenuButton a -> Boxtype -> IO (())\nmenuButtonSetBox = menu_SetBox\nmenuButtonColor :: MenuButton a -> IO (Color)\nmenuButtonColor = menu_Color\nmenuButtonSetColor :: MenuButton a -> Color -> IO (())\nmenuButtonSetColor = menu_SetColor\nmenuButtonSetColorWithBgSel :: MenuButton a -> Color -> Color -> IO (())\nmenuButtonSetColorWithBgSel = menu_SetColorWithBgSel\nmenuButtonSelectionColor :: MenuButton a -> IO (Color)\nmenuButtonSelectionColor = menu_SelectionColor\nmenuButtonSetSelectionColor :: MenuButton a -> Color -> IO (())\nmenuButtonSetSelectionColor = menu_SetSelectionColor\nmenuButtonLabel :: MenuButton a -> IO (String)\nmenuButtonLabel = menu_Label\nmenuButtonCopyLabel :: MenuButton a -> String -> IO (())\nmenuButtonCopyLabel = menu_CopyLabel\nmenuButtonSetLabel :: MenuButton a -> String -> IO (())\nmenuButtonSetLabel = menu_SetLabel\nmenuButtonLabeltype :: MenuButton a -> IO (Labeltype)\nmenuButtonLabeltype = menu_Labeltype\nmenuButtonSetLabeltype :: MenuButton a -> Labeltype -> IO (())\nmenuButtonSetLabeltype = menu_SetLabeltype\nmenuButtonLabelcolor :: MenuButton a -> IO (Color)\nmenuButtonLabelcolor = menu_Labelcolor\nmenuButtonSetLabelcolor :: MenuButton a -> Color -> IO (())\nmenuButtonSetLabelcolor = menu_SetLabelcolor\nmenuButtonLabelfont :: MenuButton a -> IO (Font)\nmenuButtonLabelfont = menu_Labelfont\nmenuButtonSetLabelfont :: MenuButton a -> Font -> IO (())\nmenuButtonSetLabelfont = menu_SetLabelfont\nmenuButtonLabelsize :: MenuButton a -> IO (FontSize)\nmenuButtonLabelsize = menu_Labelsize\nmenuButtonSetLabelsize :: MenuButton a -> FontSize -> IO (())\nmenuButtonSetLabelsize = menu_SetLabelsize\nmenuButtonImage :: MenuButton a -> IO (Image ())\nmenuButtonImage = menu_Image\nmenuButtonSetImage :: MenuButton a -> Image b -> IO (())\nmenuButtonSetImage = menu_SetImage\nmenuButtonDeimage :: MenuButton a -> IO (Image ())\nmenuButtonDeimage = menu_Deimage\nmenuButtonSetDeimage :: MenuButton a -> Image b -> IO (())\nmenuButtonSetDeimage = menu_SetDeimage\nmenuButtonTooltip :: MenuButton a -> IO (String)\nmenuButtonTooltip = menu_Tooltip\nmenuButtonCopyTooltip :: MenuButton a -> String -> IO (())\nmenuButtonCopyTooltip = menu_CopyTooltip\nmenuButtonSetTooltip :: MenuButton a -> String -> IO (())\nmenuButtonSetTooltip = menu_SetTooltip\nmenuButtonWhen :: MenuButton a -> IO (When)\nmenuButtonWhen = menu_When\nmenuButtonSetWhen :: MenuButton a -> Word8 -> IO (())\nmenuButtonSetWhen = menu_SetWhen\nmenuButtonVisible :: MenuButton a -> IO (Int)\nmenuButtonVisible = menu_Visible\nmenuButtonVisibleR :: MenuButton a -> IO (Int)\nmenuButtonVisibleR = menu_VisibleR\nmenuButtonSetVisible :: MenuButton a -> IO (())\nmenuButtonSetVisible = menu_SetVisible\nmenuButtonClearVisible :: MenuButton a -> IO (())\nmenuButtonClearVisible = menu_ClearVisible\nmenuButtonActive :: MenuButton a -> IO (Int)\nmenuButtonActive = menu_Active\nmenuButtonActiveR :: MenuButton a -> IO (Int)\nmenuButtonActiveR = menu_ActiveR\nmenuButtonActivate :: MenuButton a -> IO (())\nmenuButtonActivate = menu_Activate\nmenuButtonDeactivate :: MenuButton a -> IO (())\nmenuButtonDeactivate = menu_Deactivate\nmenuButtonOutput :: MenuButton a -> IO (Int)\nmenuButtonOutput = menu_Output\nmenuButtonSetOutput :: MenuButton a -> IO (())\nmenuButtonSetOutput = menu_SetOutput\nmenuButtonClearOutput :: MenuButton a -> IO (())\nmenuButtonClearOutput = menu_ClearOutput\nmenuButtonTakesevents :: MenuButton a -> IO (Int)\nmenuButtonTakesevents = menu_Takesevents\nmenuButtonSetChanged :: MenuButton a -> IO (())\nmenuButtonSetChanged = menu_SetChanged\nmenuButtonClearChanged :: MenuButton a -> IO (())\nmenuButtonClearChanged = menu_ClearChanged\nmenuButtonTakeFocus :: MenuButton a -> IO (Int)\nmenuButtonTakeFocus = menu_TakeFocus\nmenuButtonSetVisibleFocus :: MenuButton a -> IO (())\nmenuButtonSetVisibleFocus = menu_SetVisibleFocus\nmenuButtonClearVisibleFocus :: MenuButton a -> IO (())\nmenuButtonClearVisibleFocus = menu_ClearVisibleFocus\nmenuButtonModifyVisibleFocus :: MenuButton a -> Int -> IO (())\nmenuButtonModifyVisibleFocus = menu_ModifyVisibleFocus\nmenuButtonVisibleFocus :: MenuButton a -> IO (Int)\nmenuButtonVisibleFocus = menu_VisibleFocus\nmenuButtonContains :: MenuButton a -> Widget b -> IO (Int)\nmenuButtonContains = menu_Contains\nmenuButtonInside :: MenuButton a -> MenuButton a -> IO (Int)\nmenuButtonInside = menu_Inside\nmenuButtonRedraw :: MenuButton a -> IO (())\nmenuButtonRedraw = menu_Redraw\nmenuButtonRedrawLabel :: MenuButton a -> IO (())\nmenuButtonRedrawLabel = menu_RedrawLabel\nmenuButtonDamage :: MenuButton a -> IO (Word8)\nmenuButtonDamage = menu_Damage\nmenuButtonClearDamageWithBitmask :: MenuButton a -> Word8 -> IO (())\nmenuButtonClearDamageWithBitmask = menu_ClearDamageWithBitmask\nmenuButtonClearDamage :: MenuButton a -> IO (())\nmenuButtonClearDamage = menu_ClearDamage\nmenuButtonDamageWithText :: MenuButton a -> Word8 -> IO (())\nmenuButtonDamageWithText = menu_DamageWithText\nmenuButtonDamageInsideWidget :: MenuButton a -> Word8 -> Rectangle -> IO (())\nmenuButtonDamageInsideWidget = menu_DamageInsideWidget\nmenuButtonMeasureLabel :: MenuButton a -> IO (Size)\nmenuButtonMeasureLabel = menu_MeasureLabel\nmenuButtonWindow :: MenuButton a -> IO (Window ())\nmenuButtonWindow = menu_Window\nmenuButtonTopWindow :: MenuButton a -> IO (Window ())\nmenuButtonTopWindow = menu_TopWindow\nmenuButtonTopWindowOffset :: MenuButton a -> IO (Position)\nmenuButtonTopWindowOffset = menu_TopWindowOffset\nmenuButtonItemPathnameWithFinditem :: MenuButton a -> String -> Int -> MenuItem b -> IO (Int)\nmenuButtonItemPathnameWithFinditem = menu_ItemPathnameWithFinditem\nmenuButtonItemPathname :: MenuButton a -> String -> Int -> IO (Int)\nmenuButtonItemPathname = menu_ItemPathname\nmenuButtonPicked :: MenuButton a -> MenuItem b -> IO (MenuItem b)\nmenuButtonPicked = menu_Picked\nmenuButtonFind :: MenuButton a -> MenuItemLocator b -> IO (Int)\nmenuButtonFind = menu_Find\nmenuButtonTestShortcut :: MenuButton a -> IO (MenuItem b)\nmenuButtonTestShortcut = menu_TestShortcut\nmenuButtonGlobal :: MenuButton a -> IO ()\nmenuButtonGlobal = menu_Global\nmenuButtonMenu :: MenuButton a -> IO (MenuButton a)\nmenuButtonMenu = menu_Menu\nmenuButtonsetMenu :: MenuButton a -> [MenuItem b] -> IO ()\nmenuButtonsetMenu = menu_setMenu\nmenuButtonCopy :: MenuButton a -> MenuItem b -> IO ()\nmenuButtonCopy = menu_Copy\nmenuButtonInsert :: MenuButton a -> Int -> String -> Shortcut -> (MenuButton a -> IO ()) -> [MenuProps] -> IO (Int)\nmenuButtonInsert = menu_Insert\nmenuButtonAdd :: MenuItem a -> String -> Shortcut -> (MenuButton b -> IO ()) -> [MenuProps] -> IO (Int)\nmenuButtonAdd = menu_Add\nmenuButtonSize :: MenuButton a -> IO (Int)\nmenuButtonSize = menu_Size\nmenuButtonSetSize :: MenuButton a -> Int -> Int -> IO ()\nmenuButtonSetSize = menu_SetSize\nmenuButtonClear :: MenuButton a -> IO ()\nmenuButtonClear = menu_Clear\nmenuButtonClearSubmenu :: MenuButton a -> Int -> IO (Int)\nmenuButtonClearSubmenu = menu_ClearSubmenu\nmenuButtonReplace :: MenuButton a -> Int -> String -> IO ()\nmenuButtonReplace = menu_Replace\nmenuButtonRemove :: MenuButton a -> Int -> IO ()\nmenuButtonRemove = menu_Remove\nmenuButtonSetShortcut :: MenuButton a -> Int -> ShortcutKeySequence -> IO ()\nmenuButtonSetShortcut = menu_SetShortcut\nmenuButtonSetMode :: MenuButton a -> Int -> Int -> IO ()\nmenuButtonSetMode = menu_SetMode\nmenuButtonMode :: MenuButton a -> Int -> IO (Int)\nmenuButtonMode = menu_Mode\nmenuButtonMvalue :: MenuButton a -> IO (MenuItem b)\nmenuButtonMvalue = menu_Mvalue\nmenuButtonValue :: MenuButton a -> IO (Int)\nmenuButtonValue = menu_Value\nmenuButtonSetValue :: MenuButton a -> MenuItemReference b -> IO (Int)\nmenuButtonSetValue = menu_SetValue\nmenuButtonText :: MenuButton a -> IO (String)\nmenuButtonText = menu_Text\nmenuButtonTextWithIndex :: MenuButton a -> Int -> IO (String)\nmenuButtonTextWithIndex = menu_TextWithIndex\nmenuButtonTextfont :: MenuButton a -> IO (Font)\nmenuButtonTextfont = menu_Textfont\nmenuButtonSetTextfont :: MenuButton a -> Font -> IO ()\nmenuButtonSetTextfont = menu_SetTextfont\nmenuButtonTextsize :: MenuButton a -> IO (FontSize)\nmenuButtonTextsize = menu_Textsize\nmenuButtonSetTextsize :: MenuButton a -> FontSize -> IO ()\nmenuButtonSetTextsize = menu_SetTextsize\nmenuButtonTextcolor :: MenuButton a -> IO (Color)\nmenuButtonTextcolor = menu_Textcolor\nmenuButtonSetTextcolor :: MenuButton a -> Color -> IO ()\nmenuButtonSetTextcolor = menu_SetTextcolor\nmenuButtonDownBox :: MenuButton a -> IO (Boxtype)\nmenuButtonDownBox = menu_DownBox\nmenuButtonSetDownBox :: MenuButton a -> Boxtype -> IO ()\nmenuButtonSetDownBox = menu_SetDownBox\nmenuButtonDownColor :: MenuButton a -> IO (Color)\nmenuButtonDownColor = menu_DownColor\nmenuButtonSetDownColor :: MenuButton a -> Int -> IO ()\nmenuButtonSetDownColor = menu_SetDownColor\n{#fun Fl_Menu_Button_handle as menuButtonHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\nmenuButtonHandle :: MenuButton a -> Event -> IO Int\nmenuButtonHandle menu_bar event = withObject menu_bar (\\p -> menuButtonHandle' p (fromIntegral . fromEnum $ event))\n{#fun Fl_Menu_Button_popup as menuButtonPopup' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuButtonPopup :: MenuButton a -> IO (MenuItem ())\nmenuButtonPopup menu_bar = withObject menu_bar (\\p -> menuButtonPopup' p >>= toObject)\n","old_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.FLTK.LowLevel.Fl_Menu_Button\n (\n -- * Constructor\n menuButtonNew,\n menuButtonDestroy,\n -- * Fl_Widget specific\n menuButtonHandle,\n menuButtonParent,\n menuButtonSetParent,\n menuButtonType_,\n menuButtonSetType,\n menuButtonAsWindow,\n menuButtonX,\n menuButtonY,\n menuButtonW,\n menuButtonH,\n menuButtonSetAlign,\n menuButtonAlign,\n menuButtonBox,\n menuButtonSetBox,\n menuButtonColor,\n menuButtonSetColor,\n menuButtonSetColorWithBgSel,\n menuButtonSelectionColor,\n menuButtonSetSelectionColor,\n menuButtonLabel,\n menuButtonCopyLabel,\n menuButtonSetLabel,\n menuButtonLabeltype,\n menuButtonSetLabeltype,\n menuButtonLabelcolor,\n menuButtonSetLabelcolor,\n menuButtonLabelfont,\n menuButtonSetLabelfont,\n menuButtonLabelsize,\n menuButtonSetLabelsize,\n menuButtonImage,\n menuButtonSetImage,\n menuButtonDeimage,\n menuButtonSetDeimage,\n menuButtonTooltip,\n menuButtonCopyTooltip,\n menuButtonSetTooltip,\n menuButtonWhen,\n menuButtonSetWhen,\n menuButtonVisible,\n menuButtonVisibleR,\n menuButtonShow,\n menuButtonHide,\n menuButtonSetVisible,\n menuButtonClearVisible,\n menuButtonActive,\n menuButtonActiveR,\n menuButtonActivate,\n menuButtonDeactivate,\n menuButtonOutput,\n menuButtonSetOutput,\n menuButtonClearOutput,\n menuButtonTakesevents,\n menuButtonSetChanged,\n menuButtonClearChanged,\n menuButtonTakeFocus,\n menuButtonSetVisibleFocus,\n menuButtonClearVisibleFocus,\n menuButtonModifyVisibleFocus,\n menuButtonVisibleFocus,\n menuButtonContains,\n menuButtonInside,\n menuButtonRedraw,\n menuButtonRedrawLabel,\n menuButtonDamage,\n menuButtonClearDamageWithBitmask,\n menuButtonClearDamage,\n menuButtonDamageWithText,\n menuButtonDamageInsideWidget,\n menuButtonMeasureLabel,\n menuButtonWindow,\n menuButtonTopWindow,\n menuButtonTopWindowOffset,\n menuButtonAsGroup,\n menuButtonAsGlWindow,\n menuButtonResize,\n menuButtonSetCallback,\n menuButtonDrawLabel,\n menuButtonValue,\n menuButtonSetValue,\n menuButtonClear,\n menuButtonSetShortcut,\n menuButtonDownBox,\n menuButtonSetDownBox,\n menuButtonDownColor,\n menuButtonSetDownColor,\n menuButtonDrawBox,\n menuButtonDrawBoxWithBoxtype,\n menuButtonDrawBackdrop,\n menuButtonDrawFocus,\n menuButtonItemPathnameWithFinditem,\n menuButtonItemPathname,\n menuButtonPicked,\n menuButtonFind,\n menuButtonTestShortcut,\n menuButtonGlobal,\n menuButtonMenu,\n menuButtonsetMenu,\n menuButtonCopy,\n menuButtonInsert,\n menuButtonAdd,\n menuButtonSize,\n menuButtonSetSize,\n menuButtonClearSubmenu,\n menuButtonReplace,\n menuButtonRemove,\n menuButtonSetMode,\n menuButtonMode,\n menuButtonMvalue,\n menuButtonText,\n menuButtonTextWithIndex,\n menuButtonTextfont,\n menuButtonSetTextfont,\n menuButtonTextsize,\n menuButtonSetTextsize,\n menuButtonTextcolor,\n menuButtonSetTextcolor,\n menuButtonPopup\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Menu_ButtonC.h\"\n#include \"Fl_WidgetC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Menu_\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n{# fun Fl_Menu_Button_New as menuButtonNew' { `Int',`Int',`Int',`Int' } -> `Ptr ()' id #}\n{# fun Fl_Menu_Button_New_WithLabel as menuButtonNewWithLabel' { `Int',`Int',`Int',`Int',`String'} -> `Ptr ()' id #}\nmenuButtonNew :: Rectangle -> Maybe String -> IO (ValueInput ())\nmenuButtonNew rectangle l'=\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in case l' of\n Nothing -> menuButtonNew' x_pos y_pos width height >>=\n toObject\n Just l -> menuButtonNewWithLabel' x_pos y_pos width height l >>=\n toObject\n\n{# fun Fl_Menu_Button_Destroy as menuButtonDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nmenuButtonDestroy :: ValueInput a -> IO ()\nmenuButtonDestroy win = swapObject win $ \\winPtr -> do\n menuButtonDestroy' winPtr\n return nullPtr\n\nmenuButtonAsGroup :: SysMenuBar a -> IO (Group ())\nmenuButtonAsGroup = menu_AsGroup\nmenuButtonAsGlWindow :: SysMenuBar a -> IO (GlWindow())\nmenuButtonAsGlWindow = menu_AsGlWindow\nmenuButtonResize :: SysMenuBar a -> Rectangle -> IO (())\nmenuButtonResize = menu_Resize\nmenuButtonAsWindow :: SysMenuBar a -> IO (Window())\nmenuButtonAsWindow = menu_AsWindow\nmenuButtonHide :: SysMenuBar a -> IO (())\nmenuButtonHide = menu_Hide\nmenuButtonShow :: SysMenuBar a -> IO ()\nmenuButtonShow = menu_Show\nmenuButtonDrawBox :: SysMenuBar a -> IO ()\nmenuButtonDrawBox = menu_DrawBox\nmenuButtonDrawBoxWithBoxtype :: SysMenuBar a -> Boxtype -> Color -> Maybe Rectangle -> IO ()\nmenuButtonDrawBoxWithBoxtype = menu_DrawBoxWithBoxtype\nmenuButtonDrawBackdrop :: SysMenuBar a -> IO ()\nmenuButtonDrawBackdrop = menu_DrawBackdrop\nmenuButtonDrawFocus :: SysMenuBar a -> Maybe (Boxtype, Rectangle) -> IO ()\nmenuButtonDrawFocus = menu_DrawFocus\nmenuButtonSetCallback :: SysMenuBar a -> (SysMenuBar b -> IO ()) -> IO (())\nmenuButtonSetCallback = menu_SetCallback\nmenuButtonParent :: SysMenuBar a -> IO (Group ())\nmenuButtonParent = menu_Parent\nmenuButtonSetParent :: SysMenuBar a -> Group b -> IO ()\nmenuButtonSetParent = menu_SetParent\nmenuButtonType_ :: SysMenuBar a -> IO (Word8)\nmenuButtonType_ = menu_Type_\nmenuButtonSetType :: SysMenuBar a -> Word8 -> IO (())\nmenuButtonSetType = menu_SetType\nmenuButtonDrawLabel :: SysMenuBar a -> Maybe (Rectangle,AlignType)-> IO (())\nmenuButtonDrawLabel = menu_DrawLabel\nmenuButtonX :: SysMenuBar a -> IO (Int)\nmenuButtonX = menu_X\nmenuButtonY :: SysMenuBar a -> IO (Int)\nmenuButtonY = menu_Y\nmenuButtonW :: SysMenuBar a -> IO (Int)\nmenuButtonW = menu_W\nmenuButtonH :: SysMenuBar a -> IO (Int)\nmenuButtonH = menu_H\nmenuButtonSetAlign :: SysMenuBar a -> AlignType -> IO (())\nmenuButtonSetAlign = menu_SetAlign\nmenuButtonAlign :: SysMenuBar a -> IO (AlignType)\nmenuButtonAlign = menu_Align\nmenuButtonBox :: SysMenuBar a -> IO (Boxtype)\nmenuButtonBox = menu_Box\nmenuButtonSetBox :: SysMenuBar a -> Boxtype -> IO (())\nmenuButtonSetBox = menu_SetBox\nmenuButtonColor :: SysMenuBar a -> IO (Color)\nmenuButtonColor = menu_Color\nmenuButtonSetColor :: SysMenuBar a -> Color -> IO (())\nmenuButtonSetColor = menu_SetColor\nmenuButtonSetColorWithBgSel :: SysMenuBar a -> Color -> Color -> IO (())\nmenuButtonSetColorWithBgSel = menu_SetColorWithBgSel\nmenuButtonSelectionColor :: SysMenuBar a -> IO (Color)\nmenuButtonSelectionColor = menu_SelectionColor\nmenuButtonSetSelectionColor :: SysMenuBar a -> Color -> IO (())\nmenuButtonSetSelectionColor = menu_SetSelectionColor\nmenuButtonLabel :: SysMenuBar a -> IO (String)\nmenuButtonLabel = menu_Label\nmenuButtonCopyLabel :: SysMenuBar a -> String -> IO (())\nmenuButtonCopyLabel = menu_CopyLabel\nmenuButtonSetLabel :: SysMenuBar a -> String -> IO (())\nmenuButtonSetLabel = menu_SetLabel\nmenuButtonLabeltype :: SysMenuBar a -> IO (Labeltype)\nmenuButtonLabeltype = menu_Labeltype\nmenuButtonSetLabeltype :: SysMenuBar a -> Labeltype -> IO (())\nmenuButtonSetLabeltype = menu_SetLabeltype\nmenuButtonLabelcolor :: SysMenuBar a -> IO (Color)\nmenuButtonLabelcolor = menu_Labelcolor\nmenuButtonSetLabelcolor :: SysMenuBar a -> Color -> IO (())\nmenuButtonSetLabelcolor = menu_SetLabelcolor\nmenuButtonLabelfont :: SysMenuBar a -> IO (Font)\nmenuButtonLabelfont = menu_Labelfont\nmenuButtonSetLabelfont :: SysMenuBar a -> Font -> IO (())\nmenuButtonSetLabelfont = menu_SetLabelfont\nmenuButtonLabelsize :: SysMenuBar a -> IO (FontSize)\nmenuButtonLabelsize = menu_Labelsize\nmenuButtonSetLabelsize :: SysMenuBar a -> FontSize -> IO (())\nmenuButtonSetLabelsize = menu_SetLabelsize\nmenuButtonImage :: SysMenuBar a -> IO (Image ())\nmenuButtonImage = menu_Image\nmenuButtonSetImage :: SysMenuBar a -> Image b -> IO (())\nmenuButtonSetImage = menu_SetImage\nmenuButtonDeimage :: SysMenuBar a -> IO (Image ())\nmenuButtonDeimage = menu_Deimage\nmenuButtonSetDeimage :: SysMenuBar a -> Image b -> IO (())\nmenuButtonSetDeimage = menu_SetDeimage\nmenuButtonTooltip :: SysMenuBar a -> IO (String)\nmenuButtonTooltip = menu_Tooltip\nmenuButtonCopyTooltip :: SysMenuBar a -> String -> IO (())\nmenuButtonCopyTooltip = menu_CopyTooltip\nmenuButtonSetTooltip :: SysMenuBar a -> String -> IO (())\nmenuButtonSetTooltip = menu_SetTooltip\nmenuButtonWhen :: SysMenuBar a -> IO (When)\nmenuButtonWhen = menu_When\nmenuButtonSetWhen :: SysMenuBar a -> Word8 -> IO (())\nmenuButtonSetWhen = menu_SetWhen\nmenuButtonVisible :: SysMenuBar a -> IO (Int)\nmenuButtonVisible = menu_Visible\nmenuButtonVisibleR :: SysMenuBar a -> IO (Int)\nmenuButtonVisibleR = menu_VisibleR\nmenuButtonSetVisible :: SysMenuBar a -> IO (())\nmenuButtonSetVisible = menu_SetVisible\nmenuButtonClearVisible :: SysMenuBar a -> IO (())\nmenuButtonClearVisible = menu_ClearVisible\nmenuButtonActive :: SysMenuBar a -> IO (Int)\nmenuButtonActive = menu_Active\nmenuButtonActiveR :: SysMenuBar a -> IO (Int)\nmenuButtonActiveR = menu_ActiveR\nmenuButtonActivate :: SysMenuBar a -> IO (())\nmenuButtonActivate = menu_Activate\nmenuButtonDeactivate :: SysMenuBar a -> IO (())\nmenuButtonDeactivate = menu_Deactivate\nmenuButtonOutput :: SysMenuBar a -> IO (Int)\nmenuButtonOutput = menu_Output\nmenuButtonSetOutput :: SysMenuBar a -> IO (())\nmenuButtonSetOutput = menu_SetOutput\nmenuButtonClearOutput :: SysMenuBar a -> IO (())\nmenuButtonClearOutput = menu_ClearOutput\nmenuButtonTakesevents :: SysMenuBar a -> IO (Int)\nmenuButtonTakesevents = menu_Takesevents\nmenuButtonSetChanged :: SysMenuBar a -> IO (())\nmenuButtonSetChanged = menu_SetChanged\nmenuButtonClearChanged :: SysMenuBar a -> IO (())\nmenuButtonClearChanged = menu_ClearChanged\nmenuButtonTakeFocus :: SysMenuBar a -> IO (Int)\nmenuButtonTakeFocus = menu_TakeFocus\nmenuButtonSetVisibleFocus :: SysMenuBar a -> IO (())\nmenuButtonSetVisibleFocus = menu_SetVisibleFocus\nmenuButtonClearVisibleFocus :: SysMenuBar a -> IO (())\nmenuButtonClearVisibleFocus = menu_ClearVisibleFocus\nmenuButtonModifyVisibleFocus :: SysMenuBar a -> Int -> IO (())\nmenuButtonModifyVisibleFocus = menu_ModifyVisibleFocus\nmenuButtonVisibleFocus :: SysMenuBar a -> IO (Int)\nmenuButtonVisibleFocus = menu_VisibleFocus\nmenuButtonContains :: SysMenuBar a -> Widget b -> IO (Int)\nmenuButtonContains = menu_Contains\nmenuButtonInside :: SysMenuBar a -> SysMenuBar a -> IO (Int)\nmenuButtonInside = menu_Inside\nmenuButtonRedraw :: SysMenuBar a -> IO (())\nmenuButtonRedraw = menu_Redraw\nmenuButtonRedrawLabel :: SysMenuBar a -> IO (())\nmenuButtonRedrawLabel = menu_RedrawLabel\nmenuButtonDamage :: SysMenuBar a -> IO (Word8)\nmenuButtonDamage = menu_Damage\nmenuButtonClearDamageWithBitmask :: SysMenuBar a -> Word8 -> IO (())\nmenuButtonClearDamageWithBitmask = menu_ClearDamageWithBitmask\nmenuButtonClearDamage :: SysMenuBar a -> IO (())\nmenuButtonClearDamage = menu_ClearDamage\nmenuButtonDamageWithText :: SysMenuBar a -> Word8 -> IO (())\nmenuButtonDamageWithText = menu_DamageWithText\nmenuButtonDamageInsideWidget :: SysMenuBar a -> Word8 -> Rectangle -> IO (())\nmenuButtonDamageInsideWidget = menu_DamageInsideWidget\nmenuButtonMeasureLabel :: SysMenuBar a -> IO (Size)\nmenuButtonMeasureLabel = menu_MeasureLabel\nmenuButtonWindow :: SysMenuBar a -> IO (Window ())\nmenuButtonWindow = menu_Window\nmenuButtonTopWindow :: SysMenuBar a -> IO (Window ())\nmenuButtonTopWindow = menu_TopWindow\nmenuButtonTopWindowOffset :: SysMenuBar a -> IO (Position)\nmenuButtonTopWindowOffset = menu_TopWindowOffset\nmenuButtonItemPathnameWithFinditem :: SysMenuBar a -> String -> Int -> MenuItem b -> IO (Int)\nmenuButtonItemPathnameWithFinditem = menu_ItemPathnameWithFinditem\nmenuButtonItemPathname :: SysMenuBar a -> String -> Int -> IO (Int)\nmenuButtonItemPathname = menu_ItemPathname\nmenuButtonPicked :: SysMenuBar a -> MenuItem b -> IO (MenuItem b)\nmenuButtonPicked = menu_Picked\nmenuButtonFind :: SysMenuBar a -> MenuItemLocator b -> IO (Int)\nmenuButtonFind = menu_Find\nmenuButtonTestShortcut :: SysMenuBar a -> IO (MenuItem b)\nmenuButtonTestShortcut = menu_TestShortcut\nmenuButtonGlobal :: SysMenuBar a -> IO ()\nmenuButtonGlobal = menu_Global\nmenuButtonMenu :: SysMenuBar a -> IO (SysMenuBar a)\nmenuButtonMenu = menu_Menu\nmenuButtonsetMenu :: SysMenuBar a -> [MenuItem b] -> IO ()\nmenuButtonsetMenu = menu_setMenu\nmenuButtonCopy :: SysMenuBar a -> MenuItem b -> IO ()\nmenuButtonCopy = menu_Copy\nmenuButtonInsert :: SysMenuBar a -> Int -> String -> Shortcut -> (SysMenuBar a -> IO ()) -> [MenuProps] -> IO (Int)\nmenuButtonInsert = menu_Insert\nmenuButtonAdd :: MenuItem a -> String -> Shortcut -> (SysMenuBar b -> IO ()) -> [MenuProps] -> IO (Int)\nmenuButtonAdd = menu_Add\nmenuButtonSize :: SysMenuBar a -> IO (Int)\nmenuButtonSize = menu_Size\nmenuButtonSetSize :: SysMenuBar a -> Int -> Int -> IO ()\nmenuButtonSetSize = menu_SetSize\nmenuButtonClear :: SysMenuBar a -> IO ()\nmenuButtonClear = menu_Clear\nmenuButtonClearSubmenu :: SysMenuBar a -> Int -> IO (Int)\nmenuButtonClearSubmenu = menu_ClearSubmenu\nmenuButtonReplace :: SysMenuBar a -> Int -> String -> IO ()\nmenuButtonReplace = menu_Replace\nmenuButtonRemove :: SysMenuBar a -> Int -> IO ()\nmenuButtonRemove = menu_Remove\nmenuButtonSetShortcut :: SysMenuBar a -> Int -> ShortcutKeySequence -> IO ()\nmenuButtonSetShortcut = menu_SetShortcut\nmenuButtonSetMode :: SysMenuBar a -> Int -> Int -> IO ()\nmenuButtonSetMode = menu_SetMode\nmenuButtonMode :: SysMenuBar a -> Int -> IO (Int)\nmenuButtonMode = menu_Mode\nmenuButtonMvalue :: SysMenuBar a -> IO (MenuItem b)\nmenuButtonMvalue = menu_Mvalue\nmenuButtonValue :: SysMenuBar a -> IO (Int)\nmenuButtonValue = menu_Value\nmenuButtonSetValue :: SysMenuBar a -> MenuItemReference b -> IO (Int)\nmenuButtonSetValue = menu_SetValue\nmenuButtonText :: SysMenuBar a -> IO (String)\nmenuButtonText = menu_Text\nmenuButtonTextWithIndex :: SysMenuBar a -> Int -> IO (String)\nmenuButtonTextWithIndex = menu_TextWithIndex\nmenuButtonTextfont :: SysMenuBar a -> IO (Font)\nmenuButtonTextfont = menu_Textfont\nmenuButtonSetTextfont :: SysMenuBar a -> Font -> IO ()\nmenuButtonSetTextfont = menu_SetTextfont\nmenuButtonTextsize :: SysMenuBar a -> IO (FontSize)\nmenuButtonTextsize = menu_Textsize\nmenuButtonSetTextsize :: SysMenuBar a -> FontSize -> IO ()\nmenuButtonSetTextsize = menu_SetTextsize\nmenuButtonTextcolor :: SysMenuBar a -> IO (Color)\nmenuButtonTextcolor = menu_Textcolor\nmenuButtonSetTextcolor :: SysMenuBar a -> Color -> IO ()\nmenuButtonSetTextcolor = menu_SetTextcolor\nmenuButtonDownBox :: SysMenuBar a -> IO (Boxtype)\nmenuButtonDownBox = menu_DownBox\nmenuButtonSetDownBox :: SysMenuBar a -> Boxtype -> IO ()\nmenuButtonSetDownBox = menu_SetDownBox\nmenuButtonDownColor :: SysMenuBar a -> IO (Color)\nmenuButtonDownColor = menu_DownColor\nmenuButtonSetDownColor :: SysMenuBar a -> Int -> IO ()\nmenuButtonSetDownColor = menu_SetDownColor\n{#fun Fl_Menu_Button_handle as menuButtonHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\nmenuButtonHandle :: SysMenuBar a -> Event -> IO Int\nmenuButtonHandle menu_bar event = withObject menu_bar (\\p -> menuButtonHandle' p (fromIntegral . fromEnum $ event))\n{#fun Fl_Menu_Button_popup as menuButtonPopup' { id `Ptr ()' } -> `Ptr ()' id #}\nmenuButtonPopup :: SysMenuBar a -> IO (MenuItem ())\nmenuButtonPopup menu_bar = withObject menu_bar (\\p -> menuButtonPopup' p >>= toObject)\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"177178d89872fc17dac5cd9e58ba835f89aec2c8","subject":"efficient masked. readBand needs to be inlined","message":"efficient masked. readBand needs to be inlined\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , SomeDataset (..)\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , unValue\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , openAnyReadOnly\n , openAnyReadWrite\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , getMaskBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Data.Coerce (coerce)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value {-# UNPACK #-} !a | NoData deriving (Eq, Show)\n\nunValue :: Value a -> a\nunValue (Value a) = a\nunValue NoData = error \"called unValue on NoData\"\n{-# INLINE unValue #-}\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: GDALType a => FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p >>= checkType\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\nopenAnyWithMode :: forall s t. Access -> String -> GDAL s (SomeDataset s t)\nopenAnyWithMode m p = do\n ds <- openWithMode m p\n dt <- getBand ds 1 >>= bandDatatype\n case dt of\n GDT_Byte -> return $ SomeDataset ((coerce ds) :: Dataset s t Word8)\n GDT_UInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word16)\n GDT_UInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word32)\n GDT_Int16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int16)\n GDT_Int32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int32)\n GDT_Float32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Float)\n GDT_Float64 -> return $ SomeDataset ((coerce ds) :: Dataset s t Double)\n GDT_CInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int16))\n GDT_CInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int32))\n GDT_CFloat32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Float))\n GDT_CFloat64 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Double))\n _ -> liftIO (throw InvalidType)\n\ncheckType\n :: forall s t a. GDALType a\n => Dataset s t a -> GDAL s (Dataset s t a)\ncheckType ds = do\n c <- datasetBandCount ds\n if c > 0\n then do\n b <- getBand ds 1\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ds\n else liftIO (throw InvalidType)\n else return ds\n\ndata SomeDataset s (t :: DatasetMode)\n = forall a. GDALType a => SomeDataset (Dataset s t a)\n\nopenAnyReadOnly :: forall s. FilePath -> GDAL s (SomeDataset s ReadOnly)\nopenAnyReadOnly = openAnyWithMode GA_ReadOnly\n\nopenAnyReadWrite :: forall s. FilePath -> GDAL s (SomeDataset s ReadWrite)\nopenAnyReadWrite = openAnyWithMode GA_Update\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: (Band s t a) -> GDAL s (Maybe Double)\nbandNodataValue = fmap (fmap realToFrac) . liftIO . c_bandNodataValue\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s a) -> Double -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s a. GDALType a\n => (ROBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = do\n toValue <- getToValue band\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy 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 0\n 0\n return $ St.map toValue $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\ngetToValue band = do\n mNodata <- c_bandNodataValue band\n return $ case mNodata of\n Nothing -> Value\n Just nd -> \\v -> if toNodata v == nd then NoData else Value v\n{-# INLINE getToValue #-}\n\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n len <- bandBlockLen band\n liftIO $ do\n toValue <- getToValue band\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ band (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.map toValue $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\ngetMaskBand :: Band s t a -> GDAL s (Band s t Word8)\ngetMaskBand = liftIO . c_getMaskBand\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , SomeDataset (..)\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , unValue\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , openAnyReadOnly\n , openAnyReadWrite\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , setBandNodataDefault\n , getBand\n , getMaskBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Data.Coerce (coerce)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 nodataAsDouble :: a -> Double\n -- | how to convert from double for use with bandNodataValue\n nodataFromDouble :: Double -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value {-# UNPACK #-} !a | NoData deriving (Eq, Show)\n\nunValue :: Value a -> a\nunValue (Value a) = a\nunValue NoData = error \"called unValue on NoData\"\n{-# INLINE unValue #-}\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: Bool) + sizeOf (undefined :: a)\n alignment _ = 4\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Bool) `plusPtr` 1\n t <- peek (castPtr p::Ptr Bool)\n if t\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Bool) False\n Value a -> do\n poke (castPtr p :: Ptr Bool) True\n let p1 = (castPtr p :: Ptr Bool) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: GDALType a => FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p >>= checkType\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\nopenAnyWithMode :: forall s t. Access -> String -> GDAL s (SomeDataset s t)\nopenAnyWithMode m p = do\n ds <- openWithMode m p\n dt <- getBand ds 1 >>= bandDatatype\n case dt of\n GDT_Byte -> return $ SomeDataset ((coerce ds) :: Dataset s t Word8)\n GDT_UInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word16)\n GDT_UInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word32)\n GDT_Int16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int16)\n GDT_Int32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int32)\n GDT_Float32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Float)\n GDT_Float64 -> return $ SomeDataset ((coerce ds) :: Dataset s t Double)\n GDT_CInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int16))\n GDT_CInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int32))\n GDT_CFloat32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Float))\n GDT_CFloat64 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Double))\n _ -> liftIO (throw InvalidType)\n\ncheckType\n :: forall s t a. GDALType a\n => Dataset s t a -> GDAL s (Dataset s t a)\ncheckType ds = do\n c <- datasetBandCount ds\n if c > 0\n then do\n b <- getBand ds 1\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ds\n else liftIO (throw InvalidType)\n else return ds\n\ndata SomeDataset s (t :: DatasetMode)\n = forall a. GDALType a => SomeDataset (Dataset s t a)\n\nopenAnyReadOnly :: forall s. FilePath -> GDAL s (SomeDataset s ReadOnly)\nopenAnyReadOnly = openAnyWithMode GA_ReadOnly\n\nopenAnyReadWrite :: forall s. FilePath -> GDAL s (SomeDataset s ReadWrite)\nopenAnyReadWrite = openAnyWithMode GA_Update\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: (Band s t a) -> GDAL s (Maybe Double)\nbandNodataValue b = liftIO $ 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 s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s a) -> Double -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nsetBandNodataDefault :: forall s a. GDALType a => (RWBand s a) -> GDAL s ()\nsetBandNodataDefault = flip setBandNodataValue (nodataAsDouble (nodata :: a))\n\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s a. GDALType a\n => (ROBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by =\n readMasked band $ \\(b :: Band s t a') -> do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t a\n -> (forall a'. GDALType a' => Band s t a' -> IO (Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = do\n vs <- reader band\n mask <- c_getMaskBand band\n ms <- reader mask\n return $! St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- fmap (maybe nodata nodataFromDouble) (bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n len <- bandBlockLen band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n nElems <- bandBlockLen b\n bNodata <- fmap (maybe nodata nodataFromDouble) (bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\ngetMaskBand :: Band s t a -> GDAL s (Band s t Word8)\ngetMaskBand = liftIO . c_getMaskBand\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n nodataAsDouble = fromIntegral\n nodataFromDouble = round\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n nodataAsDouble = fromIntegral\n nodataFromDouble = round\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n nodataAsDouble = fromIntegral\n nodataFromDouble = round\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n nodataAsDouble = fromIntegral\n nodataFromDouble = round\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n nodataAsDouble = fromIntegral\n nodataFromDouble = round\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n nodataAsDouble = realToFrac\n nodataFromDouble = realToFrac\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n nodataAsDouble = id\n nodataFromDouble = id\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n nodataAsDouble = fromIntegral . realPart\n nodataFromDouble d = nodataFromDouble d :+ nodataFromDouble d\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n nodataAsDouble = fromIntegral . realPart\n nodataFromDouble d = nodataFromDouble d :+ nodataFromDouble d\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n nodataAsDouble = realToFrac . realPart\n nodataFromDouble d = nodataFromDouble d :+ nodataFromDouble d\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n nodataAsDouble = realPart\n nodataFromDouble d = nodataFromDouble d :+ nodataFromDouble d\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ab4731efadd1238b194fec606a983e92e4619964","subject":"[project @ 2005-05-08 12:59:27 by duncan_coutts] import Systems.Glib.Flags","message":"[project @ 2005-05-08 12:59:27 by duncan_coutts]\nimport Systems.Glib.Flags\n","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Pango\/Description.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\n--\n-- Version $Revision: 1.5 $ from $Date: 2005\/05\/08 12:59:27 $\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-- Functions to manage font description.\n--\n-- * Font descriptions provide a way to query and state requirements of\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Monad (liftM)\nimport Data.Ratio\nimport Data.Bits ((.&.))\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(Flags, fromFlags)\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GObject\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\nimport Graphics.UI.Gtk.General.Enums\nimport Graphics.UI.Gtk.General.Structs\t(pangoScale)\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family_static#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleQblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Rational -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (round (p*fromIntegral pangoScale))\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Rational)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (fromIntegral x % pangoScale)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns 'True' if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns 'False'.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- \"[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]\" where FAMILY_LIST is a comma\n-- separated list of font families optionally terminated by a comma,\n-- STYLE_OPTIONS is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. SIZE is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) - text layout functions: Font Descriptions\n--\n-- Author : Axel Simon\n--\n-- Created: 8 Feburary 2003\n--\n-- Version $Revision: 1.4 $ from $Date: 2005\/02\/12 17:19:24 $\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-- Functions to manage font description.\n--\n-- * Font descriptions provide a way to query and state requirements of\n-- fonts. This data structure has several fields describing different\n-- characteristics of a font. Each of these fields can be set of left\n-- unspecified.\n--\nmodule Graphics.UI.Gtk.Pango.Description (\n FontDescription,\n fontDescriptionNew,\n fontDescriptionCopy,\n fontDescriptionSetFamily,\n fontDescriptionGetFamily,\n fontDescriptionSetStyle,\n fontDescriptionGetStyle,\n fontDescriptionSetVariant,\n fontDescriptionGetVariant,\n fontDescriptionSetWeight,\n fontDescriptionGetWeight,\n fontDescriptionSetStretch,\n fontDescriptionGetStretch,\n fontDescriptionSetSize,\n fontDescriptionGetSize,\n fontDescriptionUnsetFields,\n fontDescriptionMerge,\n fontDescriptionBetterMatch,\n fontDescriptionFromString,\n fontDescriptionToString\n ) where\n\nimport Monad (liftM)\nimport Data.Ratio\nimport Data.Bits ((.&.))\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GObject\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Pango.Types#}\nimport Graphics.UI.Gtk.Pango.Enums\nimport Graphics.UI.Gtk.General.Enums\nimport Graphics.UI.Gtk.General.Structs\t(pangoScale)\n\n{# context lib=\"pango\" prefix=\"pango_font_description\" #}\n\n-- | Create a new font description.\n--\n-- * All field are unset.\n--\nfontDescriptionNew :: IO FontDescription\nfontDescriptionNew = {#call unsafe new#} >>= makeNewFontDescription \n\n-- | Make a deep copy of a font description.\n--\nfontDescriptionCopy :: FontDescription -> IO FontDescription\nfontDescriptionCopy fd = {#call unsafe copy#} fd >>= makeNewFontDescription \n\n-- | Set the font famliy.\n--\n-- * A font family is a name designating the design of the font (e.g. Sans\n-- or Times) without the variant.\n--\n-- * In some contexts a comma separated list of font families can be used.\n--\nfontDescriptionSetFamily :: FontDescription -> String -> IO ()\nfontDescriptionSetFamily fd family = withUTFString family $ \\strPtr ->\n {#call unsafe set_family_static#} fd strPtr\n\n-- | Get the font family.\n--\n-- * 'Nothing' is returned if the font family is not set.\n--\nfontDescriptionGetFamily :: FontDescription -> IO (Maybe String)\nfontDescriptionGetFamily fd = do\n strPtr <- {#call unsafe get_family#} fd\n if strPtr==nullPtr then return Nothing else\n liftM Just $ peekUTFString strPtr\n\n-- Flags denoting which fields in a font description are set.\n{#enum PangoFontMask as FontMask {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags FontMask\n\n-- | Set the style field.\n--\n-- * Most fonts will have either a 'StyleItalic' or 'StyleQblique'\n-- but rarely both.\n--\nfontDescriptionSetStyle :: FontDescription -> FontStyle -> IO ()\nfontDescriptionSetStyle fd p =\n {#call unsafe set_style#} fd (fromIntegral (fromEnum p))\n\n-- | Get the style field.\nfontDescriptionGetStyle :: FontDescription -> IO (Maybe FontStyle)\nfontDescriptionGetStyle fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStyle) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_style#} fd\n else return Nothing\n\n-- | Set the variant field.\n--\nfontDescriptionSetVariant :: FontDescription -> Variant -> IO ()\nfontDescriptionSetVariant fd p =\n {#call unsafe set_variant#} fd (fromIntegral (fromEnum p))\n\n-- | Get the variant field.\nfontDescriptionGetVariant :: FontDescription -> IO (Maybe Variant)\nfontDescriptionGetVariant fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskVariant) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_variant#} fd\n else return Nothing\n\n-- | Set the weight field.\n--\nfontDescriptionSetWeight :: FontDescription -> Weight -> IO ()\nfontDescriptionSetWeight fd p =\n {#call unsafe set_weight#} fd (fromIntegral (fromEnum p))\n\n-- | Get the weight field.\nfontDescriptionGetWeight :: FontDescription -> IO (Maybe Weight)\nfontDescriptionGetWeight fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskWeight) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $\n\t {#call unsafe get_weight#} fd\n else return Nothing\n\n-- | Set the stretch field.\n--\nfontDescriptionSetStretch :: FontDescription -> Stretch -> IO ()\nfontDescriptionSetStretch fd p =\n {#call unsafe set_stretch#} fd (fromIntegral (fromEnum p))\n\n-- | Get the stretch field.\nfontDescriptionGetStretch :: FontDescription -> IO (Maybe Stretch)\nfontDescriptionGetStretch fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskStretch) .&. (fromIntegral fields) \/=0\n then liftM (Just . toEnum . fromIntegral) $ \n\t {#call unsafe get_stretch#} fd\n else return Nothing\n\n-- | Set the size field.\n--\n-- * The given size is in points (pts). One point is 1\\\/72 inch.\n--\nfontDescriptionSetSize :: FontDescription -> Rational -> IO ()\nfontDescriptionSetSize fd p = \n {#call unsafe set_size#} fd (round (p*fromIntegral pangoScale))\n\n-- | Get the size field.\nfontDescriptionGetSize :: FontDescription -> IO (Maybe Rational)\nfontDescriptionGetSize fd = do\n fields <- {#call unsafe get_set_fields#} fd\n if (fromEnum PangoFontMaskSize) .&. (fromIntegral fields) \/=0\n then liftM (\\x -> Just (fromIntegral x % pangoScale)) $ \n\t {#call unsafe get_size#} fd\n else return Nothing\n\n-- | Reset fields in a font description.\n--\nfontDescriptionUnsetFields :: FontDescription -> [FontMask] -> IO ()\nfontDescriptionUnsetFields fd mask =\n {#call unsafe unset_fields#} fd (fromIntegral (fromFlags mask))\n\n-- | Merge two font descriptions.\n--\n-- * Copy fields from the second description to the first. If the boolean\n-- parameter is set, existing fields in the first description will be\n-- replaced.\n--\nfontDescriptionMerge :: FontDescription -> FontDescription -> Bool -> IO ()\nfontDescriptionMerge fd1 fd2 replace =\n {#call unsafe merge#} fd1 fd2 (fromBool replace)\n\n-- | Determine if two descriptions are simliar.\n--\n-- * Returns 'True' if the two descriptions only differ in weight or style.\n--\nfontDescriptionIsMatch :: FontDescription -> FontDescription -> Bool\nfontDescriptionIsMatch fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fdA (FontDescription nullForeignPtr) fdB\n\n-- | Determine which of two descriptions matches a given description better.\n--\n-- * Returns 'True' if the last description is a better match to the first\n-- arguement than the middle one.\n--\n-- * Approximate matching is done on weight and style. If the other\n-- attributes do not match, the function returns 'False'.\n--\nfontDescriptionBetterMatch :: FontDescription -> FontDescription -> \n\t\t\t FontDescription -> Bool\nfontDescriptionBetterMatch fd fdA fdB = unsafePerformIO $ liftM toBool $\n {#call unsafe better_match#} fd fdA fdB\n\n-- | Create a font description from a string.\n--\n-- * The given argument must have the form \n-- \"[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]\" where FAMILY_LIST is a comma\n-- separated list of font families optionally terminated by a comma,\n-- STYLE_OPTIONS is a whitespace separated list of words where each\n-- word describes one of style, variant, weight or stretch. SIZE is\n-- a decimal number giving the size of the font in points. If any of\n-- these fields is absent, the resulting 'FontDescription' will have\n-- the corresponing fields unset.\n--\nfontDescriptionFromString :: String -> IO FontDescription\nfontDescriptionFromString descr = withUTFString descr $ \\strPtr ->\n {#call unsafe from_string#} strPtr >>= makeNewFontDescription\n\n-- | Convert a font description to a string.\n--\n-- * Creates a string representation of a font description. See\n-- 'fontDescriptionFromString' for the format of the string.\n--\nfontDescriptionToString :: FontDescription -> IO String\nfontDescriptionToString fd = do\n strPtr <- {#call unsafe to_string#} fd\n str <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return str\n\n\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"84a968316eeb3f42a355343d55d42ba996aa2ff6","subject":"readMasked changes strategy depending on MaskFlags","message":"readMasked changes strategy depending on MaskFlags\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , SomeDataset (..)\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , unValue\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , openAnyReadOnly\n , openAnyReadWrite\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Data.Coerce (coerce)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\nunValue :: Value a -> a\nunValue (Value a) = a\nunValue NoData = error \"called unValue on NoData\"\n{-# INLINE unValue #-}\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: GDALType a => FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p >>= checkType\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\nopenAnyWithMode :: forall s t. Access -> String -> GDAL s (SomeDataset s t)\nopenAnyWithMode m p = do\n ds <- openWithMode m p\n dt <- getBand ds 1 >>= bandDatatype\n case dt of\n GDT_Byte -> return $ SomeDataset ((coerce ds) :: Dataset s t Word8)\n GDT_UInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word16)\n GDT_UInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word32)\n GDT_Int16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int16)\n GDT_Int32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int32)\n GDT_Float32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Float)\n GDT_Float64 -> return $ SomeDataset ((coerce ds) :: Dataset s t Double)\n GDT_CInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int16))\n GDT_CInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int32))\n GDT_CFloat32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Float))\n GDT_CFloat64 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Double))\n _ -> liftIO (throw InvalidType)\n\ncheckType\n :: forall s t a. GDALType a\n => Dataset s t a -> GDAL s (Dataset s t a)\ncheckType ds = do\n c <- datasetBandCount ds\n if c > 0\n then do\n b <- getBand ds 1\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ds\n else liftIO (throw InvalidType)\n else return ds\n\ndata SomeDataset s (t :: DatasetMode)\n = forall a. GDALType a => SomeDataset (Dataset s t a)\n\nopenAnyReadOnly :: forall s. FilePath -> GDAL s (SomeDataset s ReadOnly)\nopenAnyReadOnly = openAnyWithMode GA_ReadOnly\n\nopenAnyReadWrite :: forall s. FilePath -> GDAL s (SomeDataset s ReadWrite)\nopenAnyReadWrite = openAnyWithMode GA_Update\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: (Band s t a) -> GDAL s (Maybe Double)\nbandNodataValue = fmap (fmap realToFrac) . liftIO . c_bandNodataValue\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s a) -> Double -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s a. GDALType a\n => (ROBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by =\n readMasked band $ \\(b :: Band s t a') -> do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t a\n -> (forall a'. GDALType a' => Band s t a' -> IO (Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader\n | hasFlag MaskPerDataset = useMaskBand\n | hasFlag MaskNoData = useNoData\n | hasFlag MaskAllValid = useAsIs\n | otherwise = useMaskBand\n where\n hasFlag f = fromEnumC f .&. c_getMaskFlags band == fromEnumC f\n useAsIs = fmap (St.map Value) (reader band)\n useNoData = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n fmap (St.map toValue) (reader band)\n useMaskBand = do\n vs <- reader band\n mask <- c_getMaskBand band\n ms <- reader mask\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n\nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n len <- bandBlockLen band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , SomeDataset (..)\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , unValue\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , openAnyReadOnly\n , openAnyReadWrite\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , getMaskBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Data.Coerce (coerce)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value {-# UNPACK #-} !a | NoData deriving (Eq, Show)\n\nunValue :: Value a -> a\nunValue (Value a) = a\nunValue NoData = error \"called unValue on NoData\"\n{-# INLINE unValue #-}\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: GDALType a => FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p >>= checkType\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\nopenAnyWithMode :: forall s t. Access -> String -> GDAL s (SomeDataset s t)\nopenAnyWithMode m p = do\n ds <- openWithMode m p\n dt <- getBand ds 1 >>= bandDatatype\n case dt of\n GDT_Byte -> return $ SomeDataset ((coerce ds) :: Dataset s t Word8)\n GDT_UInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word16)\n GDT_UInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Word32)\n GDT_Int16 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int16)\n GDT_Int32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Int32)\n GDT_Float32 -> return $ SomeDataset ((coerce ds) :: Dataset s t Float)\n GDT_Float64 -> return $ SomeDataset ((coerce ds) :: Dataset s t Double)\n GDT_CInt16 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int16))\n GDT_CInt32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Int32))\n GDT_CFloat32 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Float))\n GDT_CFloat64 -> return $ SomeDataset ((coerce ds) :: Dataset s t (Complex Double))\n _ -> liftIO (throw InvalidType)\n\ncheckType\n :: forall s t a. GDALType a\n => Dataset s t a -> GDAL s (Dataset s t a)\ncheckType ds = do\n c <- datasetBandCount ds\n if c > 0\n then do\n b <- getBand ds 1\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ds\n else liftIO (throw InvalidType)\n else return ds\n\ndata SomeDataset s (t :: DatasetMode)\n = forall a. GDALType a => SomeDataset (Dataset s t a)\n\nopenAnyReadOnly :: forall s. FilePath -> GDAL s (SomeDataset s ReadOnly)\nopenAnyReadOnly = openAnyWithMode GA_ReadOnly\n\nopenAnyReadWrite :: forall s. FilePath -> GDAL s (SomeDataset s ReadWrite)\nopenAnyReadWrite = openAnyWithMode GA_Update\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: (Band s t a) -> GDAL s (Maybe Double)\nbandNodataValue = fmap (fmap realToFrac) . liftIO . c_bandNodataValue\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s a) -> Double -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s a. GDALType a\n => (ROBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = do\n toValue <- getToValue band\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy 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 0\n 0\n return $ St.map toValue $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\ngetToValue band = do\n mNodata <- c_bandNodataValue band\n return $ case mNodata of\n Nothing -> Value\n Just nd -> \\v -> if toNodata v == nd then NoData else Value v\n{-# INLINE getToValue #-}\n\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n len <- bandBlockLen band\n liftIO $ do\n toValue <- getToValue band\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ band (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.map toValue $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\ngetMaskBand :: Band s t a -> GDAL s (Band s t Word8)\ngetMaskBand = liftIO . c_getMaskBand\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = round\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"dd70875003201b1bc8d95602f969ad04abc81903","subject":"Added function to read status out of the future","message":"Added function to read status out of the future\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , getFutureStatus\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\ngetFutureStatus :: Future a -> IO Status\ngetFutureStatus = readMVar . futureStatus\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\n#ifdef MPICH2\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n#else\nwait request =\n alloca $ \\statusPtr -> do\n checkError $ Internal.wait (castPtr request) (castPtr statusPtr)\n peek statusPtr\n#endif\n","old_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\n#ifdef MPICH2\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n#else\nwait request =\n alloca $ \\statusPtr -> do\n checkError $ Internal.wait (castPtr request) (castPtr statusPtr)\n peek statusPtr\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ecc09f3f3efb871cf142d3f21016fdea67dd093a","subject":"docs","message":"docs\n\ndarcs-hash:20080226163121-0faa6-cd93e2af4e22bbb846d8d75df6fce4da22a5e945.gz\n","repos":"the-real-blackh\/hexpat,the-real-blackh\/hexpat,the-real-blackh\/hexpat","old_file":"Text\/XML\/Expat\/Raw.chs","new_file":"Text\/XML\/Expat\/Raw.chs","new_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n\n-- |This module wraps the Expat API directly. If you use this interface,\n-- you must e.g. free your 'Parser' manually.\n\nmodule Text.XML.Expat.Raw (\n -- ** Parser Setup\n Parser, parserCreate, parserFree, parse,\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler\n) where\n\nimport C2HS\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.\nnewtype Parser = Parser {#type Parser#}\nasParser :: Ptr () -> Parser\nasParser ptr = Parser ptr\nunParser :: Parser -> Ptr ()\nunParser (Parser p) = p\n-- |Create a parser. The parameter is the default character encoding, and can\n-- be one of\n--\n-- - \\\"US-ASCII\\\"\n--\n-- - \\\"UTF-8\\\"\n--\n-- - \\\"UTF-16\\\"\n--\n-- - \\\"ISO-8859-1\\\"\n{#fun unsafe XML_ParserCreate as parserCreate {`String'} -> `Parser' asParser#}\n\n-- |Free a Parser.\n{#fun unsafe XML_ParserFree as parserFree {unParser `Parser'} -> `()'#}\n\nunStatus :: CInt -> Bool\nunStatus 0 = False\nunStatus 1 = True\n-- |@parse data False@ feeds mode data into a 'Parser'. The end of the data\n-- is indicated by passing True for the final parameter. @parse@ returns\n-- False on a parse error.\n{#fun XML_Parse as parse\n {unParser `Parser', `String' &, `Bool'} -> `Bool' unStatus#}\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 = String -> [(String,String)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = String -> 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 = String -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler handler = mkCStartElementHandler h where\n h ptr cname cattrs = do\n name <- peekCString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekCString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler (Parser p) handler = do\n handler' <- wrapStartElementHandler handler\n {#call unsafe XML_SetStartElementHandler as ^#} p handler'\n\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler handler = mkCEndElementHandler h where\n h ptr cname = do\n name <- peekCString cname\n handler name\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler (Parser p) handler = do\n handler' <- wrapEndElementHandler handler\n {#call unsafe XML_SetEndElementHandler as ^#} p handler'\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler handler = mkCCharacterDataHandler h where\n h ptr cdata len = do\n data_ <- peekCStringLen (cdata, fromIntegral len)\n handler data_\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler (Parser p) handler = do\n handler' <- wrapCharacterDataHandler handler\n {#call unsafe XML_SetCharacterDataHandler as ^#} p handler'\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n","old_contents":"module Text.XML.Expat.Raw (\n Parser, parserCreate, parserFree, parse,\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler\n) where\nimport C2HS\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\nnewtype Parser = Parser {#type Parser#}\nasParser :: Ptr () -> Parser\nasParser ptr = Parser ptr\nunParser :: Parser -> Ptr ()\nunParser (Parser p) = p\n{#fun unsafe XML_ParserCreate as parserCreate {`String'} -> `Parser' asParser#}\n{#fun unsafe XML_ParserFree as parserFree {unParser `Parser'} -> `()'#}\n\n{#fun XML_Parse as parse\n {unParser `Parser', `String' &, `Bool'} -> `Int'#}\n\ntype StartElementHandler = String -> [(String,String)] -> IO ()\ntype EndElementHandler = String -> IO ()\ntype CharacterDataHandler = String -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler handler = mkCStartElementHandler h where\n h ptr cname cattrs = do\n name <- peekCString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekCString cattrlist\n handler name (pairwise attrlist)\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler (Parser p) handler = do\n handler' <- wrapStartElementHandler handler\n {#call unsafe XML_SetStartElementHandler as ^#} p handler'\n\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler handler = mkCEndElementHandler h where\n h ptr cname = do\n name <- peekCString cname\n handler name\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler (Parser p) handler = do\n handler' <- wrapEndElementHandler handler\n {#call unsafe XML_SetEndElementHandler as ^#} p handler'\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler handler = mkCCharacterDataHandler h where\n h ptr cdata len = do\n data_ <- peekCStringLen (cdata, fromIntegral len)\n handler data_\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler (Parser p) handler = do\n handler' <- wrapCharacterDataHandler handler\n {#call unsafe XML_SetCharacterDataHandler as ^#} p handler'\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ed0a26e6022d641e98f03e2215b2be4bc2f8d81e","subject":"Pick the right function to load a Pixbuf on Windows.","message":"Pick the right function to load a Pixbuf on Windows.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/PixbufAnimation.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/PixbufAnimation.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf Animation\n--\n-- Author : Matthew Arsenault\n--\n-- Created: 14 November 2009\n--\n-- Copyright (C) 2009 Matthew Arsenault\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.Gdk.PixbufAnimation (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'PixbufAnimation'\n-- | +----'PixbufSimpleAnim'\n-- @\n\n-- * Types\n PixbufAnimation,\n PixbufAnimationClass,\n castToPixbufAnimation, gTypePixbufAnimation,\n toPixbufAnimation,\n\n PixbufAnimationIter,\n PixbufAnimationIterClass,\n castToPixbufAnimationIter, gTypePixbufAnimationIter,\n toPixbufAnimationIter,\n\n PixbufSimpleAnim,\n PixbufSimpleAnimClass,\n castToPixbufSimpleAnim, gTypePixbufSimpleAnim,\n toPixbufSimpleAnim,\n\n-- * Constructors\n pixbufAnimationNewFromFile,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimNew,\n#endif\n\n-- * Methods\n pixbufAnimationGetWidth,\n pixbufAnimationGetHeight,\n pixbufAnimationGetIter,\n pixbufAnimationIsStaticImage,\n pixbufAnimationGetStaticImage,\n pixbufAnimationIterAdvance,\n pixbufAnimationIterGetDelayTime,\n pixbufAnimationIterOnCurrentlyLoadingFrame,\n pixbufAnimationIterGetPixbuf,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimAddFrame,\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n pixbufSimpleAnimSetLoop,\n pixbufSimpleAnimGetLoop\n#endif\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\n{# import Graphics.UI.Gtk.Gdk.Pixbuf #}\n\n{# context prefix=\"gdk\" #}\n\n\n--CHECKME: Domain error doc, GFileError ???\n-- | Creates a new animation by loading it from a file. The file\n-- format is detected automatically. If the file's format does not\n-- support multi-frame images, then an animation with a single frame\n-- will be created. Possible errors are in the 'PixbufError' and\n-- 'GFileError' domains.\n--\n-- Any of several error conditions may occur: the file could not be\n-- opened, there was no loader for the file's format, there was not\n-- enough memory to allocate the image buffer, or the image file\n-- contained invalid data.\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' or 'GFileError'\n--\npixbufAnimationNewFromFile :: FilePath -- ^ Name of file to load, in the GLib file name encoding\n -> IO PixbufAnimation -- ^ A newly-created animation\npixbufAnimationNewFromFile fname =\n constructNewGObject mkPixbufAnimation $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,5)\n {#call unsafe pixbuf_animation_new_from_file_utf8#} strPtr errPtrPtr\n#else\n {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr\n#endif\n\n-- | Queries the width of the bounding box of a pixbuf animation.\npixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Width of the bounding box of the animation.\npixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self\n\n-- | Queries the height of the bounding box of a pixbuf animation.\npixbufAnimationGetHeight :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Height of the bounding box of the animation.\npixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self\n\n\n-- | Get an iterator for displaying an animation. The iterator\n-- provides the frames that should be displayed at a given time. The\n-- start time would normally come from 'gGetCurrentTime', and marks\n-- the beginning of animation playback. After creating an iterator,\n-- you should immediately display the pixbuf returned by\n-- 'pixbufAnimationIterGetPixbuf'. Then, you should install a\n-- timeout (with 'timeoutAdd') or by some other mechanism ensure\n-- that you'll update the image after\n-- 'pixbufAnimationIterGetDelayTime' milliseconds. Each time the\n-- image is updated, you should reinstall the timeout with the new,\n-- possibly-changed delay time.\n--\n-- As a shortcut, if start_time is @Nothing@, the result of\n-- 'gGetCurrentTime' will be used automatically.\n--\n-- To update the image (i.e. possibly change the result of\n-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),\n-- call 'pixbufAnimationIterAdvance'.\n--\n-- If you're using 'PixbufLoader', in addition to updating the image\n-- after the delay time, you should also update it whenever you\n-- receive the area_updated signal and\n-- 'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In\n-- this case, the frame currently being fed into the loader has\n-- received new data, so needs to be refreshed. The delay time for a\n-- frame may also be modified after an area_updated signal, for\n-- example if the delay time for a frame is encoded in the data after\n-- the frame itself. So your timeout should be reinstalled after any\n-- area_updated signal.\n--\n-- A delay time of -1 is possible, indicating \"infinite.\"\n--\npixbufAnimationGetIter :: PixbufAnimation -- ^ a 'PixbufAnimation'\n -> Maybe GTimeVal -- ^ time when the animation starts playing\n -> IO PixbufAnimationIter -- ^ an iterator to move over the animation\npixbufAnimationGetIter self tv = maybeWith with tv $ \\stPtr ->\n constructNewGObject mkPixbufAnimationIter $\n {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)\n\n\n\n-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns\n-- out to be a plain, unanimated image, then this function will\n-- return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve\n-- the image.\n--\npixbufAnimationIsStaticImage :: PixbufAnimation\n -> IO Bool -- ^ TRUE if the \"animation\" was really just an image\npixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self\n\n\n-- | If an animation is really just a plain image (has only one\n-- frame), this function returns that image. If the animation is an\n-- animation, this function returns a reasonable thing to display as\n-- a static unanimated image, which might be the first frame, or\n-- something more sophisticated. If an animation hasn't loaded any\n-- frames yet, this function will return @Nothing@.\n--\npixbufAnimationGetStaticImage :: PixbufAnimation\n -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation\npixbufAnimationGetStaticImage self =\n maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self\n\n\n\n-- | Possibly advances an animation to a new frame. Chooses the frame\n-- based on the start time passed to 'pixbufAnimationGetIter'.\n--\n-- current_time would normally come from 'gGetCurrentTime', and must\n-- be greater than or equal to the time passed to\n-- 'pixbufAnimationGetIter', and must increase or remain unchanged\n-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you\n-- can't go backward in time; animations only play forward.\n--\n-- As a shortcut, pass @Nothing@ for the current time and\n-- 'gGetCurrentTime' will be invoked on your behalf. So you only need\n-- to explicitly pass current_time if you're doing something odd like\n-- playing the animation at double speed.\n--\n-- If this function returns @False@, there's no need to update the\n-- animation display, assuming the display had been rendered prior to\n-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and\n-- update the display with the new pixbuf.\n--\npixbufAnimationIterAdvance :: PixbufAnimationIter -- ^ A 'PixbufAnimationIter'\n -> Maybe GTimeVal -- ^ current time\n -> IO Bool -- ^ @True@ if the image may need updating\npixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \\tvPtr ->\n {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)\n\n\n-- | Gets the number of milliseconds the current pixbuf should be\n-- displayed, or -1 if the current pixbuf should be displayed\n-- forever. 'timeoutAdd' conveniently takes a timeout in\n-- milliseconds, so you can use a timeout to schedule the next\n-- update.\n--\npixbufAnimationIterGetDelayTime :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Int -- ^ delay time in milliseconds (thousandths of a second)\npixbufAnimationIterGetDelayTime self = liftM fromIntegral $\n {#call unsafe pixbuf_animation_iter_get_delay_time#} self\n\n\n-- | Used to determine how to respond to the area_updated signal on\n-- 'PixbufLoader' when loading an animation. area_updated is emitted\n-- for an area of the frame currently streaming in to the loader. So\n-- if you're on the currently loading frame, you need to redraw the\n-- screen for the updated area.\n--\npixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter\n -> IO Bool -- ^ @True@ if the frame we're on is partially loaded, or the last frame\npixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $\n {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter\n\n--CHECKME: referencing, usage of constructNewGObject\n-- | Gets the current pixbuf which should be displayed; the pixbuf will\n-- be the same size as the animation itself\n-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This\n-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'\n-- milliseconds. The caller of this function does not own a reference\n-- to the returned pixbuf; the returned pixbuf will become invalid\n-- when the iterator advances to the next frame, which may happen\n-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to\n-- keep it (don't just add a reference), as it may get recycled as you\n-- advance the iterator.\n--\npixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Pixbuf -- ^ the pixbuf to be displayed\npixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $\n {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter\n\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Creates a new, empty animation.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimNew :: Int -- ^ the width of the animation\n -> Int -- ^ the height of the animation\n -> Float -- ^ the speed of the animation, in frames per second\n -> IO PixbufSimpleAnim -- ^ a newly allocated 'PixbufSimpleAnim'\npixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $\n {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)\n\n\n-- | Adds a new frame to animation. The pixbuf must have the\n-- dimensions specified when the animation was constructed.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimAddFrame :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Pixbuf -- ^ the pixbuf to add\n -> IO ()\npixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb\n\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n\n-- | Sets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimSetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Bool -- ^ whether to loop the animation\n -> IO ()\npixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)\n\n\n-- | Gets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimGetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> IO Bool -- ^ @True@ if the animation loops forever, @False@ otherwise\npixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf Animation\n--\n-- Author : Matthew Arsenault\n--\n-- Created: 14 November 2009\n--\n-- Copyright (C) 2009 Matthew Arsenault\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.Gdk.PixbufAnimation (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'PixbufAnimation'\n-- | +----'PixbufSimpleAnim'\n-- @\n\n-- * Types\n PixbufAnimation,\n PixbufAnimationClass,\n castToPixbufAnimation, gTypePixbufAnimation,\n toPixbufAnimation,\n\n PixbufAnimationIter,\n PixbufAnimationIterClass,\n castToPixbufAnimationIter, gTypePixbufAnimationIter,\n toPixbufAnimationIter,\n\n PixbufSimpleAnim,\n PixbufSimpleAnimClass,\n castToPixbufSimpleAnim, gTypePixbufSimpleAnim,\n toPixbufSimpleAnim,\n\n-- * Constructors\n pixbufAnimationNewFromFile,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimNew,\n#endif\n\n-- * Methods\n pixbufAnimationGetWidth,\n pixbufAnimationGetHeight,\n pixbufAnimationGetIter,\n pixbufAnimationIsStaticImage,\n pixbufAnimationGetStaticImage,\n pixbufAnimationIterAdvance,\n pixbufAnimationIterGetDelayTime,\n pixbufAnimationIterOnCurrentlyLoadingFrame,\n pixbufAnimationIterGetPixbuf,\n#if GTK_CHECK_VERSION(2,8,0)\n pixbufSimpleAnimAddFrame,\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n pixbufSimpleAnimSetLoop,\n pixbufSimpleAnimGetLoop\n#endif\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\n{# import Graphics.UI.Gtk.Gdk.Pixbuf #}\n\n{# context prefix=\"gdk\" #}\n\n\n--CHECKME: Domain error doc, GFileError ???\n-- | Creates a new animation by loading it from a file. The file\n-- format is detected automatically. If the file's format does not\n-- support multi-frame images, then an animation with a single frame\n-- will be created. Possible errors are in the 'PixbufError' and\n-- 'GFileError' domains.\n--\n-- Any of several error conditions may occur: the file could not be\n-- opened, there was no loader for the file's format, there was not\n-- enough memory to allocate the image buffer, or the image file\n-- contained invalid data.\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' or 'GFileError'\n--\npixbufAnimationNewFromFile :: FilePath -- ^ Name of file to load, in the GLib file name encoding\n -> IO PixbufAnimation -- ^ A newly-created animation\npixbufAnimationNewFromFile fname =\n constructNewGObject mkPixbufAnimation $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr\n\n\n-- | Queries the width of the bounding box of a pixbuf animation.\npixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Width of the bounding box of the animation.\npixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self\n\n-- | Queries the height of the bounding box of a pixbuf animation.\npixbufAnimationGetHeight :: PixbufAnimation -- ^ An animation.\n -> IO Int -- ^ Height of the bounding box of the animation.\npixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self\n\n\n-- | Get an iterator for displaying an animation. The iterator\n-- provides the frames that should be displayed at a given time. The\n-- start time would normally come from 'gGetCurrentTime', and marks\n-- the beginning of animation playback. After creating an iterator,\n-- you should immediately display the pixbuf returned by\n-- 'pixbufAnimationIterGetPixbuf'. Then, you should install a\n-- timeout (with 'timeoutAdd') or by some other mechanism ensure\n-- that you'll update the image after\n-- 'pixbufAnimationIterGetDelayTime' milliseconds. Each time the\n-- image is updated, you should reinstall the timeout with the new,\n-- possibly-changed delay time.\n--\n-- As a shortcut, if start_time is @Nothing@, the result of\n-- 'gGetCurrentTime' will be used automatically.\n--\n-- To update the image (i.e. possibly change the result of\n-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),\n-- call 'pixbufAnimationIterAdvance'.\n--\n-- If you're using 'PixbufLoader', in addition to updating the image\n-- after the delay time, you should also update it whenever you\n-- receive the area_updated signal and\n-- 'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In\n-- this case, the frame currently being fed into the loader has\n-- received new data, so needs to be refreshed. The delay time for a\n-- frame may also be modified after an area_updated signal, for\n-- example if the delay time for a frame is encoded in the data after\n-- the frame itself. So your timeout should be reinstalled after any\n-- area_updated signal.\n--\n-- A delay time of -1 is possible, indicating \"infinite.\"\n--\npixbufAnimationGetIter :: PixbufAnimation -- ^ a 'PixbufAnimation'\n -> Maybe GTimeVal -- ^ time when the animation starts playing\n -> IO PixbufAnimationIter -- ^ an iterator to move over the animation\npixbufAnimationGetIter self tv = maybeWith with tv $ \\stPtr ->\n constructNewGObject mkPixbufAnimationIter $\n {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)\n\n\n\n-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns\n-- out to be a plain, unanimated image, then this function will\n-- return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve\n-- the image.\n--\npixbufAnimationIsStaticImage :: PixbufAnimation\n -> IO Bool -- ^ TRUE if the \"animation\" was really just an image\npixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self\n\n\n-- | If an animation is really just a plain image (has only one\n-- frame), this function returns that image. If the animation is an\n-- animation, this function returns a reasonable thing to display as\n-- a static unanimated image, which might be the first frame, or\n-- something more sophisticated. If an animation hasn't loaded any\n-- frames yet, this function will return @Nothing@.\n--\npixbufAnimationGetStaticImage :: PixbufAnimation\n -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation\npixbufAnimationGetStaticImage self =\n maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self\n\n\n\n-- | Possibly advances an animation to a new frame. Chooses the frame\n-- based on the start time passed to 'pixbufAnimationGetIter'.\n--\n-- current_time would normally come from 'gGetCurrentTime', and must\n-- be greater than or equal to the time passed to\n-- 'pixbufAnimationGetIter', and must increase or remain unchanged\n-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you\n-- can't go backward in time; animations only play forward.\n--\n-- As a shortcut, pass @Nothing@ for the current time and\n-- 'gGetCurrentTime' will be invoked on your behalf. So you only need\n-- to explicitly pass current_time if you're doing something odd like\n-- playing the animation at double speed.\n--\n-- If this function returns @False@, there's no need to update the\n-- animation display, assuming the display had been rendered prior to\n-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and\n-- update the display with the new pixbuf.\n--\npixbufAnimationIterAdvance :: PixbufAnimationIter -- ^ A 'PixbufAnimationIter'\n -> Maybe GTimeVal -- ^ current time\n -> IO Bool -- ^ @True@ if the image may need updating\npixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \\tvPtr ->\n {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)\n\n\n-- | Gets the number of milliseconds the current pixbuf should be\n-- displayed, or -1 if the current pixbuf should be displayed\n-- forever. 'timeoutAdd' conveniently takes a timeout in\n-- milliseconds, so you can use a timeout to schedule the next\n-- update.\n--\npixbufAnimationIterGetDelayTime :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Int -- ^ delay time in milliseconds (thousandths of a second)\npixbufAnimationIterGetDelayTime self = liftM fromIntegral $\n {#call unsafe pixbuf_animation_iter_get_delay_time#} self\n\n\n-- | Used to determine how to respond to the area_updated signal on\n-- 'PixbufLoader' when loading an animation. area_updated is emitted\n-- for an area of the frame currently streaming in to the loader. So\n-- if you're on the currently loading frame, you need to redraw the\n-- screen for the updated area.\n--\npixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter\n -> IO Bool -- ^ @True@ if the frame we're on is partially loaded, or the last frame\npixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $\n {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter\n\n--CHECKME: referencing, usage of constructNewGObject\n-- | Gets the current pixbuf which should be displayed; the pixbuf will\n-- be the same size as the animation itself\n-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This\n-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'\n-- milliseconds. The caller of this function does not own a reference\n-- to the returned pixbuf; the returned pixbuf will become invalid\n-- when the iterator advances to the next frame, which may happen\n-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to\n-- keep it (don't just add a reference), as it may get recycled as you\n-- advance the iterator.\n--\npixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator\n -> IO Pixbuf -- ^ the pixbuf to be displayed\npixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $\n {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter\n\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Creates a new, empty animation.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimNew :: Int -- ^ the width of the animation\n -> Int -- ^ the height of the animation\n -> Float -- ^ the speed of the animation, in frames per second\n -> IO PixbufSimpleAnim -- ^ a newly allocated 'PixbufSimpleAnim'\npixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $\n {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)\n\n\n-- | Adds a new frame to animation. The pixbuf must have the\n-- dimensions specified when the animation was constructed.\n--\n-- * Available since Gtk+ version 2.8\n--\npixbufSimpleAnimAddFrame :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Pixbuf -- ^ the pixbuf to add\n -> IO ()\npixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb\n\n#endif\n\n#if GTK_CHECK_VERSION(2,18,0)\n\n-- | Sets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimSetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> Bool -- ^ whether to loop the animation\n -> IO ()\npixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)\n\n\n-- | Gets whether animation should loop indefinitely when it reaches\n-- the end.\n--\n-- * Available since Gtk+ version 2.18\n--\npixbufSimpleAnimGetLoop :: PixbufSimpleAnim -- ^ a 'PixbufSimpleAnim'\n -> IO Bool -- ^ @True@ if the animation loops forever, @False@ otherwise\npixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"225df6385ce0e42e3d737ff02972e54ff124bdd5","subject":"Add desciption docs in SourceBuffer.chs","message":"Add desciption docs in SourceBuffer.chs\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Description\n-- | The 'SourceBuffer' object is the model for 'SourceView' widgets. It extends the 'TextBuffer'\n-- object by adding features useful to display and edit source code as syntax highlighting and bracket\n-- matching. It also implements support for undo\/redo operations.\n-- \n-- To create a 'SourceBuffer' use 'sourceBufferNew' or\n-- 'sourceBufferNewWithLanguage'. The second form is just a convenience function which allows\n-- you to initially set a 'SourceLanguage'.\n-- \n-- By default highlighting is enabled, but you can disable it with\n-- 'sourceBufferSetHighlightSyntax'.\n\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} \n (toSourceBuffer sb) \n (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} \n (toSourceBuffer sb)\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBufferClass buffer => buffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n (toSourceBuffer sb) \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} (toSourceBuffer sb)\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} (toSourceBuffer sb) (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} (toSourceBuffer sb)\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBufferClass buffer => buffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n (toSourceBuffer sb) \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} (toSourceBuffer sb)\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} (toSourceBuffer sb) (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} (toSourceBuffer sb)\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} (toSourceBuffer sb)\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} (toSourceBuffer sb)\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} (toSourceBuffer sb)\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} (toSourceBuffer sb)\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} (toSourceBuffer sb)\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} (toSourceBuffer sb)\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBufferClass buffer => buffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} (toSourceBuffer sb) strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n (toSourceBuffer buffer) \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n (toSourceBuffer buffer)\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBufferClass buffer => buffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} (toSourceBuffer sb) start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: SourceBufferClass buffer => Attr buffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: SourceBufferClass buffer => Attr buffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: SourceBufferClass buffer => Attr buffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: SourceBufferClass buffer => Signal buffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: SourceBufferClass buffer => Signal buffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} \n (toSourceBuffer sb) \n (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} \n (toSourceBuffer sb)\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBufferClass buffer => buffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n (toSourceBuffer sb) \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} (toSourceBuffer sb)\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} (toSourceBuffer sb) (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} (toSourceBuffer sb)\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBufferClass buffer => buffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n (toSourceBuffer sb) \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} (toSourceBuffer sb)\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} (toSourceBuffer sb) (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} (toSourceBuffer sb)\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} (toSourceBuffer sb)\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} (toSourceBuffer sb)\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} (toSourceBuffer sb)\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} (toSourceBuffer sb)\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} (toSourceBuffer sb)\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} (toSourceBuffer sb)\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBufferClass buffer => buffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} (toSourceBuffer sb) strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n (toSourceBuffer buffer) \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n (toSourceBuffer buffer)\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBufferClass buffer => buffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} (toSourceBuffer sb) start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: SourceBufferClass buffer => Attr buffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: SourceBufferClass buffer => Attr buffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: SourceBufferClass buffer => Attr buffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: SourceBufferClass buffer => Signal buffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: SourceBufferClass buffer => Signal buffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"38cb51193bce87f1f2246eff32382fcb2c1c373c","subject":"implemented ifoldl' and ifoldlM'","message":"implemented ifoldl' and ifoldlM'\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 TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , throwIfError\n , unDataset\n , unBand\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, liftM2, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = GDALException !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset { unDataset :: Ptr (Dataset s t a) }\n\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a)\n = Band { unBand :: Ptr (Band s t a) }\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $ do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Dataset s t a\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Dataset s t a -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = (fromIntegral (getDatasetXSize_ ds), fromIntegral (getDatasetYSize_ ds)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Dataset s t a -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Dataset s t a -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Dataset s t a -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ setProjection' d\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Dataset s t a -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform d 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 :: Dataset s t a -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds (Geotransform g0 g1 g2 g3 g4 g5) = liftIO $ do\n allocaArray 6 $ \\a -> do\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 ds a\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Dataset s t a -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Dataset s t a -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band ds = liftIO $ do\n rBand@(Band p) <- getRasterBand ds (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Dataset s t a -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ band xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ band)\n , fromIntegral (getBandYSize_ band))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError \"could not set nodata\" $ setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Band s t b' -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Band s t b' -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = do\n flags <- c_getMaskFlags band\n reader band >>= fmap V_Value . mask flags\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 vs = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand vs = do\n ms <- c_getMaskBand band >>= 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by (V_Value uvec) = liftIO $ do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc b = liftIO $ do\n mNodata <- c_bandNodataValue b\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 acc = f acc x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount b\n (sx,sy) = bandBlockSize b\n (bx,by) = bandSize b\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y (V_Value uvec) = do\n checkType b\n liftIO $ do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n nElems = bandBlockLen b\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n--\n-- Value\n--\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype instance U.Vector (Value a) = V_Value (St.Vector (Value a))\nnewtype instance U.MVector s (Value a) = MV_Value (St.MVector s (Value a))\ninstance Storable a => U.Unbox (Value a)\n\ninstance Storable a => M.MVector U.MVector (Value a) where\n basicLength (MV_Value v ) = M.basicLength v\n basicUnsafeSlice m n (MV_Value v) = MV_Value (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_Value v) (MV_Value u) = M.basicOverlaps v u\n basicUnsafeNew = liftM MV_Value . M.basicUnsafeNew\n basicUnsafeRead (MV_Value v) i = M.basicUnsafeRead v i\n basicUnsafeWrite (MV_Value v) i x = M.basicUnsafeWrite v i x\n basicInitialize (MV_Value v) = M.basicInitialize v\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n {-# INLINE basicInitialize #-}\n\ninstance Storable a => G.Vector U.Vector (Value a) where\n basicUnsafeFreeze (MV_Value v) = liftM V_Value (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Value v) = liftM MV_Value (G.basicUnsafeThaw v)\n basicLength ( V_Value v) = G.basicLength v\n basicUnsafeSlice m n (V_Value v) = V_Value (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_Value v) i = G.basicUnsafeIndexM v i\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n , foldl'\n , foldlM'\n\n -- Internal Util\n , throwIfError\n , unDataset\n , unBand\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, liftM2, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = GDALException !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset { unDataset :: Ptr (Dataset s t a) }\n\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a)\n = Band { unBand :: Ptr (Band s t a) }\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $ do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Dataset s t a\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Dataset s t a -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = (fromIntegral (getDatasetXSize_ ds), fromIntegral (getDatasetYSize_ ds)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Dataset s t a -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Dataset s t a -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Dataset s t a -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ setProjection' d\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Dataset s t a -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform d 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 :: Dataset s t a -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds (Geotransform g0 g1 g2 g3 g4 g5) = liftIO $ do\n allocaArray 6 $ \\a -> do\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 ds a\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Dataset s t a -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Dataset s t a -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band ds = liftIO $ do\n rBand@(Band p) <- getRasterBand ds (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Dataset s t a -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ band xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ band)\n , fromIntegral (getBandYSize_ band))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError \"could not set nodata\" $ setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Band s t b' -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Band s t b' -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = do\n flags <- c_getMaskFlags band\n reader band >>= fmap V_Value . mask flags\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 vs = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand vs = do\n ms <- c_getMaskBand band >>= 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by (V_Value uvec) = liftIO $ do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> GDAL s b\nfoldl' f = foldlM' (\\acc -> return . f acc)\n{-# INLINE foldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f initialAcc b = liftIO $ do\n mNodata <- c_bandNodataValue b\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n applyTo i j acc = f acc . toValue =<< peekElemOff ptr (j*sx+i)\n goB !iB !jB !acc\n | iB < nx = do\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount b\n (sx,sy) = bandBlockSize b\n (bx,by) = bandSize b\n{-# INLINE foldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y (V_Value uvec) = do\n checkType b\n liftIO $ do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n nElems = bandBlockLen b\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n--\n-- Value\n--\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype instance U.Vector (Value a) = V_Value (St.Vector (Value a))\nnewtype instance U.MVector s (Value a) = MV_Value (St.MVector s (Value a))\ninstance Storable a => U.Unbox (Value a)\n\ninstance Storable a => M.MVector U.MVector (Value a) where\n basicLength (MV_Value v ) = M.basicLength v\n basicUnsafeSlice m n (MV_Value v) = MV_Value (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_Value v) (MV_Value u) = M.basicOverlaps v u\n basicUnsafeNew = liftM MV_Value . M.basicUnsafeNew\n basicUnsafeRead (MV_Value v) i = M.basicUnsafeRead v i\n basicUnsafeWrite (MV_Value v) i x = M.basicUnsafeWrite v i x\n basicInitialize (MV_Value v) = M.basicInitialize v\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n {-# INLINE basicInitialize #-}\n\ninstance Storable a => G.Vector U.Vector (Value a) where\n basicUnsafeFreeze (MV_Value v) = liftM V_Value (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Value v) = liftM MV_Value (G.basicUnsafeThaw v)\n basicLength ( V_Value v) = G.basicLength v\n basicUnsafeSlice m n (V_Value v) = V_Value (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_Value v) i = G.basicUnsafeIndexM v i\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7162ae161c33b7c8170835544fe229195bdfde59","subject":"Formatting and renaming","message":"Formatting and renaming\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\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","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\ncreateBlobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\ncreateBlobFromFile (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\ncreateBlobFromBuffer :: ObjID -> Repository -> CPtr -> Int -> IO (Maybe GitError)\ncreateBlobFromBuffer (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 -> 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":"b0af58b8c11b9e1269f24a59cde480ae8beb7e1d","subject":"Export ConvKernel","message":"Export ConvKernel\n","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, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n , ConvKernel\n )\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 System.IO.Unsafe\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\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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, UnicodeSyntax, ViewPatterns#-}\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,KernelShape(EllipseShape,CrossShape,RectShape) \n )\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 System.IO.Unsafe\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\n-- | Perform a black tophat filtering of size\nblackTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (closeOp se) i\n in x `IM.sub` i\n\n-- | Perform a white tophat filtering of size\nwhiteTopHat size i =\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) RectShape\n x = unsafeOperate (openOp se) i\n in i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) RectShape\nbigSE = structuringElement (9,9) (4,4) RectShape\n\n---------- Low level wrapper\n#c\nenum KernelShape {\n RectShape = CV_SHAPE_RECT\n ,CrossShape = CV_SHAPE_CROSS\n ,EllipseShape = CV_SHAPE_ELLIPSE\n ,CustomShape = CV_SHAPE_CUSTOM\n };\n#endc\n{#enum KernelShape {} #}\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 . fromEnum $ 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 $ \\(unS -> img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(unS -> 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 = dilate 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0fab8e380ea974520bef55f1984effe0fdefb135","subject":"oops, JITFallback was never exported...","message":"oops, JITFallback was never exported...\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 BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : [2009..2014] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..), JITFallback(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 ( throwIO )\nimport Data.Maybe ( mapMaybe )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal as B\n\n#if CUDA_VERSION < 5050\nimport Debug.Trace ( trace )\n#endif\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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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 , CU_PREFER_PTX as PTX }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : [2009..2014] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 ( throwIO )\nimport Data.Maybe ( mapMaybe )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal as B\n\n#if CUDA_VERSION < 5050\nimport Debug.Trace ( trace )\n#endif\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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2718cf997bdab5a61ed8d49af52f3de84cb92128","subject":"Fix broken indentation in clCreateProgramWithBinary","message":"Fix broken indentation in clCreateProgramWithBinary\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Program.chs","new_file":"src\/System\/GPU\/OpenCL\/Program.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 System.GPU.OpenCL.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clCreateProgramWithBinary, clRetainProgram, \n clReleaseProgram, clUnloadCompiler, clBuildProgram, \n clGetProgramReferenceCount, clGetProgramContext, clGetProgramNumDevices, \n clGetProgramDevices, clGetProgramSource, clGetProgramBinarySizes, \n clGetProgramBinaries, clGetProgramBuildStatus, clGetProgramBuildOptions, \n clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clSetKernelArg, clGetKernelFunctionName, clGetKernelNumArgs, \n clGetKernelReferenceCount, clGetKernelContext, clGetKernelProgram, \n clGetKernelWorkGroupSize, clGetKernelCompileWorkGroupSize, \n clGetKernelLocalMemSize\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM, forM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLulong, CLProgram, CLContext, CLKernel, CLDeviceID, CLError,\n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, \n whenSuccess, wrapPError, wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import CALLCONV \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import CALLCONV \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import CALLCONV \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import CALLCONV \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import CALLCONV \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import CALLCONV \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it throws one of the\nfollowing 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO CLProgram\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n{-| Creates a program object for a context, and loads specified binary data into\nthe program object.\n\nThe program binaries specified by binaries contain the bits that describe the\nprogram executable that will be run on the device(s) associated with\ncontext. The program binary can consist of either or both of device-specific\nexecutable(s), and\/or implementation-specific intermediate representation (IR)\nwhich will be converted to the device-specific executable.\n\nOpenCL allows applications to create a program object using the program\nsource or binary and build appropriate program executables. This allows\napplications to determine whether they want to use the pre-built offline binary\nor load and compile the program source and use the executable compiled\/linked\nonline as the program executable. This can be very useful as it allows\napplications to load and build program executables online on its first instance\nfor appropriate OpenCL devices in the system. These executables can now be\nqueried and cached by the application. Future instances of the application\nlaunching will no longer need to compile and build the program executables. The\ncached executables can be read and loaded by the application, which can help\nsignificantly reduce the application initialization time.\n\nReturns a valid non-zero program object and a list of 'CLError' values whether\nthe program binary for each device specified in device_list was loaded\nsuccessfully or not. It is list of the same length the list of devices with\n'CL_SUCCESS' if binary was successfully loaded for device specified by same\nposition; otherwise returns 'CL_INVALID_VALUE' if length of binary is zero or\n'CL_INVALID_BINARY' if program binary is not a valid binary\nfor the specified device.\n\nThe function can throw on of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context. \n\n * 'CL_INVALID_VALUE' if the device list is empty; or if lengths or binaries are\nempty.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in the device list are not in\nthe list of devices associated with context.\n\n * 'CL_INVALID_BINARY' if an invalid program binary was encountered for any\ndevice.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-} \nclCreateProgramWithBinary :: CLContext -> [CLDeviceID] -> [[Word8]] \n -> IO (CLProgram, [CLError])\nclCreateProgramWithBinary ctx devs bins = wrapPError $ \\perr ->\n withArray devs $ \\pdevs ->\n withArray lbins $ \\plbins -> do\n buffs <- forM bins $ \\bs -> do\n buff <- mallocArray (length bs) :: IO (Ptr Word8)\n pokeArray buff bs\n return buff\n\n ret <- withArray buffs $ \\(pbuffs :: Ptr (Ptr Word8)) -> do\n allocaArray ndevs $ \\(perrs :: Ptr CLint) -> do\n prog <- raw_clCreateProgramWithBinary ctx (fromIntegral ndevs) pdevs plbins pbuffs perrs perr\n errs <- peekArray ndevs perrs\n return (prog, map getEnumCL errs)\n\n mapM_ free buffs\n return ret\n \n where\n lbins = map (fromIntegral . length) bins :: [CSize]\n ndevs = length devs\n\n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram can throw the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO ()\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n whenSuccess (raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr)\n $ return ()\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO CSize\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid 0 nullPtr value_size)\n $ peek value_size\n \n-- | Return the program 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 clGetProgramInfo with\n-- 'CL_PROGRAM_REFERENCE_COUNT'.\nclGetProgramReferenceCount :: CLProgram -> IO CLuint\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_CONTEXT'.\nclGetProgramContext :: CLProgram -> IO CLContext\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_NUM_DEVICES'.\nclGetProgramNumDevices :: CLProgram -> IO CLuint\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_DEVICES'.\nclGetProgramDevices :: CLProgram -> IO [CLDeviceID]\nclGetProgramDevices prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_SOURCE'.\nclGetProgramSource :: CLProgram -> IO String\nclGetProgramSource prg = do\n n <- getProgramInfoSize prg infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARY_SIZES'.\nclGetProgramBinarySizes :: CLProgram -> IO [CSize]\nclGetProgramBinarySizes prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n\nThis function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARIES'.\n-}\nclGetProgramBinaries :: CLProgram -> IO [[Word8]]\nclGetProgramBinaries prg = do\n sizes <- clGetProgramBinarySizes prg\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr)\n $ zipWithM peekArray (map fromIntegral sizes) buffers\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO CSize\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid 0 nullPtr val)\n $ peek val\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_STATUS'.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO CLBuildStatus\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_OPTIONS'.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildOptions prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_LOG'.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildLog prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it throws one of the following 'CLError'\nexceptions:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO CLKernel\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, throws 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, throws 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and throws\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO [CLKernel]\nclCreateKernelsInProgram prg = do\n n <- alloca $ \\pn -> do\n whenSuccess (raw_clCreateKernelsInProgram prg 0 nullPtr pn)\n $ peek pn \n allocaArray (fromIntegral n) $ \\pks -> do\n whenSuccess (raw_clCreateKernelsInProgram prg n pks nullPtr)\n $ peekArray (fromIntegral n) pks\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n{-| Used to set the argument value for a specific argument of a kernel.\n\nA kernel object does not update the reference count for objects such as memory,\nsampler objects specified as argument values by 'clSetKernelArg', Users may not\nrely on a kernel object to retain objects specified as argument values to the\nkernel.\n\nImplementations shall not allow 'CLKernel' objects to hold reference counts to\n'CLKernel' arguments, because no mechanism is provided for the user to tell the\nkernel to release that ownership right. If the kernel holds ownership rights on\nkernel args, that would make it impossible for the user to tell with certainty\nwhen he may safely release user allocated resources associated with OpenCL\nobjects such as the CLMem backing store used with 'CL_MEM_USE_HOST_PTR'.\n\n'clSetKernelArg' throws one of the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n \n * 'CL_INVALID_ARG_INDEX' if arg_index is not a valid argument index.\n\n * 'CL_INVALID_ARG_VALUE' if arg_value specified is NULL for an argument that is\nnot declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_MEM_OBJECT' for an argument declared to be a memory object when\nthe specified arg_value is not a valid memory object.\n\n * 'CL_INVALID_SAMPLER' for an argument declared to be of type sampler_t when\nthe specified arg_value is not a valid sampler object.\n\n * 'CL_INVALID_ARG_SIZE' if arg_size does not match the size of the data type\nfor an argument that is not a memory object or if the argument is a memory\nobject and arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is\ndeclared with the __local qualifier or if the argument is a sampler and arg_size\n!= sizeof(cl_sampler). \n-}\nclSetKernelArg :: Storable a => CLKernel -> CLuint -> a -> IO ()\nclSetKernelArg krn idx val = with val $ \\pval -> do\n whenSuccess (raw_clSetKernelArg krn idx (fromIntegral . sizeOf $ val) (castPtr pval))\n $ return ()\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO CSize\ngetKernelInfoSize krn infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid 0 nullPtr val)\n $ peek val\n \n-- | Return the kernel function name.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_FUNCTION_NAME'.\nclGetKernelFunctionName :: CLKernel -> IO String\nclGetKernelFunctionName krn = do\n n <- getKernelInfoSize krn infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_NUM_ARGS'.\nclGetKernelNumArgs :: CLKernel -> IO CLuint\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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 clGetKernelInfo with\n-- 'CL_KERNEL_REFERENCE_COUNT'.\nclGetKernelReferenceCount :: CLKernel -> IO CLuint\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_CONTEXT'.\nclGetKernelContext :: CLKernel -> IO CLContext\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_PROGRAM'.\nclGetKernelProgram :: CLKernel -> IO CLProgram\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n\n#c\nenum CLKernelGroupInfo {\n cL_KERNEL_WORK_GROUP_SIZE=CL_KERNEL_WORK_GROUP_SIZE,\n cL_KERNEL_COMPILE_WORK_GROUP_SIZE=CL_KERNEL_COMPILE_WORK_GROUP_SIZE,\n cL_KERNEL_LOCAL_MEM_SIZE=CL_KERNEL_LOCAL_MEM_SIZE,\n };\n#endc\n{#enum CLKernelGroupInfo {upcaseFirstLetter} #}\n\n-- | This provides a mechanism for the application to query the work-group size\n-- that can be used to execute a kernel on a specific device given by\n-- device. The OpenCL implementation uses the resource requirements of the\n-- kernel (register usage etc.) to determine what this work-group size should\n-- be.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_WORK_GROUP_SIZE'.\nclGetKernelWorkGroupSize :: CLKernel -> CLDeviceID -> IO CSize\nclGetKernelWorkGroupSize krn device = wrapGetInfo (\\(dat :: Ptr CSize)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_WORK_GROUP_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Returns the work-group size specified by the __attribute__((reqd_work_gr\n-- oup_size(X, Y, Z))) qualifier. See Function Qualifiers. If the work-group\n-- size is not specified using the above attribute qualifier (0, 0, 0) is\n-- returned.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_COMPILE_WORK_GROUP_SIZE'.\nclGetKernelCompileWorkGroupSize :: CLKernel -> CLDeviceID -> IO [CSize]\nclGetKernelCompileWorkGroupSize krn device = do\n allocaArray num $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr buff) nullPtr)\n $ peekArray num buff\n where \n infoid = getCLValue CL_KERNEL_COMPILE_WORK_GROUP_SIZE\n num = 3\n elemSize = fromIntegral $ sizeOf (0::CSize)\n size = fromIntegral $ num * elemSize\n\n\n-- | Returns the amount of local memory in bytes being used by a kernel. This\n-- includes local memory that may be needed by an implementation to execute the\n-- kernel, variables declared inside the kernel with the __local address\n-- qualifier and local memory to be allocated for arguments to the kernel\n-- declared as pointers with the __local address qualifier and whose size is\n-- specified with 'clSetKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel declared\n-- with the __local address qualifier, is not specified, its size is assumed to\n-- be 0.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_LOCAL_MEM_SIZE'.\nclGetKernelLocalMemSize :: CLKernel -> CLDeviceID -> IO CLulong\nclGetKernelLocalMemSize krn device = wrapGetInfo (\\(dat :: Ptr CLulong)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_LOCAL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CLulong)\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 System.GPU.OpenCL.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clCreateProgramWithBinary, clRetainProgram, \n clReleaseProgram, clUnloadCompiler, clBuildProgram, \n clGetProgramReferenceCount, clGetProgramContext, clGetProgramNumDevices, \n clGetProgramDevices, clGetProgramSource, clGetProgramBinarySizes, \n clGetProgramBinaries, clGetProgramBuildStatus, clGetProgramBuildOptions, \n clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clSetKernelArg, clGetKernelFunctionName, clGetKernelNumArgs, \n clGetKernelReferenceCount, clGetKernelContext, clGetKernelProgram, \n clGetKernelWorkGroupSize, clGetKernelCompileWorkGroupSize, \n clGetKernelLocalMemSize\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM, forM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLulong, CLProgram, CLContext, CLKernel, CLDeviceID, CLError,\n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, \n whenSuccess, wrapPError, wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import CALLCONV \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import CALLCONV \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import CALLCONV \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import CALLCONV \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import CALLCONV \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import CALLCONV \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it throws one of the\nfollowing 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO CLProgram\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n{-| Creates a program object for a context, and loads specified binary data into\nthe program object.\n\nThe program binaries specified by binaries contain the bits that describe the\nprogram executable that will be run on the device(s) associated with\ncontext. The program binary can consist of either or both of device-specific\nexecutable(s), and\/or implementation-specific intermediate representation (IR)\nwhich will be converted to the device-specific executable.\n\nOpenCL allows applications to create a program object using the program\nsource or binary and build appropriate program executables. This allows\napplications to determine whether they want to use the pre-built offline binary\nor load and compile the program source and use the executable compiled\/linked\nonline as the program executable. This can be very useful as it allows\napplications to load and build program executables online on its first instance\nfor appropriate OpenCL devices in the system. These executables can now be\nqueried and cached by the application. Future instances of the application\nlaunching will no longer need to compile and build the program executables. The\ncached executables can be read and loaded by the application, which can help\nsignificantly reduce the application initialization time.\n\nReturns a valid non-zero program object and a list of 'CLError' values whether\nthe program binary for each device specified in device_list was loaded\nsuccessfully or not. It is list of the same length the list of devices with\n'CL_SUCCESS' if binary was successfully loaded for device specified by same\nposition; otherwise returns 'CL_INVALID_VALUE' if length of binary is zero or\n'CL_INVALID_BINARY' if program binary is not a valid binary\nfor the specified device.\n\nThe function can throw on of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context. \n\n * 'CL_INVALID_VALUE' if the device list is empty; or if lengths or binaries are\nempty.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in the device list are not in\nthe list of devices associated with context.\n\n * 'CL_INVALID_BINARY' if an invalid program binary was encountered for any\ndevice.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-} \nclCreateProgramWithBinary :: CLContext -> [CLDeviceID] -> [[Word8]] \n -> IO (CLProgram, [CLError])\nclCreateProgramWithBinary ctx devs bins = wrapPError $ \\perr -> do withArray\ndevs $ \\pdevs -> do withArray lbins $ \\plbins -> do buffs <- forM bins $ \\bs ->\ndo buff <- mallocArray (length bs) :: IO (Ptr Word8) pokeArray buff bs return\nbuff\n\n ret <- withArray buffs $ \\(pbuffs :: Ptr (Ptr Word8)) -> do\n allocaArray ndevs $ \\(perrs :: Ptr CLint) -> do\n prog <- raw_clCreateProgramWithBinary ctx (fromIntegral ndevs) pdevs plbins pbuffs perrs perr\n errs <- peekArray ndevs perrs\n return (prog, map getEnumCL errs)\n \n mapM_ free buffs\n return ret\n \n where\n lbins = map (fromIntegral . length) bins :: [CSize]\n ndevs = length devs\n\n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram can throw the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO ()\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n whenSuccess (raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr)\n $ return ()\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO CSize\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid 0 nullPtr value_size)\n $ peek value_size\n \n-- | Return the program 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 clGetProgramInfo with\n-- 'CL_PROGRAM_REFERENCE_COUNT'.\nclGetProgramReferenceCount :: CLProgram -> IO CLuint\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_CONTEXT'.\nclGetProgramContext :: CLProgram -> IO CLContext\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_NUM_DEVICES'.\nclGetProgramNumDevices :: CLProgram -> IO CLuint\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_DEVICES'.\nclGetProgramDevices :: CLProgram -> IO [CLDeviceID]\nclGetProgramDevices prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_SOURCE'.\nclGetProgramSource :: CLProgram -> IO String\nclGetProgramSource prg = do\n n <- getProgramInfoSize prg infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARY_SIZES'.\nclGetProgramBinarySizes :: CLProgram -> IO [CSize]\nclGetProgramBinarySizes prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n\nThis function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARIES'.\n-}\nclGetProgramBinaries :: CLProgram -> IO [[Word8]]\nclGetProgramBinaries prg = do\n sizes <- clGetProgramBinarySizes prg\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr)\n $ zipWithM peekArray (map fromIntegral sizes) buffers\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO CSize\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid 0 nullPtr val)\n $ peek val\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_STATUS'.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO CLBuildStatus\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_OPTIONS'.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildOptions prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_LOG'.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildLog prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it throws one of the following 'CLError'\nexceptions:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO CLKernel\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, throws 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, throws 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and throws\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO [CLKernel]\nclCreateKernelsInProgram prg = do\n n <- alloca $ \\pn -> do\n whenSuccess (raw_clCreateKernelsInProgram prg 0 nullPtr pn)\n $ peek pn \n allocaArray (fromIntegral n) $ \\pks -> do\n whenSuccess (raw_clCreateKernelsInProgram prg n pks nullPtr)\n $ peekArray (fromIntegral n) pks\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n{-| Used to set the argument value for a specific argument of a kernel.\n\nA kernel object does not update the reference count for objects such as memory,\nsampler objects specified as argument values by 'clSetKernelArg', Users may not\nrely on a kernel object to retain objects specified as argument values to the\nkernel.\n\nImplementations shall not allow 'CLKernel' objects to hold reference counts to\n'CLKernel' arguments, because no mechanism is provided for the user to tell the\nkernel to release that ownership right. If the kernel holds ownership rights on\nkernel args, that would make it impossible for the user to tell with certainty\nwhen he may safely release user allocated resources associated with OpenCL\nobjects such as the CLMem backing store used with 'CL_MEM_USE_HOST_PTR'.\n\n'clSetKernelArg' throws one of the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n \n * 'CL_INVALID_ARG_INDEX' if arg_index is not a valid argument index.\n\n * 'CL_INVALID_ARG_VALUE' if arg_value specified is NULL for an argument that is\nnot declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_MEM_OBJECT' for an argument declared to be a memory object when\nthe specified arg_value is not a valid memory object.\n\n * 'CL_INVALID_SAMPLER' for an argument declared to be of type sampler_t when\nthe specified arg_value is not a valid sampler object.\n\n * 'CL_INVALID_ARG_SIZE' if arg_size does not match the size of the data type\nfor an argument that is not a memory object or if the argument is a memory\nobject and arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is\ndeclared with the __local qualifier or if the argument is a sampler and arg_size\n!= sizeof(cl_sampler). \n-}\nclSetKernelArg :: Storable a => CLKernel -> CLuint -> a -> IO ()\nclSetKernelArg krn idx val = with val $ \\pval -> do\n whenSuccess (raw_clSetKernelArg krn idx (fromIntegral . sizeOf $ val) (castPtr pval))\n $ return ()\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO CSize\ngetKernelInfoSize krn infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid 0 nullPtr val)\n $ peek val\n \n-- | Return the kernel function name.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_FUNCTION_NAME'.\nclGetKernelFunctionName :: CLKernel -> IO String\nclGetKernelFunctionName krn = do\n n <- getKernelInfoSize krn infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_NUM_ARGS'.\nclGetKernelNumArgs :: CLKernel -> IO CLuint\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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 clGetKernelInfo with\n-- 'CL_KERNEL_REFERENCE_COUNT'.\nclGetKernelReferenceCount :: CLKernel -> IO CLuint\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_CONTEXT'.\nclGetKernelContext :: CLKernel -> IO CLContext\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_PROGRAM'.\nclGetKernelProgram :: CLKernel -> IO CLProgram\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n\n#c\nenum CLKernelGroupInfo {\n cL_KERNEL_WORK_GROUP_SIZE=CL_KERNEL_WORK_GROUP_SIZE,\n cL_KERNEL_COMPILE_WORK_GROUP_SIZE=CL_KERNEL_COMPILE_WORK_GROUP_SIZE,\n cL_KERNEL_LOCAL_MEM_SIZE=CL_KERNEL_LOCAL_MEM_SIZE,\n };\n#endc\n{#enum CLKernelGroupInfo {upcaseFirstLetter} #}\n\n-- | This provides a mechanism for the application to query the work-group size\n-- that can be used to execute a kernel on a specific device given by\n-- device. The OpenCL implementation uses the resource requirements of the\n-- kernel (register usage etc.) to determine what this work-group size should\n-- be.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_WORK_GROUP_SIZE'.\nclGetKernelWorkGroupSize :: CLKernel -> CLDeviceID -> IO CSize\nclGetKernelWorkGroupSize krn device = wrapGetInfo (\\(dat :: Ptr CSize)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_WORK_GROUP_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Returns the work-group size specified by the __attribute__((reqd_work_gr\n-- oup_size(X, Y, Z))) qualifier. See Function Qualifiers. If the work-group\n-- size is not specified using the above attribute qualifier (0, 0, 0) is\n-- returned.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_COMPILE_WORK_GROUP_SIZE'.\nclGetKernelCompileWorkGroupSize :: CLKernel -> CLDeviceID -> IO [CSize]\nclGetKernelCompileWorkGroupSize krn device = do\n allocaArray num $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr buff) nullPtr)\n $ peekArray num buff\n where \n infoid = getCLValue CL_KERNEL_COMPILE_WORK_GROUP_SIZE\n num = 3\n elemSize = fromIntegral $ sizeOf (0::CSize)\n size = fromIntegral $ num * elemSize\n\n\n-- | Returns the amount of local memory in bytes being used by a kernel. This\n-- includes local memory that may be needed by an implementation to execute the\n-- kernel, variables declared inside the kernel with the __local address\n-- qualifier and local memory to be allocated for arguments to the kernel\n-- declared as pointers with the __local address qualifier and whose size is\n-- specified with 'clSetKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel declared\n-- with the __local address qualifier, is not specified, its size is assumed to\n-- be 0.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_LOCAL_MEM_SIZE'.\nclGetKernelLocalMemSize :: CLKernel -> CLDeviceID -> IO CLulong\nclGetKernelLocalMemSize krn device = wrapGetInfo (\\(dat :: Ptr CLulong)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_LOCAL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CLulong)\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ff6293d6461200999ec1705b8ceafcd0c891c917","subject":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)","message":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a5a209ef0f16f38571be7fd322d8a99e67f9bc1c","subject":"Add pixbufRenderThresholdAlpha","message":"Add pixbufRenderThresholdAlpha\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"b55f4f0dfd37c4b4d6322266c05f150c609c4da6","subject":"Improve EventListener a bit","message":"Improve EventListener a bit\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/EventTargetClosures.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/DOM\/EventTargetClosures.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# CFILES events.c #-}\nmodule Graphics.UI.Gtk.WebKit.DOM.EventTargetClosures\n (EventName(..), SaferEventListener(..), EventListener(..), unEventListener, EventListenerClass(..),\n eventListenerNew, eventListenerNewAsync, eventListenerNewSync, eventListenerRelease) where\nimport Control.Monad.Reader (ReaderT)\nimport System.Glib.FFI (newStablePtr, freeStablePtr, StablePtr, Ptr(..), toBool, CInt(..), CChar,\n withForeignPtr, fromBool)\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Control.Monad (void)\n\nnewtype EventName t e = EventName String\nnewtype SaferEventListener t e = SaferEventListener EventListener\n\n{# pointer *GClosure newtype #}\n\ndata EventListener = EventListener (Ptr GClosure) (StablePtr (Ptr GObject -> Ptr GObject -> IO ()))\n\nunEventListener (EventListener p _) = p\n\nclass EventListenerClass a where\n toEventListener :: a -> EventListener\n\ninstance EventListenerClass EventListener where\n toEventListener a = a\n\nforeign import ccall unsafe \"gtk2hs_closure_new\"\n gtk2hs_closure_new :: StablePtr a -> IO (Ptr GClosure)\n\neventListenerNew :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNew callback = do\n sptr <- newStablePtr action\n gclosurePtr <- gtk2hs_closure_new sptr\n return $ EventListener gclosurePtr sptr\n where action :: Ptr GObject -> Ptr GObject -> IO ()\n action obj1 obj2 =\n failOnGError $\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj2) >>= \\obj2' ->\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj1) >>= \\obj1' ->\n callback (unsafeCastGObject obj2')\n\neventListenerNewAsync :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNewAsync = eventListenerNew\n\neventListenerNewSync :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNewSync = eventListenerNew\n\nforeign import ccall unsafe \"g_closure_unref\"\n g_closure_unref :: Ptr GClosure -> IO ()\n\neventListenerRelease :: EventListener -> IO ()\neventListenerRelease (EventListener gclosurePtr sptr) = do\n g_closure_unref gclosurePtr\n freeStablePtr sptr\n\n\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# CFILES events.c #-}\nmodule Graphics.UI.Gtk.WebKit.DOM.EventTargetClosures\n (EventName(..), SaferEventListener(..), EventListener(..), unEventListener, EventListenerClass(..), eventListenerNew) where\nimport Control.Monad.Reader (ReaderT)\nimport System.Glib.FFI (newStablePtr, StablePtr, Ptr(..), toBool, CInt(..), CChar,\n withForeignPtr, fromBool)\nimport System.Glib.UTFString\nimport Control.Applicative\n{#import Graphics.UI.Gtk.WebKit.Types#}\nimport System.Glib.GError\nimport Control.Monad (void)\n\nnewtype EventName t e = EventName String\nnewtype SaferEventListener t e = SaferEventListener EventListener\n\n{# pointer *GClosure as EventListener newtype #}\n\nunEventListener (EventListener p) = p\n\nclass EventListenerClass a where\n toEventListener :: a -> EventListener\n\ninstance EventListenerClass EventListener where\n toEventListener a = a\n\nforeign import ccall unsafe \"gtk2hs_closure_new\"\n gtk2hs_closure_new :: StablePtr a -> IO (Ptr EventListener)\n\neventListenerNew :: EventClass event => (event -> IO ()) -> IO EventListener\neventListenerNew callback = do -- EventListener . castRef <$> syncCallback1 AlwaysRetain True (callback . unsafeCastGObject . GObject)\n sptr <- newStablePtr action\n gclosurePtr <- gtk2hs_closure_new sptr\n return $ EventListener gclosurePtr\n where action :: Ptr GObject -> Ptr GObject -> IO ()\n action obj1 obj2 =\n failOnGError $\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj2) >>= \\obj2' ->\n makeNewGObject (GObject, objectUnrefFromMainloop) (return obj1) >>= \\obj1' ->\n callback (unsafeCastGObject obj2')\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7b3cb0b22bf6dc636683d776cb276978ecf03bce","subject":"gstreamer: remove commented function messageParseAsyncStart in Message.chs","message":"gstreamer: remove commented function messageParseAsyncStart in Message.chs\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Message.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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n \n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\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 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--\nmodule Media.Streaming.GStreamer.Message (\n \n Message,\n MessageClass,\n castToMessage,\n toMessage,\n fromMessage,\n MessageType(..),\n messageTypeGetName,\n messageTypeToQuark,\n messageSrc,\n messageTimestamp,\n messageType,\n messageTypeName,\n messageStructure,\n messageNewApplication,\n messageParseClockLost,\n messageParseClockProvide,\n messageParseError,\n messageParseInfo,\n messageParseNewClock,\n messageParseSegmentDone,\n messageParseSegmentStart,\n messageParseStateChanged,\n messageParseTag,\n messageParseBuffering,\n messageParseWarning,\n messageParseDuration, \n --messageParseAsyncStart\n ) where\n\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Types#}\nimport System.Glib.FFI\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport System.Glib.GError\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nmessageTypeGetName :: MessageType\n -> String\nmessageTypeGetName messageType =\n unsafePerformIO $\n {# call message_type_get_name #} (fromIntegral $ fromEnum messageType) >>=\n peekUTFString\n\nmessageTypeToQuark :: MessageType\n -> Quark\nmessageTypeToQuark messageType =\n {# call fun message_type_to_quark #} (fromIntegral $ fromEnum messageType)\n\nmessageSrc :: Message\n -> Object\nmessageSrc message =\n unsafePerformIO $ withMessage message {# get GstMessage->src #} >>=\n newObject_ Object\n\nmessageTimestamp :: Message\n -> ClockTime\nmessageTimestamp message =\n unsafePerformIO $ withMessage message {# get GstMessage->timestamp #}\n\nmessageType :: Message\n -> MessageType\nmessageType message =\n toEnum $ fromIntegral $ unsafePerformIO $\n withMessage message cMessageGetMessageType\nforeign import ccall unsafe \"_hs_gst_message_get_message_type\"\n cMessageGetMessageType :: Ptr Message\n -> IO {# type GstMessageType #}\n\nmessageTypeName :: Message\n -> String\nmessageTypeName =\n messageTypeGetName . messageType\n\nmessageStructure :: Message\n -> Structure\nmessageStructure message =\n unsafePerformIO $ {# call message_get_structure #} message >>= newStructure_\n\nmessageNewApplication :: Object\n -> Structure\n -> IO Message\nmessageNewApplication object structure =\n (giveStructure structure $ {# call message_new_application #} object) >>=\n newMessage\n\nmessageParseClockLost :: Message\n -> Maybe Clock\nmessageParseClockLost message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n liftM Just $ peek clockPtr >>= newClock_\n\nmessageParseClockProvide :: Message\n -> Maybe (Clock, Bool)\nmessageParseClockProvide message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n alloca $ \\readyPtr ->\n do poke clockPtr nullPtr\n poke readyPtr $ fromBool False\n {# call message_parse_clock_provide #} message (castPtr clockPtr) readyPtr\n clock <- peek clockPtr >>= maybePeek newClock_\n ready <- peek readyPtr\n return $ maybe Nothing (\\clock -> Just (clock, toBool ready)) clock\n\nmessageParseError :: Message\n -> (Maybe GError, Maybe String)\nmessageParseError message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_error #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseInfo :: Message\n -> (Maybe GError, Maybe String)\nmessageParseInfo message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_info #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseNewClock :: Message\n -> Maybe Clock\nmessageParseNewClock message =\n unsafePerformIO $ alloca $ \\clockPtr ->\n do poke clockPtr nullPtr\n {# call message_parse_clock_lost #} message $ castPtr clockPtr\n peek clockPtr >>= maybePeek newClock_\n\nmessageParseSegmentDone :: Message\n -> (Format, Int64)\nmessageParseSegmentDone message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_done #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseSegmentStart :: Message\n -> (Format, Int64)\nmessageParseSegmentStart message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_segment_start #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\nmessageParseStateChanged :: Message\n -> (State, State, State)\nmessageParseStateChanged message =\n unsafePerformIO $ alloca $ \\oldStatePtr ->\n alloca $ \\newStatePtr -> alloca $ \\pendingPtr ->\n do poke oldStatePtr 0\n poke newStatePtr 0\n poke pendingPtr 0\n {# call message_parse_state_changed #} message oldStatePtr newStatePtr pendingPtr\n oldState <- liftM (toEnum . fromIntegral) $ peek oldStatePtr\n newState <- liftM (toEnum . fromIntegral) $ peek newStatePtr\n pending <- liftM (toEnum . fromIntegral) $ peek pendingPtr\n return (oldState, newState, pending)\n\nmessageParseTag :: Message\n -> TagList\nmessageParseTag message =\n unsafePerformIO $ alloca $ \\tagListPtr ->\n do poke tagListPtr nullPtr\n {# call message_parse_tag #} message $ castPtr tagListPtr\n peek tagListPtr >>= newTagList\n\nmessageParseBuffering :: Message\n -> Int\nmessageParseBuffering message =\n fromIntegral $ unsafePerformIO $ alloca $ \\percentPtr ->\n do poke percentPtr 0\n {# call message_parse_buffering #} message percentPtr\n peek percentPtr\n\nmessageParseWarning :: Message\n -> (Maybe GError, Maybe String)\nmessageParseWarning message =\n unsafePerformIO $ alloca $ \\gErrorPtr ->\n alloca $ \\debugPtr ->\n do poke gErrorPtr nullPtr\n poke debugPtr nullPtr\n {# call message_parse_warning #} message (castPtr gErrorPtr) debugPtr\n gError <- peek gErrorPtr >>=\n (maybePeek $ \\ptr ->\n do gError <- peek ptr\n {# call g_error_free #} $ castPtr ptr\n return gError)\n debug <- peek debugPtr >>= maybePeek readUTFString\n return (gError, debug)\n\nmessageParseDuration :: Message\n -> (Format, Int64)\nmessageParseDuration message =\n unsafePerformIO $ alloca $ \\formatPtr ->\n alloca $ \\positionPtr ->\n do poke formatPtr $ fromIntegral $ fromEnum FormatUndefined\n poke positionPtr 0\n {# call message_parse_duration #} message formatPtr positionPtr\n format <- peek formatPtr\n position <- peek positionPtr\n return (toEnum $ fromIntegral format, fromIntegral position)\n\n{-\nmessageParseAsyncStart :: Message\n -> Bool\nmessageParseAsyncStart message =\n toBool $ unsafePerformIO $ alloca $ \\newBaseTimePtr ->\n do poke newBaseTimePtr $ fromBool False\n {# call message_parse_async_start #} message newBaseTimePtr\n peek newBaseTimePtr\n-}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0ebdc33b107910916e734411f0a4ccadd47dbcf2","subject":"Add put operations.","message":"Add put operations.\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 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","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\nhyperclientCreate :: String -> Int16 -> IO HyperclientPtr\nhyperclientCreate host port = do\n inHost <- newCString host\n {# call hyperclient_create #} inHost (fromIntegral port)\n\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-- result <- hyperclientGetRaw client space inKey (fromIntegral inKeySize) returnCodePtr attributePtr attributePtrSize\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"392f9bca13006fc3b31e93c7a948345d37da559e","subject":"wibble","message":"wibble\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Errhandler.chs","new_file":"src\/Control\/Parallel\/MPI\/Errhandler.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Errhandler (Errhandler, errorsAreFatal, errorsReturn) where\n\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Errhandler = {# type MPI_Errhandler #}\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr Errhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr Errhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = unsafePerformIO $ peek errorsReturn_\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Errhandler (Errhandler, errorsAreFatal, errorsReturn) where\n\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Errhandler = {# type MPI_Errhandler #}\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr Errhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr Errhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = unsafePerformIO $ peek errorsReturn_\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"99dd6d79d8941eaf660744c1eb60c52c9de7118b","subject":"Add the forgotten Nothing case to readFile.","message":"Add the forgotten Nothing case to readFile.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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\nfileRead file Nothing = constructNewGObject mkFileInputStream $\n propagateGError $ {# call file_read #} (toFile file) (Cancellable nullForeignPtr)\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\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9e80f95c38bd9a170f35dbb37e86ae49c58adc23","subject":"A very minor haddock tweak in for callbacks.","message":"A very minor haddock tweak in for callbacks.\n\nIgnore-this: b867cabbda8b6bb0aa821421c40ba05c\n\ndarcs-hash:20090308135818-ed7c9-fb655fc018bb2b40193ed067d2c6b0d70aff17f1.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-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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(..), XMLParseError(..),\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 Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = do\n ok <- withHandlers parser $ doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\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 error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return True\n-- to continue parsing as normal, or False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return True to continue parsing as normal, or False to\n-- terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return True to continue\n-- parsing as normal, or False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","old_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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(..), XMLParseError(..),\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 Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = do\n ok <- withHandlers parser $ doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\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 error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return False to terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ea5e0018a54651390ed3db0bca67f7f4c36d5e39","subject":"gstreamer: more docs for M.S.G.Core.Bus","message":"gstreamer: more docs for M.S.G.Core.Bus\n\ndarcs-hash:20080519004951-21862-34406132707946ab5cebc5248041c1fa9a8cce06.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"f1743f418b7b9939b43fc25d7af2cf8ae115c020","subject":"gstreamer: more docs for M.S.G.Core.Bus","message":"gstreamer: more docs for M.S.G.Core.Bus\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"6677f7ea27c3b919c11d76e6b044a6a29472f26c","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","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"4f0c6bff792c2291a87a89bd4ed62ed17fc5916c","subject":"gstreamer: more docs in M.S.G.Core.Caps","message":"gstreamer: more docs in M.S.G.Core.Caps","repos":"vincenthz\/webkit","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":"b26f7845fb84d5dda3b6173e93ce297d8befa4c1","subject":"[project @ 2002-07-17 15:59:19 by juhp]","message":"[project @ 2002-07-17 15:59:19 by juhp]\n\n(treeViewColumnNewWithAttributes): Haskell implementation to\navoid binding to original variad function.\n(treeViewColumnAddAttributes): New convenience function.\n(treeViewColumnSetAttributes): Haskell implementation to\navoid binding to original variad function.\n(treeViewColumnClearAttributes): Add binding.\n\ndarcs-hash:20020717155919-f332a-a89d58aed845a5c401649ab842f685953b622f4b.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/treeList\/TreeViewColumn.chs","new_file":"gtk\/treeList\/TreeViewColumn.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget TreeViewColumn@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 May 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/17 15:59:19 $\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--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * tree_view_column_new_with_attributes and tree_view_column_set_attributes \n-- are variadic and the funcitonality can be achieved through other \n-- functions.\n--\n-- * tree_view_column_set_cell_data and tree_view_column_cell_get_size are not\n-- bound because I am not sure what they do and when they are useful\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * treeViewColumnSetCellData is not bound. With this function the user has\n-- control over how data in the store is mapped to the attributes of a\n-- cell renderer. This functin should be bound in the future to allow the\n-- user to insert Haskell data types into the store and convert these\n-- values to attributes of cell renderers.\n--\nmodule TreeViewColumn(\n TreeViewColumn,\n TreeViewColumnClass,\n castToTreeViewColumn,\n treeViewColumnNew,\n treeViewColumnNewWithAttributes,\n treeViewColumnPackStart,\n treeViewColumnPackEnd,\n treeViewColumnClear,\n treeViewColumnGetCellRenderers,\n treeViewColumnAddAttribute,\n treeViewColumnAddAttributes,\n treeViewColumnSetAttributes,\n treeViewColumnClearAttributes,\n treeViewColumnSetSpacing,\n treeViewColumnGetSpacing,\n treeViewColumnSetVisible,\n treeViewColumnGetVisible,\n treeViewColumnSetResizable,\n treeViewColumnGetResizable,\n TreeViewColumnSizing(..),\n treeViewColumnSetSizing,\n treeViewColumnGetSizing,\n treeViewColumnGetWidth,\n treeViewColumnSetFixedWidth,\n treeViewColumnSetMinWidth,\n treeViewColumnGetMinWidth,\n treeViewColumnSetMaxWidth,\n treeViewColumnGetMaxWidth,\n treeViewColumnClicked,\n treeViewColumnSetTitle,\n treeViewColumnGetTitle,\n treeViewColumnSetClickable,\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 onColClicked,\n afterColClicked\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(TreeViewColumnSizing(..), SortType(..))\n{#import TreeModel#}\nimport CellRenderer (Attribute(..))\n{#import GList#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- TreeViewColumn type declaration\n\n-- methods\n\n-- @constructor treeViewColumnNew@ Generate a new TreeViewColumn widget.\n--\ntreeViewColumnNew :: IO TreeViewColumn\ntreeViewColumnNew = makeNewObject mkTreeViewColumn \n {#call tree_view_column_new#}\n\n-- @method treeViewColumnNewWithAttributes@ Returns a new TreeViewColumn with\n-- title @ref arg title@, cell renderer @ref arg cr@, and attributes\n-- @ref arg attribs@.\n--\ntreeViewColumnNewWithAttributes :: CellRendererClass cr => String -> cr -> \n\t\t\t\t [(String, Int)] -> IO TreeViewColumn\ntreeViewColumnNewWithAttributes title cr attribs =\n do\n tvc <- treeViewColumnNew\n treeViewColumnSetTitle tvc title\n treeViewColumnPackStart tvc cr True\n treeViewColumnAddAttributes tvc cr attribs\n return tvc\n\n-- @method treeViewColumnPackStart@ Add a cell renderer at the beginning of\n-- a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackStart :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackStart tvc cr expand = \n {#call unsafe tree_view_column_pack_start#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnPackEnd@ Add a cell renderer at the end of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackEnd :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackEnd tvc cr expand = \n {#call unsafe tree_view_column_pack_end#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnClear@ Remove the associations of attributes\n-- to a store for all @ref type CellRenderers@.\n--\ntreeViewColumnClear :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClear tvc = \n {#call tree_view_column_clear#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetCellRenderers@ Retrieve all \n-- @ref type CellRenderer@s that are contained in this column.\n--\ntreeViewColumnGetCellRenderers :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> IO [CellRenderer]\ntreeViewColumnGetCellRenderers tvc = do\n glist <- {#call unsafe tree_view_column_get_cell_renderers#} \n\t (toTreeViewColumn tvc)\n crs <- fromGList glist\n mapM (makeNewObject mkCellRenderer) (map return crs)\n\n-- @method treeViewColumnAddAttribute@ Insert an attribute to change the\n-- behaviour of the column's cell renderer.\n--\n-- * The @ref type CellRenderer@ @ref arg cr@ must already be in \n-- @ref type TreeViewColumn@.\n--\ntreeViewColumnAddAttribute :: (TreeViewColumnClass tvc, CellRendererClass cr)\n\t\t\t => tvc -> cr -> String -> Int -> IO ()\ntreeViewColumnAddAttribute tvc cr attr col = \n withCString attr $ \\cstr -> {#call unsafe tree_view_column_add_attribute#} \n (toTreeViewColumn tvc) (toCellRenderer cr) cstr (fromIntegral col)\n\n-- @method treeViewColumnAddAttributes@ Insert attributes @ref arg attribs@\n-- to change the behaviour of column @ref arg tvc@'s cell renderer\n-- @ref arg cr@.\n--\ntreeViewColumnAddAttributes :: \n (TreeViewColumnClass tvc, CellRendererClass cr) => \n tvc -> cr -> [(String,Int)] -> IO ()\ntreeViewColumnAddAttributes tvc cr attribs = \n mapM_ (\\ (attr, col) -> treeViewColumnAddAttribute tvc cr attr col) attribs\n\n-- @method treeViewColumnSetAttributes@ Set the attributes of\n-- the cell renderer @ref arg cr@ in the tree column @ref arg tvc@\n-- be @red arg attribs@.\n-- The attributes are given as a list of attribute\/column pairs.\n-- All existing attributes are removed, and replaced with the new attributes.\n--\ntreeViewColumnSetAttributes :: \n (TreeViewColumnClass tvc, CellRendererClass cr) =>\n tvc -> cr -> [(String, Int)] -> IO ()\ntreeViewColumnSetAttributes tvc cr attribs =\n do\n treeViewColumnClearAttributes tvc cr\n treeViewColumnAddAttributes tvc cr attribs\n\n-- @method treeViewColumnClearAttributes@ Clears all existing attributes\n-- of the column @ref arg tvc@.\n--\ntreeViewColumnClearAttributes :: \n (TreeViewColumnClass tvc, CellRendererClass cr) =>\n tvc -> cr -> IO ()\ntreeViewColumnClearAttributes tvc cr =\n {#call tree_view_column_clear_attributes#} (toTreeViewColumn tvc)\n (toCellRenderer cr)\n\n\n-- @method treeViewColumnSetSpacing@ Set the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnSetSpacing :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetSpacing tvc vis =\n {#call tree_view_column_set_spacing#} (toTreeViewColumn tvc) \n (fromIntegral vis)\n\n\n-- @method treeViewColumnGetSpacing@ Get the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnGetSpacing :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSpacing tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_spacing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetVisible@ Set the visibility of a given column.\n--\ntreeViewColumnSetVisible :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetVisible tvc vis =\n {#call tree_view_column_set_visible#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetVisible@ Get the visibility of a given column.\n--\ntreeViewColumnGetVisible :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetVisible tvc = liftM toBool $\n {#call unsafe tree_view_column_get_visible#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetResizable@ Set if a given column is resizable\n-- by the user.\n--\ntreeViewColumnSetResizable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetResizable tvc vis =\n {#call tree_view_column_set_resizable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetResizable@ Get if a given column is resizable\n-- by the user.\n--\ntreeViewColumnGetResizable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetResizable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_resizable#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetSizing@ Set wether the column can be resized.\n--\ntreeViewColumnSetSizing :: TreeViewColumnClass tvc => tvc ->\n TreeViewColumnSizing -> IO ()\ntreeViewColumnSetSizing tvc size = {#call tree_view_column_set_sizing#} \n (toTreeViewColumn tvc) ((fromIntegral.fromEnum) size)\n\n\n-- @method treeViewColumnGetSizing@ Return the resizing type of the column.\n--\ntreeViewColumnGetSizing :: TreeViewColumnClass tvc => tvc ->\n IO TreeViewColumnSizing\ntreeViewColumnGetSizing tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sizing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnGetWidth@ Query the current width of the column.\n--\ntreeViewColumnGetWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_width#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetFixedWidth@ Set the width of the column.\n--\n-- * This is meaningful only if the sizing type is\n-- @ref type TreeViewColumnFixed@.\n--\ntreeViewColumnSetFixedWidth :: TreeViewColumnClass tvc => Int -> tvc -> IO ()\ntreeViewColumnSetFixedWidth width tvc = \n {#call tree_view_column_set_fixed_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n\n-- @method treeViewColumnSetMinWidth@ Set minimum width of the column.\n--\ntreeViewColumnSetMinWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMinWidth tvc width = {#call tree_view_column_set_min_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMinWidth@ Get the minimum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMinWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMinWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_min_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetMaxWidth@ Set maximum width of the column.\n--\ntreeViewColumnSetMaxWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMaxWidth tvc width = {#call tree_view_column_set_max_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMaxWidth@ Get the maximum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMaxWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMaxWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_max_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnClicked@ Emit the @ref arg clicked@ signal on the\n-- column.\n--\ntreeViewColumnClicked :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClicked tvc =\n {#call tree_view_column_clicked#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetTitle@ Set the widget's title if a custom widget\n-- has not been set.\n--\ntreeViewColumnSetTitle :: TreeViewColumnClass tvc => tvc -> String -> IO ()\ntreeViewColumnSetTitle tvc title = withCString title $\n {#call tree_view_column_set_title#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetTitle@ Get the widget's title.\n--\ntreeViewColumnGetTitle :: TreeViewColumnClass tvc => tvc -> IO (Maybe String)\ntreeViewColumnGetTitle tvc = do\n strPtr <- {#call unsafe tree_view_column_get_title#} (toTreeViewColumn tvc)\n if strPtr==nullPtr then return Nothing else liftM Just $ peekCString strPtr\n\n-- @method treeViewColumnSetClickable@ Set if the column should be sensitive\n-- to mouse clicks.\n--\ntreeViewColumnSetClickable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetClickable tvc click = {#call tree_view_column_set_clickable#} \n (toTreeViewColumn tvc) (fromBool click)\n\n-- @method treeViewColumnSetWidget@ Set the column's title to this widget.\n--\ntreeViewColumnSetWidget :: (TreeViewColumnClass tvc, WidgetClass w) => tvc ->\n w -> IO ()\ntreeViewColumnSetWidget tvc w =\n {#call tree_view_column_set_widget#} (toTreeViewColumn tvc) (toWidget w)\n\n-- @method treeViewColumnGetWidget@ Retrieve the widget responsible for\n-- showing the column title. In case only a text title was set this will be a\n-- @ref arg Alignment@ widget with a @ref arg Label@ inside.\n--\ntreeViewColumnGetWidget :: TreeViewColumnClass tvc => tvc -> IO Widget\ntreeViewColumnGetWidget tvc = makeNewObject mkWidget $\n {#call unsafe tree_view_column_get_widget#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetAlignment@ Set the alignment of the title.\n--\ntreeViewColumnSetAlignment :: TreeViewColumnClass tvc => tvc -> Float -> IO ()\ntreeViewColumnSetAlignment tvc align = {#call tree_view_column_set_alignment#}\n (toTreeViewColumn tvc) (realToFrac align)\n\n-- @method treeViewColumnGetAlignment@ Get the alignment of the titlte.\n--\ntreeViewColumnGetAlignment :: TreeViewColumnClass tvc => tvc -> IO Float\ntreeViewColumnGetAlignment tvc = liftM realToFrac $\n {#call unsafe tree_view_column_get_alignment#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetReorderable@ Set if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnSetReorderable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetReorderable tvc vis =\n {#call tree_view_column_set_reorderable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n-- @method treeViewColumnGetReorderable@ Get if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnGetReorderable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetReorderable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_reorderable#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortColumnId@ Set the column by which to sort.\n--\n-- * Sets the logical @ref arg 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 column in\n-- the @ref type TreeModel@.\n--\ntreeViewColumnSetSortColumnId :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Int -> IO ()\ntreeViewColumnSetSortColumnId tvc columnId = \n {#call tree_view_column_set_sort_column_id#} \n (toTreeViewColumn tvc) (fromIntegral columnId)\n\n-- @method treeViewColumnGetSortColumnId@ Get the column by which to sort.\n--\n-- * Retrieves the logical @ref arg columnId@ that the model sorts on when\n-- this column is selected for sorting.\n--\n-- * Returns -1 if this column can't be used for sorting.\n--\ntreeViewColumnGetSortColumnId :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSortColumnId tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_sort_column_id#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortIndicator@ Set if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnSetSortIndicator :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Bool -> IO ()\ntreeViewColumnSetSortIndicator tvc sort =\n {#call tree_view_column_set_sort_indicator#} (toTreeViewColumn tvc) \n (fromBool sort)\n\n-- @method treeViewColumnGetSortIndicator@ Query if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnGetSortIndicator :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetSortIndicator tvc = liftM toBool $\n {#call unsafe tree_view_column_get_sort_indicator#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortOrder@ Set if a given column is sorted\n-- in ascending or descending order.\n--\n-- * In order for sorting to work, it is necessary to either use automatic\n-- sorting via @ref method treeViewColumnSetSortColumnId@ or to use a\n-- user defined sorting on the elements in a @ref type TreeModel@.\n--\ntreeViewColumnSetSortOrder :: TreeViewColumnClass tvc => \n\t\t\t tvc -> SortType -> IO ()\ntreeViewColumnSetSortOrder tvc sort =\n {#call tree_view_column_set_sort_order#} (toTreeViewColumn tvc) \n ((fromIntegral.fromEnum) sort)\n\n-- @method treeViewColumnGetSortOrder@ Query if a given column is sorted\n-- in ascending or descending order.\n--\ntreeViewColumnGetSortOrder :: TreeViewColumnClass tvc => tvc -> IO SortType\ntreeViewColumnGetSortOrder tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sort_order#} (toTreeViewColumn tvc)\n\n-- @signal colClicked@ Emitted when the header of this column has been\n-- clicked on.\n--\nonColClicked, afterColClicked :: TreeViewColumnClass tvc => tvc -> IO () -> \n\t\t\t\t\t\t\t IO (ConnectId tvc)\nonColClicked = connect_NONE__NONE \"clicked\" False\nafterColClicked = connect_NONE__NONE \"clicked\" True\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget TreeViewColumn@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/08 09:15:09 $\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--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * tree_view_column_new_with_attributes and tree_view_column_set_attributes \n-- are variadic and the funcitonality can be achieved through other \n-- functions.\n--\n-- * tree_view_column_set_cell_data and tree_view_column_cell_get_size are not\n-- bound because I am not sure what they do and when they are useful\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * treeViewColumnSetCellData is not bound. With this function the user has\n-- control over how data in the store is mapped to the attributes of a\n-- cell renderer. This functin should be bound in the future to allow the\n-- user to insert Haskell data types into the store and convert these\n-- values to attributes of cell renderers.\n--\nmodule TreeViewColumn(\n TreeViewColumn,\n TreeViewColumnClass,\n castToTreeViewColumn,\n treeViewColumnNew,\n treeViewColumnPackStart,\n treeViewColumnPackEnd,\n treeViewColumnClear,\n treeViewColumnGetCellRenderers,\n treeViewColumnAddAttribute,\n treeViewColumnSetSpacing,\n treeViewColumnGetSpacing,\n treeViewColumnSetVisible,\n treeViewColumnGetVisible,\n treeViewColumnSetResizable,\n treeViewColumnGetResizable,\n TreeViewColumnSizing(..),\n treeViewColumnSetSizing,\n treeViewColumnGetSizing,\n treeViewColumnGetWidth,\n treeViewColumnSetFixedWidth,\n treeViewColumnSetMinWidth,\n treeViewColumnGetMinWidth,\n treeViewColumnSetMaxWidth,\n treeViewColumnGetMaxWidth,\n treeViewColumnClicked,\n treeViewColumnSetTitle,\n treeViewColumnGetTitle,\n treeViewColumnSetClickable,\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 onColClicked,\n afterColClicked\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(TreeViewColumnSizing(..), SortType(..))\n{#import TreeModel#}\nimport CellRenderer (Attribute(..))\n{#import GList#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- TreeViewColumn type declaration\n\n-- methods\n\n-- @constructor treeViewColumnNew@ Generate a new TreeViewColumn widget.\n--\ntreeViewColumnNew :: IO TreeViewColumn\ntreeViewColumnNew = makeNewObject mkTreeViewColumn \n {#call tree_view_column_new#}\n\n-- @method treeViewColumnPackStart@ Add a cell renderer at the beginning of\n-- a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackStart :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackStart tvc cr expand = \n {#call unsafe tree_view_column_pack_start#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnPackEnd@ Add a cell renderer at the end of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @arg expand@ set to True.\n--\ntreeViewColumnPackEnd :: (TreeViewColumnClass tvc, CellRendererClass cr) =>\n\t\t\t tvc -> cr -> Bool -> IO ()\ntreeViewColumnPackEnd tvc cr expand = \n {#call unsafe tree_view_column_pack_end#} (toTreeViewColumn tvc)\n (toCellRenderer cr) (fromBool expand)\n\n-- @method treeViewColumnClear@ Remove the associations of attributes\n-- to a store for all @ref type CellRenderers@.\n--\ntreeViewColumnClear :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClear tvc = \n {#call tree_view_column_clear#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetCellRenderers@ Retrieve all \n-- @ref type CellRenderer@s that are contained in this column.\n--\ntreeViewColumnGetCellRenderers :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> IO [CellRenderer]\ntreeViewColumnGetCellRenderers tvc = do\n glist <- {#call unsafe tree_view_column_get_cell_renderers#} \n\t (toTreeViewColumn tvc)\n crs <- fromGList glist\n mapM (makeNewObject mkCellRenderer) (map return crs)\n\n-- @method treeViewColumnAddAttribute@ Insert an attribute to change the\n-- behaviour of the column's cell renderer.\n--\n-- * The @ref type CellRenderer@ @ref arg cr@ must already be in \n-- @ref type TreeViewColumn@.\n--\ntreeViewColumnAddAttribute :: (TreeViewColumnClass tvc, CellRendererClass cr)\n\t\t\t => tvc -> cr -> String -> Int -> IO ()\ntreeViewColumnAddAttribute tvc cr attr col = \n withCString attr $ \\cstr -> {#call unsafe tree_view_column_add_attribute#} \n (toTreeViewColumn tvc) (toCellRenderer cr) cstr (fromIntegral col)\n\n\n-- @method treeViewColumnSetSpacing@ Set the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnSetSpacing :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetSpacing tvc vis =\n {#call tree_view_column_set_spacing#} (toTreeViewColumn tvc) \n (fromIntegral vis)\n\n\n-- @method treeViewColumnGetSpacing@ Get the number of pixels between two\n-- cell renderers.\n--\ntreeViewColumnGetSpacing :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSpacing tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_spacing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetVisible@ Set the visibility of a given column.\n--\ntreeViewColumnSetVisible :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetVisible tvc vis =\n {#call tree_view_column_set_visible#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetVisible@ Get the visibility of a given column.\n--\ntreeViewColumnGetVisible :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetVisible tvc = liftM toBool $\n {#call unsafe tree_view_column_get_visible#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetResizable@ Set if a given column is resizable\n-- by the user.\n--\ntreeViewColumnSetResizable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetResizable tvc vis =\n {#call tree_view_column_set_resizable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n\n-- @method treeViewColumnGetResizable@ Get if a given column is resizable\n-- by the user.\n--\ntreeViewColumnGetResizable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetResizable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_resizable#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetSizing@ Set wether the column can be resized.\n--\ntreeViewColumnSetSizing :: TreeViewColumnClass tvc => tvc ->\n TreeViewColumnSizing -> IO ()\ntreeViewColumnSetSizing tvc size = {#call tree_view_column_set_sizing#} \n (toTreeViewColumn tvc) ((fromIntegral.fromEnum) size)\n\n\n-- @method treeViewColumnGetSizing@ Return the resizing type of the column.\n--\ntreeViewColumnGetSizing :: TreeViewColumnClass tvc => tvc ->\n IO TreeViewColumnSizing\ntreeViewColumnGetSizing tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sizing#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnGetWidth@ Query the current width of the column.\n--\ntreeViewColumnGetWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_width#} (toTreeViewColumn tvc)\n\n\n-- @method treeViewColumnSetFixedWidth@ Set the width of the column.\n--\n-- * This is meaningful only if the sizing type is\n-- @ref type TreeViewColumnFixed@.\n--\ntreeViewColumnSetFixedWidth :: TreeViewColumnClass tvc => Int -> tvc -> IO ()\ntreeViewColumnSetFixedWidth width tvc = \n {#call tree_view_column_set_fixed_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n\n-- @method treeViewColumnSetMinWidth@ Set minimum width of the column.\n--\ntreeViewColumnSetMinWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMinWidth tvc width = {#call tree_view_column_set_min_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMinWidth@ Get the minimum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMinWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMinWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_min_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetMaxWidth@ Set maximum width of the column.\n--\ntreeViewColumnSetMaxWidth :: TreeViewColumnClass tvc => tvc -> Int -> IO ()\ntreeViewColumnSetMaxWidth tvc width = {#call tree_view_column_set_max_width#} \n (toTreeViewColumn tvc) (fromIntegral width)\n\n-- @method treeViewColumnGetMaxWidth@ Get the maximum width of a column.\n-- Returns -1 if this width was not set.\n--\ntreeViewColumnGetMaxWidth :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetMaxWidth tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_max_width#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnClicked@ Emit the @ref arg clicked@ signal on the\n-- column.\n--\ntreeViewColumnClicked :: TreeViewColumnClass tvc => tvc -> IO ()\ntreeViewColumnClicked tvc =\n {#call tree_view_column_clicked#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetTitle@ Set the widget's title if a custom widget\n-- has not been set.\n--\ntreeViewColumnSetTitle :: TreeViewColumnClass tvc => tvc -> String -> IO ()\ntreeViewColumnSetTitle tvc title = withCString title $\n {#call tree_view_column_set_title#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnGetTitle@ Get the widget's title.\n--\ntreeViewColumnGetTitle :: TreeViewColumnClass tvc => tvc -> IO (Maybe String)\ntreeViewColumnGetTitle tvc = do\n strPtr <- {#call unsafe tree_view_column_get_title#} (toTreeViewColumn tvc)\n if strPtr==nullPtr then return Nothing else liftM Just $ peekCString strPtr\n\n-- @method treeViewColumnSetClickable@ Set if the column should be sensitive\n-- to mouse clicks.\n--\ntreeViewColumnSetClickable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetClickable tvc click = {#call tree_view_column_set_clickable#} \n (toTreeViewColumn tvc) (fromBool click)\n\n-- @method treeViewColumnSetWidget@ Set the column's title to this widget.\n--\ntreeViewColumnSetWidget :: (TreeViewColumnClass tvc, WidgetClass w) => tvc ->\n w -> IO ()\ntreeViewColumnSetWidget tvc w =\n {#call tree_view_column_set_widget#} (toTreeViewColumn tvc) (toWidget w)\n\n-- @method treeViewColumnGetWidget@ Retrieve the widget responsible for\n-- showing the column title. In case only a text title was set this will be a\n-- @ref arg Alignment@ widget with a @ref arg Label@ inside.\n--\ntreeViewColumnGetWidget :: TreeViewColumnClass tvc => tvc -> IO Widget\ntreeViewColumnGetWidget tvc = makeNewObject mkWidget $\n {#call unsafe tree_view_column_get_widget#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetAlignment@ Set the alignment of the title.\n--\ntreeViewColumnSetAlignment :: TreeViewColumnClass tvc => tvc -> Float -> IO ()\ntreeViewColumnSetAlignment tvc align = {#call tree_view_column_set_alignment#}\n (toTreeViewColumn tvc) (realToFrac align)\n\n-- @method treeViewColumnGetAlignment@ Get the alignment of the titlte.\n--\ntreeViewColumnGetAlignment :: TreeViewColumnClass tvc => tvc -> IO Float\ntreeViewColumnGetAlignment tvc = liftM realToFrac $\n {#call unsafe tree_view_column_get_alignment#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetReorderable@ Set if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnSetReorderable :: TreeViewColumnClass tvc => tvc -> Bool -> IO ()\ntreeViewColumnSetReorderable tvc vis =\n {#call tree_view_column_set_reorderable#} (toTreeViewColumn tvc) \n (fromBool vis)\n\n-- @method treeViewColumnGetReorderable@ Get if a given column is reorderable\n-- by the user.\n--\ntreeViewColumnGetReorderable :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetReorderable tvc = liftM toBool $\n {#call unsafe tree_view_column_get_reorderable#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortColumnId@ Set the column by which to sort.\n--\n-- * Sets the logical @ref arg 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 column in\n-- the @ref type TreeModel@.\n--\ntreeViewColumnSetSortColumnId :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Int -> IO ()\ntreeViewColumnSetSortColumnId tvc columnId = \n {#call tree_view_column_set_sort_column_id#} \n (toTreeViewColumn tvc) (fromIntegral columnId)\n\n-- @method treeViewColumnGetSortColumnId@ Get the column by which to sort.\n--\n-- * Retrieves the logical @ref arg columnId@ that the model sorts on when\n-- this column is selected for sorting.\n--\n-- * Returns -1 if this column can't be used for sorting.\n--\ntreeViewColumnGetSortColumnId :: TreeViewColumnClass tvc => tvc -> IO Int\ntreeViewColumnGetSortColumnId tvc = liftM fromIntegral $\n {#call unsafe tree_view_column_get_sort_column_id#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortIndicator@ Set if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnSetSortIndicator :: TreeViewColumnClass tvc => \n\t\t\t\t tvc -> Bool -> IO ()\ntreeViewColumnSetSortIndicator tvc sort =\n {#call tree_view_column_set_sort_indicator#} (toTreeViewColumn tvc) \n (fromBool sort)\n\n-- @method treeViewColumnGetSortIndicator@ Query if a given column has\n-- sorting arrows in its heading.\n--\ntreeViewColumnGetSortIndicator :: TreeViewColumnClass tvc => tvc -> IO Bool\ntreeViewColumnGetSortIndicator tvc = liftM toBool $\n {#call unsafe tree_view_column_get_sort_indicator#} (toTreeViewColumn tvc)\n\n-- @method treeViewColumnSetSortOrder@ Set if a given column is sorted\n-- in ascending or descending order.\n--\n-- * In order for sorting to work, it is necessary to either use automatic\n-- sorting via @ref method treeViewColumnSetSortColumnId@ or to use a\n-- user defined sorting on the elements in a @ref type TreeModel@.\n--\ntreeViewColumnSetSortOrder :: TreeViewColumnClass tvc => \n\t\t\t tvc -> SortType -> IO ()\ntreeViewColumnSetSortOrder tvc sort =\n {#call tree_view_column_set_sort_order#} (toTreeViewColumn tvc) \n ((fromIntegral.fromEnum) sort)\n\n-- @method treeViewColumnGetSortOrder@ Query if a given column is sorted\n-- in ascending or descending order.\n--\ntreeViewColumnGetSortOrder :: TreeViewColumnClass tvc => tvc -> IO SortType\ntreeViewColumnGetSortOrder tvc = liftM (toEnum.fromIntegral) $\n {#call unsafe tree_view_column_get_sort_order#} (toTreeViewColumn tvc)\n\n-- @signal colClicked@ Emitted when the header of this column has been\n-- clicked on.\n--\nonColClicked, afterColClicked :: TreeViewColumnClass tvc => tvc -> IO () -> \n\t\t\t\t\t\t\t IO (ConnectId tvc)\nonColClicked = connect_NONE__NONE \"clicked\" False\nafterColClicked = connect_NONE__NONE \"clicked\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"09f75bcdbf892ca4886a7e1ab8e1809babc22e5e","subject":"fix for gdal < 1.11","message":"fix for gdal < 1.11\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException CantCreateMultipleGeomFields\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n , executeSQL\n\n , createLayer\n , getLayer\n , getLayerByName\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerFeatureDef\n\n , registerAll\n , cleanupAll\n\n , withLockedLayerPtr\n , withLockedLayerPtrs\n , unDataSource\n , unLayer\n , withLockedDataSourcePtr\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM, when, void, forM_, (<=<))\nimport Control.Monad.Catch(throwM, catch, catchJust)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLConv (cplFree)\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) = DataSource (Mutex, DataSourceH)\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\nunDataSource :: DataSource s t -> DataSourceH\nunDataSource (DataSource (_,p)) = p\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nwithLockedDataSourcePtr\n :: DataSource s t -> (DataSourceH -> IO b) -> IO b\nwithLockedDataSourcePtr (DataSource (m,p)) f = withMutex m (f p)\n\n\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s (t::AccessMode) a) = Layer (Mutex, LayerH)\n\n\nunLayer :: Layer s t a -> LayerH\nunLayer (Layer (_,p)) = p\n\nlMutex :: Layer s t a -> Mutex\nlMutex (Layer (m,_)) = m\n\nwithLockedLayerPtr\n :: Layer s t a -> (LayerH -> IO b) -> IO b\nwithLockedLayerPtr (Layer (m,p)) f = withMutex m $ f p\n\nwithLockedLayerPtrs\n :: [Layer s t a] -> ([LayerH] -> IO b) -> IO b\nwithLockedLayerPtrs ls f\n = withMutexes (map lMutex ls) (f (map unLayer ls))\n\ntype ROLayer s = Layer s ReadOnly\ntype RWLayer s = Layer s ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p = do\n ptr <- liftIO $ withCString p $ \\p' ->\n throwIfError \"open\" ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n newDataSourceHandle ptr `catch` (\\NullDataSource ->\n throwM (GDALException CE_Failure OpenFailed \"OGROpen returned a NULL ptr\"))\n\n\nnewDataSourceHandle :: DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle p\n | p==nullDataSourceH = throwBindingException NullDataSource\n | otherwise = do\n registerFinalizer (void ({#call unsafe ReleaseDataSource as ^#} p))\n m <- liftIO newMutex\n return $ DataSource (m,p)\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle <=<\n liftIO $ throwIfError \"create\" $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s a)\ncreateLayer ds FeatureDef{..} approxOk options = liftIO $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList extendedOptions $ \\pOpts ->\n throwIfError \"createLayer\" $ do\n fpL <- {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts >>=\n newLayerHandle ds NullLayer\n withLockedLayerPtr fpL $ \\pL -> do\n V.forM_ fdFields $ \\f -> withFieldDefnH f $ \\pFld ->\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if MULTI_GEOM_FIELDS\n V.forM_ fdGeoms $ \\f -> withGeomFieldDefnH f $ \\pGFld ->\n {#call OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#endif\n else throwBindingException CantCreateMultipleGeomFields\n return fpL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataSource ds\n gType = fromEnumC (gfdType fdGeom)\n extendedOptions\n | gfdName fdGeom \/= \"\" = (\"GEOMETRY_NAME\", gfdName fdGeom):options\n | otherwise = options\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s t a)\ngetLayer layer ds = liftIO $\n newLayerHandle ds (InvalidLayerIndex layer) <=<\n throwIfError \"getLayer\" $ {#call OGR_DS_GetLayer as ^#} dsH lyr\n where\n dsH = unDataSource ds\n lyr = fromIntegral layer\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s t a)\ngetLayerByName layer ds = liftIO $ useAsEncodedCString layer $\n newLayerHandle ds (InvalidLayerName layer) <=<\n throwIfError \"getLayerByName\" .\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> ({#call unsafe OGR_L_GetGeometryColumn as ^#} p >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> ({#call unsafe OGR_L_GetSpatialRef as ^#} p >>=\n maybeNewSpatialRefBorrowedHandle)\n\nnewLayerHandle\n :: DataSource s t -> OGRException -> LayerH -> IO (Layer s t a)\nnewLayerHandle (DataSource (m,_)) exc p\n | p==nullLayerH = throwBindingException exc\n | otherwise = return (Layer (m,p))\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call unsafe OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = withCString \"SQLITE\"\nwithSQLDialect OGRDialect = withCString \"OGRSQL\"\n\nexecuteSQL\n :: SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s a)\nexecuteSQL dialect query mSpatialFilter ds@(DataSource (m,dsP)) = do\n p <- catchJust selectExc execute (throwBindingException . SQLQueryError)\n when (p==nullLayerH) $ throwBindingException NullLayer\n registerFinalizer ({#call unsafe OGR_DS_ReleaseResultSet as ^#} dsP p)\n return (Layer (m, p))\n where\n selectExc GDALException{..} | gdalErrNum==AppDefined = Just gdalErrMsg\n selectExc _ = Nothing\n execute = liftIO $\n throwIfError \"executeSQL\" $\n withLockedDataSourcePtr ds $ \\dsPtr ->\n withMaybeGeometry mSpatialFilter $ \\sFilter ->\n withSQLDialect dialect $ \\sDialect ->\n useAsEncodedCString query $ \\sQuery ->\n {#call OGR_DS_ExecuteSQL as ^#} dsPtr sQuery sFilter sDialect\n\nlayerName :: Layer s t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerFeatureDef :: Layer s t a -> GDAL s FeatureDef\nlayerFeatureDef l = liftIO $ do\n let pL = unLayer l\n gfd <- layerGeomFieldDef pL\n featureDefFromHandle gfd =<< {#call unsafe OGR_L_GetLayerDefn as ^#} pL\n\n\ngetSpatialFilter :: Layer s t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $ withLockedLayerPtr l $ \\lPtr -> do\n p <- {#call unsafe OGR_L_GetSpatialFilter as ^#} lPtr\n if p == nullPtr\n then return Nothing\n else liftM Just (cloneGeometry p)\n\nsetSpatialFilter :: Layer s t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withLockedLayerPtr l $ \\lPtr -> withGeometry g$ \\gPtr ->\n {#call unsafe OGR_L_SetSpatialFilter as ^#} lPtr gPtr\n\ndata LayerCapability\n = RandomRead\n | SequentialWrite\n | RandomWrite\n | FastSpatialFilter\n | FastFeatureCount\n | FastGetExtent\n | CreateField\n | DeleteField\n | ReorderFields\n | AlterFieldDefn\n | Transactions\n | DeleteFeature\n | FastSetNextByIndex\n | StringsAsUTF8\n | IgnoreFields\n | CreateGeomField\n deriving (Eq, Show, Enum, Bounded)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndata DataSourceCapability\n = CreateLayer\n | DeleteLayer\n | CreateGeomFieldAfterCreateLayer\n deriving (Eq, Show, Enum, Bounded)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n\ndata DriverCapability\n = CreateDataSource\n | DeleteDataSource\n deriving (Eq, Show, Enum, Bounded)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"22b3cf904ad72656cbb2fab6a5a043b06846bc36","subject":"free sockaddr_storage after reading candidate addresses","message":"free sockaddr_storage after reading candidate addresses\n","repos":"Philonous\/libnice-hs,Philonous\/libnice-hs","old_file":"source\/Network\/Ice\/NiceCandidate.chs","new_file":"source\/Network\/Ice\/NiceCandidate.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Network.Ice.NiceCandidate where\n\nimport Network.Socket\nimport Network.Socket.Internal (peekSockAddr, withSockAddr)\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Control.Applicative\nimport Control.Monad\nimport Foreign.C\n\n#include \n#include \n\n{#context lib=\"libnice\" prefix=\"nice\" #}\n\n{# enum NiceCandidateType as NiceCandidateType {underscoreToCase}\n deriving (Eq, Show, Read, Bounded) #}\n\n{# enum NiceCandidateTransport {underscoreToCase}\n deriving (Eq, Show, Read, Bounded) #}\n\ntype NiceAddress = SockAddr\ntype TurnServer = Ptr ()\n\ndata NiceCandidate = NiceCandidate\n { candidateType :: NiceCandidateType\n , candidateTransport :: NiceCandidateTransport\n , address :: SockAddr\n , baseAddress :: SockAddr\n , priority :: Integer\n , streamId :: Int\n , componentId :: Int\n , foundation :: String\n , username :: Maybe String\n , password :: Maybe String\n , turn :: TurnServer\n , sockPtr :: Ptr ()\n } deriving Show\n\nenum :: (Monad m, Integral i, Enum e) => m i -> m e\nenum = liftM $ toEnum . fromIntegral\n\nmbPeekCString p = do\n mbstr <- if p == nullPtr\n then return Nothing\n else Just `fmap` peekCString p\n free p\n return mbstr\n\nmbNewCString Nothing = return nullPtr\nmbNewCString (Just x) = newCString x\n\ncandidateAddress p = do\n addrPtr <- {# call get_candidate_addr #} (castPtr p)\n addr <- peekSockAddr $ castPtr addrPtr\n free addrPtr\n return addr\n\ncandidateBaseAddress p = do\n addrPtr <- {# call get_candidate_base_addr #} (castPtr p)\n addr <- peekSockAddr $ castPtr addrPtr\n free addrPtr\n return addr\n\ninstance Storable NiceCandidate where\n sizeOf _ = {# sizeof NiceCandidateType #}\n alignment _ = {# alignof NiceCandidateType #}\n peek p = NiceCandidate\n <$> enum ({# get NiceCandidate->type #} p)\n <*> enum ({# get NiceCandidate->transport #} p)\n <*> candidateAddress p\n <*> candidateBaseAddress p\n <*> (fromIntegral <$> {# get NiceCandidate->priority #} p)\n <*> (fromIntegral <$> {# get NiceCandidate->stream_id #} p)\n <*> (fromIntegral <$> {# get NiceCandidate->component_id #} p)\n <*> (peekCString . castPtr $ p `plusPtr` 76)\n <*> (mbPeekCString =<< {# get NiceCandidate->username #} p)\n <*> (mbPeekCString =<< {# get NiceCandidate->password #} p)\n <*> {# get NiceCandidate->turn #} p\n <*> {# get NiceCandidate->sockptr #} p\n poke p NiceCandidate{..} = do\n {# set NiceCandidate->type #} p . fromIntegral . fromEnum $ candidateType\n {# set NiceCandidate->transport #} p . fromIntegral . fromEnum\n $ candidateTransport\n withSockAddr address $ \\pa _ ->\n {# call set_candidate_addr #} (castPtr p) (castPtr pa)\n withSockAddr baseAddress $ \\pa _ ->\n {# call set_candidate_base_addr #} (castPtr p) (castPtr pa)\n {# set NiceCandidate->priority #} p $ fromIntegral priority\n {# set NiceCandidate->stream_id #} p $ fromIntegral streamId\n {# set NiceCandidate->component_id #} p $ fromIntegral componentId\n withCString foundation $ \\pa ->\n {#call set_foundation #} (castPtr p) (castPtr pa)\n {# set NiceCandidate->username #} p =<< mbNewCString username\n {# set NiceCandidate->password #} p =<< mbNewCString password\n {# set NiceCandidate->turn #} p turn\n {# set NiceCandidate->sockptr #} p sockPtr\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\nmodule Network.Ice.NiceCandidate where\n\nimport Network.Socket\nimport Network.Socket.Internal (peekSockAddr, withSockAddr)\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Control.Applicative\nimport Control.Monad\nimport Foreign.C\n\n#include \n#include \n\n{#context lib=\"libnice\" prefix=\"nice\" #}\n\n{# enum NiceCandidateType as NiceCandidateType {underscoreToCase}\n deriving (Eq, Show, Read, Bounded) #}\n\n{# enum NiceCandidateTransport {underscoreToCase}\n deriving (Eq, Show, Read, Bounded) #}\n\ntype NiceAddress = SockAddr\ntype TurnServer = Ptr ()\n\ndata NiceCandidate = NiceCandidate\n { candidateType :: NiceCandidateType\n , candidateTransport :: NiceCandidateTransport\n , address :: SockAddr\n , baseAddress :: SockAddr\n , priority :: Integer\n , streamId :: Int\n , componentId :: Int\n , foundation :: String\n , username :: Maybe String\n , password :: Maybe String\n , turn :: TurnServer\n , sockPtr :: Ptr ()\n } deriving Show\n\nenum :: (Monad m, Integral i, Enum e) => m i -> m e\nenum = liftM $ toEnum . fromIntegral\n\nmbPeekCString p = do\n mbstr <- if p == nullPtr\n then return Nothing\n else Just `fmap` peekCString p\n free p\n return mbstr\n\nmbNewCString Nothing = return nullPtr\nmbNewCString (Just x) = newCString x\n\ninstance Storable NiceCandidate where\n sizeOf _ = {# sizeof NiceCandidateType #}\n alignment _ = {# alignof NiceCandidateType #}\n peek p = NiceCandidate\n <$> enum ({# get NiceCandidate->type #} p)\n <*> enum ({# get NiceCandidate->transport #} p)\n <*> (peekSockAddr . castPtr\n =<< {# call get_candidate_addr #} (castPtr p))\n <*> (peekSockAddr . castPtr\n =<< {# call get_candidate_base_addr #} (castPtr p))\n <*> (fromIntegral <$> {# get NiceCandidate->priority #} p)\n <*> (fromIntegral <$> {# get NiceCandidate->stream_id #} p)\n <*> (fromIntegral <$> {# get NiceCandidate->component_id #} p)\n <*> (peekCString . castPtr $ p `plusPtr` 76)\n <*> (mbPeekCString =<< {# get NiceCandidate->username #} p)\n <*> (mbPeekCString =<< {# get NiceCandidate->password #} p)\n <*> {# get NiceCandidate->turn #} p\n <*> {# get NiceCandidate->sockptr #} p\n poke p NiceCandidate{..} = do\n {# set NiceCandidate->type #} p . fromIntegral . fromEnum $ candidateType\n {# set NiceCandidate->transport #} p . fromIntegral . fromEnum\n $ candidateTransport\n withSockAddr address $ \\pa _ ->\n {# call set_candidate_addr #} (castPtr p) (castPtr pa)\n withSockAddr baseAddress $ \\pa _ ->\n {# call set_candidate_base_addr #} (castPtr p) (castPtr pa)\n {# set NiceCandidate->priority #} p $ fromIntegral priority\n {# set NiceCandidate->stream_id #} p $ fromIntegral streamId\n {# set NiceCandidate->component_id #} p $ fromIntegral componentId\n withCString foundation $ \\pa ->\n {#call set_foundation #} (castPtr p) (castPtr pa)\n {# set NiceCandidate->username #} p =<< mbNewCString username\n {# set NiceCandidate->password #} p =<< mbNewCString password\n {# set NiceCandidate->turn #} p turn\n {# set NiceCandidate->sockptr #} p sockPtr\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"d548e8270ce2c552af44617912d6b6ccbe0206f5","subject":"texture instances for 64-bit integral types","message":"texture instances for 64-bit integral types\n\nIgnore-this: 1e51f6e49dcad054e2864dac16aad7e7\n\ndarcs-hash:20100618092454-dcabc-2c5c554b7a5139926262aa46657b95628d90608c.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(..), AddressMode(..), FilterMode(..), Format,\n create, destroy,\n getPtr, getAddressMode, getFilterMode,\n setPtr, setAddressMode, setFilterMode, setFormat,\n\n -- Internal\n peekTex\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture a = Texture { useTexture :: {# type CUtexref #}}\n\ninstance Storable (Texture a) 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-- |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-- |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-- |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-- |Texture data formats\n--\n{# enum CUarray_format as TextureFormat\n { }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\nclass Format a where\n tag :: a -> Int\n channels :: a -> Int\n channels _ = 1\n\ninstance Format Word where tag _ = fromEnum UNSIGNED_INT32\ninstance Format Word8 where tag _ = fromEnum UNSIGNED_INT8\ninstance Format Word16 where tag _ = fromEnum UNSIGNED_INT16\ninstance Format Word32 where tag _ = fromEnum UNSIGNED_INT32\ninstance Format Word64 where\n tag _ = fromEnum UNSIGNED_INT32\n channels _ = 2\n\ninstance Format Int where tag _ = fromEnum SIGNED_INT32\ninstance Format Int8 where tag _ = fromEnum SIGNED_INT8\ninstance Format Int16 where tag _ = fromEnum SIGNED_INT16\ninstance Format Int32 where tag _ = fromEnum SIGNED_INT32\ninstance Format Int64 where\n tag _ = fromEnum SIGNED_INT32\n channels _ = 2\n\ninstance Format Float where tag _ = fromEnum FLOAT\ninstance Format Double where\n tag _ = fromEnum SIGNED_INT32\n channels _ = 2\n -- __hiloint2double()\n\n-- FIXME:\n-- * half (16-bit float)\n-- * vector types\n-- * A Int or Word on the GPU is 32-bits, but this may not be the same bitwidth\n-- as Haskell-side computations.\n--\n\n--------------------------------------------------------------------------------\n-- Texture management\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--\ncreate :: Format a => IO (Texture a)\ncreate = do\n tex <- resultIfOk =<< cuTexRefCreate\n setFormat tex\n return tex\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture a' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture a -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture a' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture a -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture a -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture a -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture a' } -> `Status' cToEnum #}\n\n{-\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture a -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture a -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture a -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture a'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture a -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture a'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Format a => Texture a -> IO ()\nsetFormat tex = doSet undefined tex\n where\n doSet :: Format b => b -> Texture b -> IO ()\n doSet fmt _ = nothingIfOk =<< cuTexRefSetFormat tex (tag fmt) (channels fmt)\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO (Texture a)\npeekTex = liftM Texture . peek\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(..), AddressMode(..), FilterMode(..), Format,\n create, destroy,\n getPtr, getAddressMode, getFilterMode,\n setPtr, setAddressMode, setFilterMode, setFormat,\n\n -- Internal\n peekTex\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture a = Texture { useTexture :: {# type CUtexref #}}\n\ninstance Storable (Texture a) 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-- |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-- |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-- |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-- |Texture data formats\n--\n{# enum CUarray_format as TextureFormat\n { }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\nclass Format a where\n tag :: a -> Int\n channels :: a -> Int\n channels _ = 1\n\ninstance Format Word where tag _ = fromEnum UNSIGNED_INT32\ninstance Format Word8 where tag _ = fromEnum UNSIGNED_INT8\ninstance Format Word16 where tag _ = fromEnum UNSIGNED_INT16\ninstance Format Word32 where tag _ = fromEnum UNSIGNED_INT32\n\ninstance Format Int where tag _ = fromEnum SIGNED_INT32\ninstance Format Int8 where tag _ = fromEnum SIGNED_INT8\ninstance Format Int16 where tag _ = fromEnum SIGNED_INT16\ninstance Format Int32 where tag _ = fromEnum SIGNED_INT32\n\ninstance Format Float where tag _ = fromEnum FLOAT\ninstance Format Double where\n tag _ = fromEnum SIGNED_INT32\n channels _ = 2\n -- __hiloint2double()\n\n-- FIXME:\n-- * half (16-bit float)\n-- * vector types\n-- * A Int or Word on the GPU is 32-bits, but this may not be the same bitwidth\n-- as Haskell-side computations.\n--\n\n--------------------------------------------------------------------------------\n-- Texture management\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--\ncreate :: Format a => IO (Texture a)\ncreate = do\n tex <- resultIfOk =<< cuTexRefCreate\n setFormat tex\n return tex\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture a' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture a -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture a' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture a -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture a -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture a -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture a' } -> `Status' cToEnum #}\n\n{-\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture a -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture a -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture a -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture a'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture a -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture a'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Format a => Texture a -> IO ()\nsetFormat tex = doSet undefined tex\n where\n doSet :: Format b => b -> Texture b -> IO ()\n doSet fmt _ = nothingIfOk =<< cuTexRefSetFormat tex (tag fmt) (channels fmt)\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO (Texture a)\npeekTex = liftM Texture . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3fe98bb9a8a257626be5f5c118321ce5e88e4a92","subject":"glade: remove glade\/Glade.chs (not sure why this file is here...)","message":"glade: remove glade\/Glade.chs (not sure why this file is here...)\n\ndarcs-hash:20090114053423-21862-4b938fd1fcc321c96d6d0da26f13f309bc4badc8.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"glade\/Glade.chs","new_file":"glade\/Glade.chs","new_contents":"","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to Libglade -*-haskell-*-\n-- for loading XML widget specifications\n--\n-- Author : Manuel M T Chakravarty\n-- Created: 13 March 2002\n--\n-- Copyright (c) 2002 Manuel M T Chakravarty\n-- Modified 2003 by Duncan Coutts (gtk2hs port)\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-- |\n--\n-- Libglade facilitates loading of XML specifications of whole widget trees\n-- that have been interactively designed with the GUI builder Glade. The\n-- present module exports operations for manipulating 'GladeXML' objects.\n--\n-- @glade_xml_signal_autoconnect()@ is not supported. The C variant is not\n-- suitable for Haskell as @-rdynamic@ leads to huge executable and we\n-- usually don't want to connect staticly named functions, but closures.\n--\n-- * @glade_xml_construct()@ is not bound, as it doesn't seem to be useful\n-- in Haskell. As usual, the @signal_connect_data@ variant for\n-- registering signal handlers isn't bound either. Moreover, the\n-- @connect_full@ functions are not bound.\n--\n-- * This binding does not support Libglade functionality that is\n-- exclusively meant for extending Libglade with new widgets. Like new\n-- widgets, such functionality is currently expected to be implemented in\n-- C.\n--\n\nmodule Glade (\n\n -- * Data types\n --\n GladeXMLClass, GladeXML,\n\n -- * Creation operations\n --\n xmlNew, xmlNewWithRootAndDomain,\n\n -- * Obtaining widget handles\n --\n xmlGetWidget, xmlGetWidgetRaw\n\n) where\n\nimport Monad\t(liftM)\nimport FFI\nimport GType\nimport Object (makeNewObject)\nimport GObject (makeNewGObject)\n{#import Hierarchy#}\n{#import GladeType#}\nimport GList\n\n{#context lib=\"glade\" prefix =\"glade\"#}\n\n\n-- | Create a new XML object (and the corresponding\n-- widgets) from the given XML file; corresponds to\n-- 'xmlNewWithRootAndDomain', but without the ability to specify a root\n-- widget or translation domain.\n--\nxmlNew :: FilePath -> IO (Maybe GladeXML)\nxmlNew file =\n withCString file $ \\strPtr1 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 nullPtr nullPtr\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Create a new GladeXML object (and\n-- the corresponding widgets) from the given XML file with an optional\n-- root widget and translation domain.\n--\n-- * If the second argument is not @Nothing@, the interface will only be built\n-- from the widget whose name is given. This feature is useful if you only\n-- want to build say a toolbar or menu from the XML file, but not the window\n-- it is embedded in. Note also that the XML parse tree is cached to speed\n-- up creating another \\'XML\\' object for the same file.\n--\nxmlNewWithRootAndDomain :: FilePath -> Maybe String -> Maybe String -> IO (Maybe GladeXML)\nxmlNewWithRootAndDomain file rootWidgetName domain =\n withCString file $ \\strPtr1 ->\n withMaybeCString rootWidgetName $ \\strPtr2 ->\n withMaybeCString domain $ \\strPtr3 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 strPtr2 strPtr3\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Get the widget that has the given name in\n-- the interface description. If the named widget cannot be found\n-- or is of the wrong type the result is an error.\n--\n-- * the second parameter should be a dynamic cast function that\n-- returns the type of object that you expect, eg castToButton\n--\n-- * the third parameter is the ID of the widget in the glade xml\n-- file, eg \\\"button1\\\".\n--\nxmlGetWidget :: (WidgetClass widget) => GladeXML -> (GObject -> widget) -> String -> IO widget\nxmlGetWidget xml cast name = do\n maybeWidget <- xmlGetWidgetRaw xml name\n return $ case maybeWidget of\n Just widget -> cast (toGObject widget) --the cast will return an error if the object is of the wrong type\n Nothing -> error $ \"glade.xmlGetWidget: no object named \" ++ show name ++ \" in the glade file\"\n\nxmlGetWidgetRaw :: GladeXML -> String -> IO (Maybe Widget)\nxmlGetWidgetRaw xml name =\n withCString name $ \\strPtr1 -> do\n widgetPtr <- {#call unsafe xml_get_widget#} xml strPtr1\n if widgetPtr==nullPtr then return Nothing\n else liftM Just $ makeNewObject mkWidget (return widgetPtr)\n\n-- Auxilliary routines\n-- -------------------\n\n-- Marshall an optional string\n--\nwithMaybeCString :: Maybe String -> (Ptr CChar -> IO a) -> IO a\nwithMaybeCString = maybeWith withCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"16968e68cd30ee4a7aef705e80f008d13f4d1821","subject":"Add property functions for Char type","message":"Add property functions for Char type\n","repos":"gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/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 objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\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\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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 writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d077d3ffea458be0385529e4c8a006f0ff95257b","subject":"Added Status, and storable instance for it. Added commRank. Improved types of send and recv by better marshalling.","message":"Added Status, and storable instance for it. Added commRank. Improved types of send and recv by better marshalling.\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Bindings\/MPI\/Internal.chs","new_file":"src\/Bindings\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n (Comm, Datatype, Status (..), init, finalize, send, recv, commWorld, commRank, int) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\ntype Datatype = {# type MPI_Datatype #}\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\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_int\" int :: Datatype\n\n{# fun unsafe init_wrapper as init {} -> `Int' #}\n\n{# fun unsafe Finalize as ^ {} -> `Int' #}\n\nwithStorable :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithStorable x f = alloca (\\ptr -> poke ptr x >> f ptr)\n\nwithStorableCast :: Storable a => a -> (Ptr c -> IO b) -> IO b\nwithStorableCast x f = withStorable x (f . castPtr)\n\n-- int MPI_Comm_rank(MPI_Comm comm, int *rank)\n{# fun unsafe Comm_rank as ^ { id `Comm', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)\n{# fun unsafe Send as ^ `Storable a' => { withStorableCast* `a', `Int', id `Datatype', `Int', `Int', id `Comm' } -> `Int' #}\n\n-- int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)\n-- recv = {# call unsafe MPI_Recv as ^ #}\n{# fun unsafe Recv as ^ `Storable a' => { withStorableCast* `a', `Int', id `Datatype', `Int', `Int', id `Comm', alloca- `Status' peek* } -> `Int' #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n#include \"constants.h\"\n\nmodule Bindings.MPI.Internal (init, finalize, send, recv, Comm, Datatype, commWorld, int) where\n\nimport Prelude hiding (init)\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\ntype Comm = {# type MPI_Comm #}\ntype Datatype = {# type MPI_Datatype #}\n\nforeign import ccall \"mpi_comm_world\" commWorld :: Comm\nforeign import ccall \"mpi_int\" int :: Datatype\n\ninit = {# call unsafe init_wrapper as ^ #}\n\n-- int MPI_Finalize(void)\nfinalize = {# call unsafe MPI_Finalize as ^ #}\n\n-- int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)\n-- send = {# call unsafe MPI_Send as ^ #}\n{# fun unsafe Send as ^ { id `Ptr ()', `Int', id `Datatype', `Int', `Int', id `Comm' } -> `Int' #}\n\n-- int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status)\nrecv = {# call unsafe MPI_Recv as ^ #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"053e9d89e7ba935d8dee6e8976944914b01dbb5d","subject":"Fix an incorrect pattern in windowSetIcon.","message":"Fix an incorrect pattern in windowSetIcon.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Window.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow, gTypeWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\n{#import Graphics.UI.Gtk.Gdk.Keys#} (KeyVal)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this 'Window'. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO (Maybe Widget)\nwindowGetDefaultWidget self = \n maybeNull (makeNewObject mkWidget) $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- Enter in a dialog (for example). This function sets or unsets the default\n-- widget for a Window about. When setting (rather than unsetting) the\n-- default widget it's generally easier to call widgetGrabDefault on the\n-- widget. Before making a widget the default widget, you must set the\n-- 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n#endif\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ returns @(left, top, right, bottom)@. @left@ is the\n -- width of the frame at the left, @top@ is the height of the frame at the top, @right@\n -- is the width of the frame at the right, @bottom@ is the height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Maybe Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self Nothing =\n {# call gtk_window_set_icon #}\n (toWindow self)\n (Pixbuf nullForeignPtr)\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO (Maybe Pixbuf) -- ^ returns icon for window, or @Nothing@ if none was set\nwindowGetIcon self =\n maybeNull (makeNewGObject mkPixbuf) $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self (Maybe Pixbuf)\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame-event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys-changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set-focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set-focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set-focus\" True\n\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Window\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon, Andy Stewart\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2005 Manuel M. T. Chakravarty, 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-- Toplevel which can contain other widgets\n--\nmodule Graphics.UI.Gtk.Windows.Window (\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----Window\n-- | +----'Dialog'\n-- | +----'Plug'\n-- @\n\n-- * Types\n Window,\n WindowClass,\n castToWindow, gTypeWindow,\n toWindow,\n WindowType(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n\n-- * Constructors\n windowNew,\n windowNewPopup,\n\n-- * Methods\n windowActivateFocus,\n windowActivateDefault,\n windowSetDefaultSize,\n windowGetDefaultSize,\n windowSetPosition,\n WindowPosition(..),\n#if GTK_CHECK_VERSION(2,4,0)\n windowIsActive,\n windowHasToplevelFocus,\n#endif\n windowListToplevels,\n windowSetDefault,\n#if GTK_CHECK_VERSION(2,14,0)\n windowGetDefaultWidget,\n#endif\n windowAddMnemonic,\n windowRemoveMnemonic,\n windowMnemonicActivate,\n windowActivateKey,\n windowPropagateKeyEvent,\n windowPresent,\n windowDeiconify,\n windowIconify,\n windowMaximize,\n windowUnmaximize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowFullscreen,\n windowUnfullscreen,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetKeepAbove,\n windowSetKeepBelow,\n#endif\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetStartupId,\n#endif\n windowGetFrame,\n windowSetFrameDimensions,\n windowGetFrameDimensions,\n windowStick,\n windowUnstick,\n windowAddAccelGroup,\n windowRemoveAccelGroup,\n windowSetDefaultIconList,\n windowGetDefaultIconList,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetDefaultIcon,\n#endif\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetDefaultIconFromFile,\n windowSetDefaultIconName,\n#if GTK_CHECK_VERSION(2,16,0)\n windowGetDefaultIconName,\n#endif\n#endif\n windowSetGravity,\n windowGetGravity,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetScreen,\n windowGetScreen,\n#endif\n windowBeginResizeDrag,\n windowBeginMoveDrag,\n windowSetTypeHint,\n windowGetTypeHint,\n windowGetIcon,\n windowGetPosition,\n windowGetSize,\n windowMove,\n windowParseGeometry,\n windowReshowWithInitialSize,\n windowResize,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetIconFromFile,\n windowSetAutoStartupNotification,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowPresentWithTime,\n#endif\n windowSetGeometryHints,\n#if GTK_CHECK_VERSION(2,10,0)\n windowGetGroup,\n#endif\n\n-- * Attributes\n windowTitle,\n windowType,\n windowAllowShrink,\n windowAllowGrow,\n windowResizable,\n windowModal,\n#if GTK_CHECK_VERSION(2,12,0)\n windowOpacity,\n#endif\n windowRole,\n#if GTK_CHECK_VERSION(2,12,0)\n windowStartupId,\n#endif\n windowWindowPosition,\n windowDefaultWidth,\n windowDefaultHeight,\n windowDeletable,\n windowDestroyWithParent,\n windowIcon,\n windowIconName,\n#if GTK_CHECK_VERSION(2,2,0)\n windowScreen,\n#endif\n windowTypeHint,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSkipTaskbarHint,\n windowSkipPagerHint,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowUrgencyHint,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowAcceptFocus,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n windowFocusOnMap,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n windowDecorated,\n windowGravity,\n#endif\n windowToplevelFocus,\n windowTransientFor,\n windowFocus,\n windowHasFrame,\n windowIconList,\n windowMnemonicModifier,\n\n-- * Signals\n frameEvent,\n keysChanged,\n setFocus,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n windowSetTitle,\n windowGetTitle,\n windowSetResizable,\n windowGetResizable,\n windowSetModal,\n windowGetModal,\n windowSetPolicy,\n windowSetTransientFor,\n windowGetTransientFor,\n windowSetDestroyWithParent,\n windowGetDestroyWithParent,\n windowGetFocus,\n windowSetFocus,\n windowSetMnemonicModifier,\n windowGetMnemonicModifier,\n#if GTK_CHECK_VERSION(2,2,0)\n windowSetSkipTaskbarHint,\n windowGetSkipTaskbarHint,\n windowSetSkipPagerHint,\n windowGetSkipPagerHint,\n#if GTK_CHECK_VERSION(2,4,0)\n windowSetAcceptFocus,\n windowGetAcceptFocus,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetFocusOnMap,\n windowGetFocusOnMap,\n#endif\n#endif\n#endif\n windowSetDecorated,\n windowGetDecorated,\n#if GTK_CHECK_VERSION(2,10,0)\n windowSetDeletable,\n windowGetDeletable,\n#endif\n windowSetHasFrame,\n windowGetHasFrame,\n windowSetRole,\n windowGetRole,\n windowSetIcon,\n windowSetIconList,\n windowGetIconList,\n#if GTK_CHECK_VERSION(2,6,0)\n windowSetIconName,\n windowGetIconName,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n windowSetUrgencyHint,\n windowGetUrgencyHint,\n#if GTK_CHECK_VERSION(2,12,0)\n windowSetOpacity,\n windowGetOpacity,\n#endif\n#endif\n onSetFocus,\n afterSetFocus\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList (fromGList, withGList)\nimport System.Glib.GObject\t\t(makeNewGObject)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport Graphics.UI.Gtk.General.Enums\t(WindowType(..), WindowPosition(..))\nimport Graphics.UI.Gtk.General.Structs (windowGetFrame)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Gdk.Enums#} (Modifier(..))\n{#import Graphics.UI.Gtk.Gdk.Keys#} (KeyVal)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM, EAny, EKey, MouseButton, TimeStamp)\nimport Control.Monad.Reader ( runReaderT, ask )\nimport Control.Monad.Trans ( liftIO )\nimport Graphics.UI.Gtk.Gdk.Enums\t(WindowEdge(..), WindowTypeHint(..),\n\t\t\t\t\tGravity(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Create a new top level window.\n--\nwindowNew :: IO Window\nwindowNew =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowToplevel)\n\n-- | Create a popup window.\n--\nwindowNewPopup :: IO Window\nwindowNewPopup =\n makeNewObject mkWindow $\n liftM (castPtr :: Ptr Widget -> Ptr Window) $\n {# call window_new #}\n ((fromIntegral . fromEnum) WindowPopup)\n\n--------------------\n-- Methods\n\n-- | Sets the title of the 'Window'. The title of a window will be displayed\n-- in its title bar; on the X Window System, the title bar is rendered by the\n-- window manager, so exactly how the title appears to users may vary according\n-- to a user's exact configuration. The title should help a user distinguish\n-- this window from other windows they may have open. A good title might\n-- include the application name and current document filename, for example.\n--\nwindowSetTitle :: WindowClass self => self -> String -> IO ()\nwindowSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call gtk_window_set_title #}\n (toWindow self)\n titlePtr\n\n-- | Retrieves the title of the window. See 'windowSetTitle'.\n--\nwindowGetTitle :: WindowClass self => self -> IO String\nwindowGetTitle self =\n {# call gtk_window_get_title #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets whether the user can resize a window. Windows are user resizable by\n-- default.\n--\nwindowSetResizable :: WindowClass self => self -> Bool -> IO ()\nwindowSetResizable self resizable =\n {# call window_set_resizable #}\n (toWindow self)\n (fromBool resizable)\n\n-- | Gets the value set by 'windowSetResizable'.\n--\nwindowGetResizable :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the user can resize the window\nwindowGetResizable self =\n liftM toBool $\n {# call unsafe window_get_resizable #}\n (toWindow self)\n\n-- | Activates the current focused widget within the window.\n--\nwindowActivateFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateFocus self =\n liftM toBool $\n {# call window_activate_focus #}\n (toWindow self)\n\n-- | Activates the default widget for the window, unless the current focused\n-- widget has been configured to receive the default action (see\n-- 'ReceivesDefault' in 'WidgetFlags'), in which case the focused widget is\n-- activated.\n--\nwindowActivateDefault :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if a widget got activated.\nwindowActivateDefault self =\n liftM toBool $\n {# call window_activate_default #}\n (toWindow self)\n\n#ifndef DISABLE_DEPRECATED\n{-# DEPRECATED windowSetPolicy \"Use windowSetResizable instead.\" #-}\n-- | Sets the window resizing policy.\n--\n-- * Warning: this function is deprecated and should not be used in\n-- newly-written code. Use 'windowSetResizable' instead.\n--\nwindowSetPolicy :: WindowClass self => self -> Bool -> Bool -> Bool -> IO ()\nwindowSetPolicy self allowShrink allowGrow autoShrink =\n {# call window_set_policy #}\n (toWindow self)\n (fromBool allowShrink)\n (fromBool allowGrow)\n (fromBool autoShrink)\n#endif\n\n-- | Sets a window modal or non-modal. Modal windows prevent interaction with\n-- other windows in the same application. To keep modal dialogs on top of main\n-- application windows, use 'windowSetTransientFor' to make the dialog\n-- transient for the parent; most window managers will then disallow lowering\n-- the dialog below the parent.\n--\nwindowSetModal :: WindowClass self => self\n -> Bool -- ^ @modal@ - whether the window is modal\n -> IO ()\nwindowSetModal self modal =\n {# call window_set_modal #}\n (toWindow self)\n (fromBool modal)\n\n-- | Returns whether the window is modal. See 'windowSetModal'.\n--\nwindowGetModal :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window is set to be modal and\n -- establishes a grab when shown\nwindowGetModal self =\n liftM toBool $\n {# call gtk_window_get_modal #}\n (toWindow self)\n\n-- | Sets the default size of a window. If the window's \\\"natural\\\" size (its\n-- size request) is larger than the default, the default will be ignored. More\n-- generally, if the default size does not obey the geometry hints for the\n-- window ('windowSetGeometryHints' can be used to set these explicitly), the\n-- default size will be clamped to the nearest permitted size.\n--\n-- Unlike 'widgetSetSizeRequest', which sets a size request for a widget and\n-- thus would keep users from shrinking the window, this function only sets the\n-- initial size, just as if the user had resized the window themselves. Users\n-- can still shrink the window again as they normally would. Setting a default\n-- size of -1 means to use the \\\"natural\\\" default size (the size request of\n-- the window).\n--\n-- For more control over a window's initial size and how resizing works,\n-- investigate 'windowSetGeometryHints'.\n--\n-- For some uses, 'windowResize' is a more appropriate function.\n-- 'windowResize' changes the current size of the window, rather than the size\n-- to be used on initial display. 'windowResize' always affects the window\n-- itself, not the geometry widget.\n--\n-- The default size of a window only affects the first time a window is\n-- shown; if a window is hidden and re-shown, it will remember the size it had\n-- prior to hiding, rather than using the default size.\n--\n-- Windows can't actually be 0x0 in size, they must be at least 1x1, but\n-- passing 0 for @width@ and @height@ is OK, resulting in a 1x1 default size.\n--\nwindowSetDefaultSize :: WindowClass self => self\n -> Int -- ^ @height@ - height in pixels, or -1 to unset the default height\n -> Int -- ^ @width@ - width in pixels, or -1 to unset the default width\n -> IO ()\nwindowSetDefaultSize self height width =\n {# call window_set_default_size #}\n (toWindow self)\n (fromIntegral height)\n (fromIntegral width)\n\n-- | Adds a mnemonic to this window.\n--\nwindowAddMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic\n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowAddMnemonic self keyval target =\n {# call window_add_mnemonic #}\n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Removes a mnemonic from this window.\n--\nwindowRemoveMnemonic :: (WindowClass self, WidgetClass widget) => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> widget -- ^ @target@ - the widget that gets activated by the mnemonic \n -> IO ()\nwindowRemoveMnemonic self keyval target =\n {# call window_remove_mnemonic #} \n (toWindow self)\n (fromIntegral keyval)\n (toWidget target)\n\n-- | Activates the targets associated with the mnemonic.\nwindowMnemonicActivate :: WindowClass self => self\n -> KeyVal -- ^ @keyval@ - the mnemonic \n -> [Modifier] -- ^ @modifier@ - the modifiers \n -> IO Bool -- ^ return @True@ if the activation is done. \nwindowMnemonicActivate self keyval modifier = liftM toBool $ \n {# call window_mnemonic_activate #}\n (toWindow self)\n (fromIntegral keyval)\n (fromIntegral (fromFlags modifier))\n\n-- | Sets the mnemonic modifier for this window.\nwindowSetMnemonicModifier :: WindowClass self => self\n -> [Modifier] -- ^ @modifier@ - the modifier mask used to activate mnemonics on this window. \n -> IO ()\nwindowSetMnemonicModifier self modifier =\n {# call window_set_mnemonic_modifier #}\n (toWindow self)\n (fromIntegral (fromFlags modifier))\n\n-- | Returns the mnemonic modifier for this window. See 'windowSetMnemonicModifier'.\nwindowGetMnemonicModifier :: WindowClass self => self\n -> IO [Modifier] -- ^ return the modifier mask used to activate mnemonics on this window. \nwindowGetMnemonicModifier self = liftM (toFlags . fromIntegral) $\n {# call window_get_mnemonic_modifier #} \n (toWindow self)\n\n-- | Activates mnemonics and accelerators for this 'Window'. \n-- This is normally called by the default 'keyPressEvent' handler for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n-- \nwindowActivateKey :: WindowClass self => self -> EventM EKey Bool\n -- ^ return @True@ if a mnemonic or accelerator was found and activated. \nwindowActivateKey self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_activate_key #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Propagate a key press or release event to the focus widget and up the focus container chain until a widget handles event. \n-- This is normally called by the default 'keyPressEvent' and 'keyReleaseEvent' handlers for toplevel windows, \n-- however in some cases it may be useful to call this directly when overriding the standard key handling for a toplevel window.\n--\nwindowPropagateKeyEvent :: WindowClass self => self\n -> EventM EKey Bool\n -- ^ return @True@ if a widget in the focus chain handled the event. \nwindowPropagateKeyEvent self = do\n ptr <- ask\n liftIO $ liftM toBool $\n {# call window_propagate_key_event #}\n (toWindow self)\n (castPtr ptr)\n\n-- | Gets the default size of the window. A value of -1 for the width or\n-- height indicates that a default size has not been explicitly set for that\n-- dimension, so the \\\"natural\\\" size of the window will be used.\n--\nwindowGetDefaultSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@ - the default width and height\nwindowGetDefaultSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_default_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | Sets a position constraint for this window. If the old or new constraint\n-- is 'WinPosCenterAlways', this will also cause the window to be repositioned\n-- to satisfy the new constraint.\n--\nwindowSetPosition :: WindowClass self => self -> WindowPosition -> IO ()\nwindowSetPosition self position =\n {# call window_set_position #}\n (toWindow self)\n ((fromIntegral . fromEnum) position)\n\n-- | Dialog windows should be set transient for the main application window\n-- they were spawned from. This allows window managers to e.g. keep the dialog\n-- on top of the main window, or center the dialog over the main window.\n-- 'dialogNewWithButtons' and other convenience functions in Gtk+ will\n-- sometimes call 'windowSetTransientFor' on your behalf.\n--\n-- On Windows, this function will and put the child window on top of the\n-- parent, much as the window manager would have done on X.\n--\n-- Note that if you want to show a window @self@ on top of a full-screen window @parent@, you need to\n-- turn the @self@ window into a dialog (using 'windowSetTypeHint' with 'WindowTypeHintDialog'). \n-- Otherwise the @parent@ window will always cover the @self@ window.\n--\nwindowSetTransientFor :: (WindowClass self, WindowClass parent) => self\n -> parent -- ^ @parent@ - parent window\n -> IO ()\nwindowSetTransientFor self parent =\n {# call window_set_transient_for #}\n (toWindow self)\n (toWindow parent)\n\n-- | Fetches the transient parent for this window. See\n-- 'windowSetTransientFor'.\n--\nwindowGetTransientFor :: WindowClass self => self\n -> IO (Maybe Window) -- ^ returns the transient parent for this window, or\n -- @Nothing@ if no transient parent has been set.\nwindowGetTransientFor self =\n maybeNull (makeNewObject mkWindow) $\n {# call gtk_window_get_transient_for #}\n (toWindow self)\n\n-- | If this setting is @True@, then destroying the transient parent of the\n-- window will also destroy the window itself. This is useful for dialogs that\n-- shouldn't persist beyond the lifetime of the main window they\\'re associated\n-- with, for example.\n--\nwindowSetDestroyWithParent :: WindowClass self => self -> Bool -> IO ()\nwindowSetDestroyWithParent self setting =\n {# call window_set_destroy_with_parent #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window will be destroyed with its transient parent.\n-- See 'windowSetDestroyWithParent'.\n--\nwindowGetDestroyWithParent :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window will be destroyed with its\n -- transient parent.\nwindowGetDestroyWithParent self =\n liftM toBool $\n {# call gtk_window_get_destroy_with_parent #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Returns whether the window is part of the current active toplevel. (That\n-- is, the toplevel window receiving keystrokes.) The return value is @True@ if\n-- the window is active toplevel itself, but also if it is, say, a 'Plug'\n-- embedded in the active toplevel. You might use this function if you wanted\n-- to draw a widget differently in an active window from a widget in an\n-- inactive window. See 'windowHasToplevelFocus'\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowIsActive :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window part of the current active\n -- window.\nwindowIsActive self =\n liftM toBool $\n {# call gtk_window_is_active #}\n (toWindow self)\n\n-- | Returns whether the input focus is within this 'Window'. For real\n-- toplevel windows, this is identical to 'windowIsActive', but for embedded\n-- windows, like 'Plug', the results will differ.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowHasToplevelFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the the input focus is within this 'Window'\nwindowHasToplevelFocus self =\n liftM toBool $\n {# call gtk_window_has_toplevel_focus #}\n (toWindow self)\n#endif\n\n-- | Returns a list of all existing toplevel windows.\n--\nwindowListToplevels :: IO [Window]\nwindowListToplevels = do\n glistPtr <- {#call unsafe gtk_window_list_toplevels#}\n winPtrs <- fromGList glistPtr\n mapM (\\ptr -> makeNewGObject mkWindow (return ptr)) winPtrs\n\n-- | Retrieves the current focused widget within the window.\n-- | Note that this is the widget that would have the focus if the toplevel\n-- | window focused; if the toplevel window is not focused then\n-- | 'widgetHasFocus' will not be True for the widget.\n--\nwindowGetFocus :: WindowClass self => self -> IO (Maybe Widget)\nwindowGetFocus self =\n maybeNull (makeNewObject mkWidget) $\n {# call unsafe gtk_window_get_focus #}\n (toWindow self)\n\n-- | If focus is not the current focus widget, and is focusable, sets it as\n-- | the focus widget for the window. If focus is Nothing, unsets the focus\n-- | widget for this window. To set the focus to a particular widget in the\n-- | toplevel, it is usually more convenient to use 'widgetGrabFocus' instead\n-- | of this function.\n--\nwindowSetFocus :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetFocus self focus =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget focus)\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Returns the default widget for window. See 'windowSetDefault' for more details.\n-- \n-- * Available since Gtk+ version 2.14\n--\nwindowGetDefaultWidget :: WindowClass self => self\n -> IO (Maybe Widget)\nwindowGetDefaultWidget self = \n maybeNull (makeNewObject mkWidget) $\n {# call window_get_default_widget #}\n (toWindow self)\n#endif\n\n-- | The default widget is the widget that's activated when the user presses\n-- Enter in a dialog (for example). This function sets or unsets the default\n-- widget for a Window about. When setting (rather than unsetting) the\n-- default widget it's generally easier to call widgetGrabDefault on the\n-- widget. Before making a widget the default widget, you must set the\n-- 'widgetCanDefault' flag on the widget.\n--\nwindowSetDefault :: (WindowClass self, WidgetClass widget) => self\n -> Maybe widget\n -> IO ()\nwindowSetDefault self defaultWidget =\n {# call unsafe gtk_window_set_focus #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget defaultWidget)\n\n-- | Presents a window to the user. This may mean raising the window in the\n-- stacking order, deiconifying it, moving it to the current desktop, and\\\/or\n-- giving it the keyboard focus, possibly dependent on the user's platform,\n-- window manager, and preferences.\n--\n-- If @window@ is hidden, this function calls 'widgetShow' as well.\n--\n-- This function should be used when the user tries to open a window that's\n-- already open. Say for example the preferences dialog is currently open, and\n-- the user chooses Preferences from the menu a second time; use\n-- 'windowPresent' to move the already-open dialog where the user can see it.\n--\n-- If you are calling this function in response to a user interaction, it is\n-- preferable to use 'windowPresentWithTime'.\n--\nwindowPresent :: WindowClass self => self -> IO ()\nwindowPresent self =\n {# call gtk_window_present #}\n (toWindow self)\n\n-- | Asks to deiconify (i.e. unminimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely deiconified afterward, because\n-- other entities (e.g. the user or window manager) could iconify it again\n-- before your code which assumes deiconification gets to run.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowDeiconify :: WindowClass self => self -> IO ()\nwindowDeiconify self =\n {# call window_deiconify #}\n (toWindow self)\n\n-- | Asks to iconify (i.e. minimize) the specified @window@. Note that you\n-- shouldn't assume the window is definitely iconified afterward, because other\n-- entities (e.g. the user or window manager) could deiconify it again, or\n-- there may not be a window manager in which case iconification isn't\n-- possible, etc. But normally the window will end up iconified. Just don't\n-- write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be iconified before it ever appears onscreen.\n--\n-- You can track iconification via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowIconify :: WindowClass self => self -> IO ()\nwindowIconify self =\n {# call window_iconify #}\n (toWindow self)\n\n-- | Asks to maximize the window, so that it becomes full-screen. Note that you\n-- shouldn't assume the window is definitely maximized afterward, because other\n-- entities (e.g. the user or window manager) could unmaximize it again, and\n-- not all window managers support maximization. But normally the window will\n-- end up maximized. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be maximized when it appears onscreen initially.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowMaximize :: WindowClass self => self -> IO ()\nwindowMaximize self =\n {# call window_maximize #}\n (toWindow self)\n\n-- | Asks to unmaximize the window. Note that you shouldn't assume the window is\n-- definitely unmaximized afterward, because other entities (e.g. the user or\n-- window manager) could maximize it again, and not all window managers honor\n-- requests to unmaximize. But normally the window will end up unmaximized.\n-- Just don't write code that crashes if not.\n--\n-- You can track maximization via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnmaximize :: WindowClass self => self -> IO ()\nwindowUnmaximize self =\n {# call window_unmaximize #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Asks to place @window@ in the fullscreen state. Note that you shouldn't\n-- assume the window is definitely full screen afterward, because other\n-- entities (e.g. the user or window manager) could unfullscreen it again, and\n-- not all window managers honor requests to fullscreen windows. But normally\n-- the window will end up fullscreen. Just don't write code that crashes if\n-- not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowFullscreen :: WindowClass self => self -> IO ()\nwindowFullscreen self =\n {# call gtk_window_fullscreen #}\n (toWindow self)\n\n-- | Asks to toggle off the fullscreen state for @window@. Note that you\n-- shouldn't assume the window is definitely not full screen afterward, because\n-- other entities (e.g. the user or window manager) could fullscreen it again,\n-- and not all window managers honor requests to unfullscreen windows. But\n-- normally the window will end up restored to its normal state. Just don't\n-- write code that crashes if not.\n--\n-- You can track the fullscreen state via the 'windowStateEvent' signal\n-- on 'Widget'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowUnfullscreen :: WindowClass self => self -> IO ()\nwindowUnfullscreen self =\n {# call gtk_window_unfullscreen #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Asks to keep @window@ above, so that it stays on top. Note that you\n-- shouldn't assume the window is definitely above afterward, because other\n-- entities (e.g. the user or window manager) could not keep it above, and not\n-- all window managers support keeping windows above. But normally the window\n-- will end kept above. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept above when it appears onscreen initially.\n--\n-- You can track the above state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepAbove :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ above other windows\n -> IO ()\nwindowSetKeepAbove self setting =\n {# call gtk_window_set_keep_above #}\n (toWindow self)\n (fromBool setting)\n\n-- | Asks to keep @window@ below, so that it stays in bottom. Note that you\n-- shouldn't assume the window is definitely below afterward, because other\n-- entities (e.g. the user or window manager) could not keep it below, and not\n-- all window managers support putting windows below. But normally the window\n-- will be kept below. Just don't write code that crashes if not.\n--\n-- It's permitted to call this function before showing a window, in which\n-- case the window will be kept below when it appears onscreen initially.\n--\n-- You can track the below state via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\n-- Note that, according to the Extended Window Manager Hints specification,\n-- the above state is mainly meant for user preferences and should not be used\n-- by applications e.g. for drawing attention to their dialogs.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetKeepBelow :: WindowClass self => self\n -> Bool -- ^ @setting@ - whether to keep @window@ below other windows\n -> IO ()\nwindowSetKeepBelow self setting =\n {# call gtk_window_set_keep_below #}\n (toWindow self)\n (fromBool setting)\n#endif\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the task bar. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipTaskbarHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- task bar\n -> IO ()\nwindowSetSkipTaskbarHint self setting =\n {# call gtk_window_set_skip_taskbar_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipTaskbarHint'\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipTaskbarHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in taskbar\nwindowGetSkipTaskbarHint self =\n liftM toBool $\n {# call gtk_window_get_skip_taskbar_hint #}\n (toWindow self)\n\n-- | Windows may set a hint asking the desktop environment not to display the\n-- window in the pager. This function sets this hint. (A \\\"pager\\\" is any\n-- desktop navigation tool such as a workspace switcher that displays a\n-- thumbnail representation of the windows on the screen.)\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetSkipPagerHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to keep this window from appearing in the\n -- pager\n -> IO ()\nwindowSetSkipPagerHint self setting =\n {# call gtk_window_set_skip_pager_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetSkipPagerHint'.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetSkipPagerHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window shouldn't be in pager\nwindowGetSkipPagerHint self =\n liftM toBool $\n {# call gtk_window_get_skip_pager_hint #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetAcceptFocus :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus\n -> IO ()\nwindowSetAcceptFocus self setting =\n {# call gtk_window_set_accept_focus #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetAcceptFocus'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowGetAcceptFocus :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus\nwindowGetAcceptFocus self =\n liftM toBool $\n {# call gtk_window_get_accept_focus #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Windows may set a hint asking the desktop environment not to receive the\n-- input focus when the window is mapped. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetFocusOnMap :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to let this window receive input focus on\n -- map\n -> IO ()\nwindowSetFocusOnMap self setting =\n {# call gtk_window_set_focus_on_map #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetFocusOnMap'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetFocusOnMap :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window should receive the input focus when\n -- mapped.\nwindowGetFocusOnMap self =\n liftM toBool $\n {# call gtk_window_get_focus_on_map #}\n (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Startup notification identifiers are used by desktop environment to track application startup, \n-- to provide user feedback and other features. This function changes the corresponding property on the underlying GdkWindow. \n-- Normally, startup identifier is managed automatically and you should only use this function in special cases like transferring focus from other processes. You should use this function before calling 'windowPresent' or any equivalent function generating a window map event.\n--\n-- This function is only useful on X11, not with other GTK+ targets.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowSetStartupId :: WindowClass self => self\n -> String\n -> IO ()\nwindowSetStartupId self startupId =\n withUTFString startupId $ \\idPtr ->\n {# call window_set_startup_id #}\n (toWindow self)\n idPtr\n#endif\n\n-- | By default, windows are decorated with a title bar, resize controls, etc.\n-- Some window managers allow Gtk+ to disable these decorations, creating a\n-- borderless window. If you set the decorated property to @False@ using this\n-- function, Gtk+ will do its best to convince the window manager not to\n-- decorate the window. Depending on the system, this function may not have any\n-- effect when called on a window that is already visible, so you should call\n-- it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager\n-- policy involved.\n--\nwindowSetDecorated :: WindowClass self => self -> Bool -> IO ()\nwindowSetDecorated self setting =\n {# call window_set_decorated #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have decorations such as a\n-- title bar via 'windowSetDecorated'.\n--\nwindowGetDecorated :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if the window has been set to have decorations\nwindowGetDecorated self =\n liftM toBool $\n {# call gtk_window_get_decorated #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | By default, windows have a close button in the window frame. \n-- Some window managers allow GTK+ to disable this button. \n-- If you set the deletable property to @False@ using this function, GTK+ will do its best to convince the window manager not to show a close button. \n-- Depending on the system, this function may not have any effect when called on a window that is already visible, \n-- so you should call it before calling 'windowShow'.\n--\n-- On Windows, this function always works, since there's no window manager policy involved.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowSetDeletable :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to decorate the window as deletable \n -> IO ()\nwindowSetDeletable self setting =\n {# call window_set_deletable #}\n (toWindow self)\n (fromBool setting)\n\n-- | Returns whether the window has been set to have a close button via 'windowSetDeletable'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowGetDeletable :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if the window has been set to have a close button \nwindowGetDeletable self = liftM toBool $ \n {# call window_get_deletable #}\n (toWindow self)\n#endif\n-- | (Note: this is a special-purpose function intended for the framebuffer\n-- port; see 'windowSetHasFrame'. It will have no effect on the window border\n-- drawn by the window manager, which is the normal case when using the X\n-- Window system.)\n--\n-- For windows with frames (see 'windowSetHasFrame') this function can be\n-- used to change the size of the frame border.\n--\nwindowSetFrameDimensions :: WindowClass self => self\n -> Int -- ^ @left@ - The width of the left border\n -> Int -- ^ @top@ - The height of the top border\n -> Int -- ^ @right@ - The width of the right border\n -> Int -- ^ @bottom@ - The height of the bottom border\n -> IO ()\nwindowSetFrameDimensions self left top right bottom =\n {# call window_set_frame_dimensions #}\n (toWindow self)\n (fromIntegral left)\n (fromIntegral top)\n (fromIntegral right)\n (fromIntegral bottom)\n\n-- | Retrieves the dimensions of the frame window for this toplevel. See \n-- 'windowSetHasFrame', 'windowSetFrameDimensions'.\n--\n-- (Note: this is a special-purpose function intended for the framebuffer port;\n-- see 'windowSetHasFrame'. \n-- It will not return the size of the window border drawn by the window manager, \n-- which is the normal case when using a windowing system. \n-- See 'drawWindowGetFrameExtents' to get the standard window border extents.)\n--\n--\n--\nwindowGetFrameDimensions :: WindowClass self => self\n -> IO (Int, Int, Int, Int)\n -- ^ returns @(left, top, right, bottom)@. @left@ is the\n -- width of the frame at the left, @top@ is the height of the frame at the top, @right@\n -- is the width of the frame at the right, @bottom@ is the height of the frame at the bottom.\nwindowGetFrameDimensions self = \n alloca $ \\lPtr -> alloca $ \\tPtr -> alloca $ \\rPtr -> alloca $ \\bPtr -> do\n {# call window_get_frame_dimensions #} (toWindow self) lPtr tPtr rPtr bPtr\n lv <- peek lPtr\n tv <- peek tPtr\n rv <- peek rPtr\n bv <- peek bPtr\n return (fromIntegral lv, fromIntegral tv, fromIntegral rv, fromIntegral bv)\n\n-- | If this function is called on a window with setting of @True@, before it is realized\n-- or showed, it will have a \"frame\" window around its 'DrawWindow',\n-- accessible using 'windowGetFrame'. Using the signal 'windowFrameEvent' you can\n-- receive all events targeted at the frame.\n--\n-- (Note: this is a special-purpose function for the framebuffer port, that causes GTK+ to draw its own window border. \n-- For most applications, you want 'windowSetDecorated' instead, which tells the window manager whether to draw the window border.)\n--\n-- This function is used by the linux-fb port to implement managed windows, \n-- but it could conceivably be used by X-programs that want to do their own window\n-- decorations.\n--\nwindowSetHasFrame :: WindowClass self => self \n -> Bool -- ^ @setting@ - a boolean \n -> IO ()\nwindowSetHasFrame self setting =\n {# call window_set_has_frame #}\n (toWindow self)\n (fromBool setting)\n\n-- | Accessor for whether the window has a frame window exterior to window->window. Gets the value set by 'windowSetHasFrame'.\n--\nwindowGetHasFrame :: WindowClass self => self\n -> IO Bool -- ^ return @True@ if a frame has been added to the window via 'windowSetHasFrame'.\nwindowGetHasFrame self = liftM toBool $\n {# call window_get_has_frame #}\n (toWindow self)\n\n-- | This function is only useful on X11, not with other Gtk+ targets.\n--\n-- In combination with the window title, the window role allows a window\n-- manager to identify \\\"the same\\\" window when an application is restarted. So\n-- for example you might set the \\\"toolbox\\\" role on your app's toolbox window,\n-- so that when the user restarts their session, the window manager can put the\n-- toolbox back in the same place.\n--\n-- If a window already has a unique title, you don't need to set the role,\n-- since the WM can use the title to identify the window when restoring the\n-- session.\n--\nwindowSetRole :: WindowClass self => self\n -> String -- ^ @role@ - unique identifier for the window to be used when\n -- restoring a session\n -> IO ()\nwindowSetRole self role =\n withUTFString role $ \\rolePtr ->\n {# call window_set_role #}\n (toWindow self)\n rolePtr\n\n-- | Returns the role of the window. See 'windowSetRole' for further\n-- explanation.\n--\nwindowGetRole :: WindowClass self => self\n -> IO (Maybe String) -- ^ returns the role of the window if set, or\n -- @Nothing@.\nwindowGetRole self =\n {# call gtk_window_get_role #}\n (toWindow self)\n >>= maybePeek peekUTFString\n\n-- | Asks to stick @window@, which means that it will appear on all user\n-- desktops. Note that you shouldn't assume the window is definitely stuck\n-- afterward, because other entities (e.g. the user or window manager) could\n-- unstick it again, and some window managers do not support sticking windows.\n-- But normally the window will end up stuck. Just don't write code that\n-- crashes if not.\n--\n-- It's permitted to call this function before showing a window.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowStick :: WindowClass self => self -> IO ()\nwindowStick self =\n {# call window_stick #}\n (toWindow self)\n\n-- | Asks to unstick @window@, which means that it will appear on only one of\n-- the user's desktops. Note that you shouldn't assume the window is definitely\n-- unstuck afterward, because other entities (e.g. the user or window manager)\n-- could stick it again. But normally the window will end up stuck. Just don't\n-- write code that crashes if not.\n--\n-- You can track stickiness via the 'windowStateEvent' signal on\n-- 'Widget'.\n--\nwindowUnstick :: WindowClass self => self -> IO ()\nwindowUnstick self =\n {# call window_unstick #}\n (toWindow self)\n\n-- | Associate @accelGroup@ with @window@, such that calling\n-- 'accelGroupsActivate' on @window@ will activate accelerators in\n-- @accelGroup@.\n--\nwindowAddAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowAddAccelGroup self accelGroup =\n {# call gtk_window_add_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Reverses the effects of 'windowAddAccelGroup'.\n--\nwindowRemoveAccelGroup :: WindowClass self => self\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'\n -> IO ()\nwindowRemoveAccelGroup self accelGroup =\n {# call gtk_window_remove_accel_group #}\n (toWindow self)\n accelGroup\n\n-- | Sets up the icon representing a 'Window'. This icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- The icon should be provided in whatever size it was naturally drawn; that\n-- is, don't scale the image before passing it to Gtk+. Scaling is postponed\n-- until the last minute, when the desired final size is known, to allow best\n-- quality.\n--\n-- If you have your icon hand-drawn in multiple sizes, use\n-- 'windowSetIconList'. Then the best size will be used.\n--\n-- This function is equivalent to calling 'windowSetIconList' with a\n-- 1-element list.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\nwindowSetIcon :: WindowClass self => self\n -> Maybe Pixbuf -- ^ @icon@ - icon image\n -> IO ()\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n (Pixbuf nullForeignPtr)\nwindowSetIcon self (Just icon) =\n {# call gtk_window_set_icon #}\n (toWindow self)\n icon\n\n-- | Gets the value set by 'windowSetIcon' (or if you\\'ve called\n-- 'windowSetIconList', gets the first icon in the icon list).\n--\nwindowGetIcon :: WindowClass self => self\n -> IO (Maybe Pixbuf) -- ^ returns icon for window, or @Nothing@ if none was set\nwindowGetIcon self =\n maybeNull (makeNewGObject mkPixbuf) $\n {# call gtk_window_get_icon #}\n (toWindow self)\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the window is minimized (also known as iconified). \n-- Some window managers or desktop environments may also place it in the window frame, or display it in other contexts.\n--\n-- 'windowSetIconList' allows you to pass in the same icon in several hand-drawn sizes. \n-- The list should contain the natural sizes your icon is available in; that is, don't scale the image before passing it to GTK+. \n-- Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.\n--\n-- By passing several sizes, you may improve the final image quality of the icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in your application in one go.\n--\n-- Note that transient windows (those who have been set transient for another window using 'windowSetTransientFor' will inherit their icon from their\n-- transient parent. \n-- So there's no need to explicitly set the icon on transient windows.\n--\nwindowSetIconList :: WindowClass self => self\n -> [Pixbuf]\n -> IO ()\nwindowSetIconList self list =\n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_icon_list #}\n (toWindow self)\n glist\n \n-- | Retrieves the list of icons set by 'windowSetIconList'. \n--\nwindowGetIconList :: WindowClass self => self \n -> IO [Pixbuf]\nwindowGetIconList self = do\n glist <- {# call window_get_icon_list #} (toWindow self)\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n-- | Sets an icon list to be used as fallback for windows that haven't had 'windowSetIconList' called on them to set up a window-specific icon list. \n-- This function allows you to set up the icon for all windows in your app at once.\n--\n-- See 'windowSetIconList' for more details.\n--\nwindowSetDefaultIconList :: [Pixbuf] -> IO ()\nwindowSetDefaultIconList list = \n withForeignPtrs (map unPixbuf list) $ \\ptrList ->\n withGList ptrList $ \\glist ->\n {# call window_set_default_icon_list #} glist\n\n-- | Gets the value set by 'windowSetDefaultIconList'. \n--\nwindowGetDefaultIconList :: IO [Pixbuf]\nwindowGetDefaultIconList = do\n glist <- {# call window_get_default_icon_list #}\n ptrList <- fromGList glist\n mapM (makeNewGObject mkPixbuf . return) ptrList\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Sets the icon for the window from a named themed icon. See the docs for\n-- 'IconTheme' for more details.\n--\n-- Note that this has nothing to do with the WM_ICON_NAME property which is\n-- mentioned in the ICCCM.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetIconName :: WindowClass self => self\n -> String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetIconName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_icon_name #}\n (toWindow self)\n namePtr\n\n-- | Returns the name of the themed icon for the window, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowGetIconName :: WindowClass self => self\n -> IO String -- ^ returns the icon name or @\\\"\\\"@ if the window has no themed\n -- icon.\nwindowGetIconName self =\n {# call gtk_window_get_icon_name #}\n (toWindow self)\n >>= \\strPtr -> if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a named themed icon, see\n-- 'windowSetIconName'.\n--\n-- * Available since Gtk+ version 2.6\n--\nwindowSetDefaultIconName :: \n String -- ^ @name@ - the name of the themed icon\n -> IO ()\nwindowSetDefaultIconName name =\n withUTFString name $ \\namePtr ->\n {# call gtk_window_set_default_icon_name #}\n namePtr\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Sets an icon to be used as fallback for windows that haven't had 'windowSetIcon' called on them from a pixbuf.\n--\n-- * Available since Gtk+ version 2.4\n--\nwindowSetDefaultIcon :: Maybe Pixbuf -> IO ()\nwindowSetDefaultIcon (Just icon) =\n {# call window_set_default_icon #} icon\nwindowSetDefaultIcon Nothing =\n {# call window_set_default_icon #} (Pixbuf nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets an icon to be used as fallback for windows that haven't had\n-- 'windowSetIconList' called on them from a file on disk. May throw a 'GError' if\n-- the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetDefaultIconFromFile ::\n String -- ^ @filename@ - location of icon file\n -> IO Bool -- ^ returns @True@ if setting the icon succeeded.\nwindowSetDefaultIconFromFile filename =\n liftM toBool $\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr ->\n {# call gtk_window_set_default_icon_from_file #}\n filenamePtr\n errPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,16,0)\n-- | Returns the fallback icon name for windows that has been set with\n-- 'windowSetDefaultIconName'.\n--\n-- * Available since Gtk+ version 2.16\n--\nwindowGetDefaultIconName ::\n IO String -- ^ returns the fallback icon name for windows\nwindowGetDefaultIconName =\n {# call window_get_default_icon_name #}\n >>= peekUTFString\n#endif\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Sets the 'Screen' where the @window@ is displayed; if the window is\n-- already mapped, it will be unmapped, and then remapped on the new screen.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetScreen :: WindowClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'.\n -> IO ()\nwindowSetScreen self screen =\n {# call gtk_window_set_screen #}\n (toWindow self)\n screen\n\n-- | Returns the 'Screen' associated with the window.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowGetScreen :: WindowClass self => self\n -> IO Screen -- ^ returns a 'Screen'.\nwindowGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_window_get_screen #}\n (toWindow self)\n\n-- | Sets the icon for @window@.\n--\n-- This function is equivalent to calling 'windowSetIcon' with a pixbuf\n-- created by loading the image from @filename@.\n--\n-- This may throw an exception if the file cannot be loaded.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetIconFromFile :: WindowClass self => self\n -> FilePath -- ^ @filename@ - location of icon file\n -> IO ()\nwindowSetIconFromFile self filename =\n propagateGError $ \\errPtr ->\n withUTFString filename $ \\filenamePtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gtk_window_set_icon_from_file_utf8 #}\n#else\n {# call gtk_window_set_icon_from_file #}\n#endif\n (toWindow self)\n filenamePtr\n errPtr\n return ()\n\n-- | By default, after showing the first 'Window' for each 'Screen', Gtk+\n-- calls 'screenNotifyStartupComplete'. Call this function to disable the\n-- automatic startup notification. You might do this if your first window is a\n-- splash screen, and you want to delay notification until after your real main\n-- window has been shown, for example.\n--\n-- In that example, you would disable startup notification temporarily, show\n-- your splash screen, then re-enable it so that showing the main window would\n-- automatically result in notification.\n--\n-- * Available since Gtk+ version 2.2\n--\nwindowSetAutoStartupNotification :: \n Bool -- ^ @setting@ - @True@ to automatically do startup notification\n -> IO ()\nwindowSetAutoStartupNotification setting =\n {# call gtk_window_set_auto_startup_notification #}\n (fromBool setting)\n#endif\n\n-- | Window gravity defines the meaning of coordinates passed to 'windowMove'.\n-- See 'windowMove' and 'Gravity' for more details.\n--\n-- The default window gravity is 'GravityNorthWest' which will typically\n-- \\\"do what you mean.\\\"\n--\nwindowSetGravity :: WindowClass self => self\n -> Gravity -- ^ @gravity@ - window gravity\n -> IO ()\nwindowSetGravity self gravity =\n {# call gtk_window_set_gravity #}\n (toWindow self)\n ((fromIntegral . fromEnum) gravity)\n\n-- | Gets the value set by 'windowSetGravity'.\n--\nwindowGetGravity :: WindowClass self => self\n -> IO Gravity -- ^ returns window gravity\nwindowGetGravity self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_gravity #}\n (toWindow self)\n\n-- | Asks the window manager to move @window@ to the given position. Window\n-- managers are free to ignore this; most window managers ignore requests for\n-- initial window positions (instead using a user-defined placement algorithm)\n-- and honor requests after the window has already been shown.\n--\n-- Note: the position is the position of the gravity-determined reference\n-- point for the window. The gravity determines two things: first, the location\n-- of the reference point in root window coordinates; and second, which point\n-- on the window is positioned at the reference point.\n--\n-- By default the gravity is 'GravityNorthWest', so the reference point is\n-- simply the @x@, @y@ supplied to 'windowMove'. The top-left corner of the\n-- window decorations (aka window frame or border) will be placed at @x@, @y@.\n-- Therefore, to position a window at the top left of the screen, you want to\n-- use the default gravity (which is 'GravityNorthWest') and move the window to\n-- 0,0.\n--\n-- To position a window at the bottom right corner of the screen, you would\n-- set 'GravitySouthEast', which means that the reference point is at @x@ + the\n-- window width and @y@ + the window height, and the bottom-right corner of the\n-- window border will be placed at that reference point. So, to place a window\n-- in the bottom right corner you would first set gravity to south east, then\n-- write: @gtk_window_move (window, gdk_screen_width() - window_width,\n-- gdk_screen_height() - window_height)@.\n--\n-- The Extended Window Manager Hints specification at\n-- http:\\\/\\\/www.freedesktop.org\\\/Standards\\\/wm-spec has a nice table of\n-- gravities in the \\\"implementation notes\\\" section.\n--\n-- The 'windowGetPosition' documentation may also be relevant.\n--\nwindowMove :: WindowClass self => self\n -> Int -- ^ @x@ - X coordinate to move window to\n -> Int -- ^ @y@ - Y coordinate to move window to\n -> IO ()\nwindowMove self x y =\n {# call gtk_window_move #}\n (toWindow self)\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Parses a standard X Window System geometry string - see the manual page for X (type 'man X') for details on this. \n-- 'windowParseGeometry' does work on all GTK+ ports including Win32 but is primarily intended for an X environment.\n--\n-- If either a size or a position can be extracted from the geometry string, \n-- 'windowParseGeometry' returns @True@ and calls gtk_window_set_default_size() and\/or gtk_window_move() to resize\/move the window.\n--\n-- If 'windowParseGeometry' returns @True@, \n-- it will also set the 'HintUserPos' and\/or 'HintUserSize' hints indicating to the window manager that the size\/position of the window was user-specified\n-- This causes most window managers to honor the geometry.\n--\n-- Note that for 'windowParseGeometry' to work as expected, it has to be called when the window has its \"final\" size, i.e. \n-- after calling 'widgetShowAll' on the contents and 'windowSetGeometryHints' on the window.\n--\nwindowParseGeometry :: WindowClass self => self\n -> String\n -> IO Bool\nwindowParseGeometry self geometry = liftM toBool $\n withUTFString geometry $ \\geometryPtr -> \n {# call window_parse_geometry #}\n (toWindow self)\n geometryPtr\n\n-- | Hides window, then reshows it, resetting the default size and position of the window. Used by GUI builders only.\n--\nwindowReshowWithInitialSize :: WindowClass self => self -> IO ()\nwindowReshowWithInitialSize self =\n {# call window_reshow_with_initial_size #} (toWindow self)\n\n-- | Resizes the window as if the user had done so, obeying geometry\n-- constraints. The default geometry constraint is that windows may not be\n-- smaller than their size request; to override this constraint, call\n-- 'widgetSetSizeRequest' to set the window's request to a smaller value.\n--\n-- If 'windowResize' is called before showing a window for the first time,\n-- it overrides any default size set with 'windowSetDefaultSize'.\n--\n-- Windows may not be resized smaller than 1 by 1 pixels.\n--\nwindowResize :: WindowClass self => self\n -> Int -- ^ @width@ - width in pixels to resize the window to\n -> Int -- ^ @height@ - height in pixels to resize the window to\n -> IO ()\nwindowResize self width height =\n {# call gtk_window_resize #}\n (toWindow self)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Starts resizing a window. This function is used if an application has\n-- window resizing controls. When GDK can support it, the resize will be done\n-- using the standard mechanism for the window manager or windowing system.\n-- Otherwise, GDK will try to emulate window resizing, potentially not all that\n-- well, depending on the windowing system.\n--\nwindowBeginResizeDrag :: WindowClass self => self\n -> WindowEdge -- ^ @edge@ - position of the resize control\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate\n -- the drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate\n -- the drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that\n -- initiated the drag\n -> IO ()\nwindowBeginResizeDrag self edge button rootX rootY timestamp =\n {# call gtk_window_begin_resize_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) edge)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | Starts moving a window. This function is used if an application has\n-- window movement grips. When GDK can support it, the window movement will be\n-- done using the standard mechanism for the window manager or windowing\n-- system. Otherwise, GDK will try to emulate window movement, potentially not\n-- all that well, depending on the windowing system.\n--\nwindowBeginMoveDrag :: WindowClass self => self\n -> MouseButton -- ^ @button@ - mouse button that initiated the drag\n -> Int -- ^ @rootX@ - X position where the user clicked to initiate the\n -- drag, in root window coordinates\n -> Int -- ^ @rootY@ - Y position where the user clicked to initiate the\n -- drag\n -> TimeStamp -- ^ @timestamp@ - timestamp from the click event that initiated\n -- the drag\n -> IO ()\nwindowBeginMoveDrag self button rootX rootY timestamp =\n {# call gtk_window_begin_move_drag #}\n (toWindow self)\n ((fromIntegral . fromEnum) button)\n (fromIntegral rootX)\n (fromIntegral rootY)\n (fromIntegral timestamp)\n\n-- | This function returns the position you need to pass to 'windowMove' to\n-- keep @window@ in its current position. This means that the meaning of the\n-- returned value varies with window gravity. See 'windowMove' for more\n-- details.\n--\n-- If you haven't changed the window gravity, its gravity will be\n-- 'GravityNorthWest'. This means that 'windowGetPosition' gets the position of\n-- the top-left corner of the window manager frame for the window. 'windowMove'\n-- sets the position of this same top-left corner.\n--\n-- Moreover, nearly all window managers are historically broken with respect\n-- to their handling of window gravity. So moving a window to its current\n-- position as returned by 'windowGetPosition' tends to result in moving the\n-- window slightly. Window managers are slowly getting better over time.\n--\n-- If a window has gravity 'GravityStatic' the window manager frame is not\n-- relevant, and thus 'windowGetPosition' will always produce accurate results.\n-- However you can't use static gravity to do things like place a window in a\n-- corner of the screen, because static gravity ignores the window manager\n-- decorations.\n--\n-- If you are saving and restoring your application's window positions, you\n-- should know that it's impossible for applications to do this without getting\n-- it somewhat wrong because applications do not have sufficient knowledge of\n-- window manager state. The Correct Mechanism is to support the session\n-- management protocol (see the \\\"GnomeClient\\\" object in the GNOME libraries\n-- for example) and allow the window manager to save your window sizes and\n-- positions.\n--\nwindowGetPosition :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(rootX, rootY)@ - X and Y coordinate of\n -- gravity-determined reference point\nwindowGetPosition self =\n alloca $ \\rootXPtr ->\n alloca $ \\rootYPtr -> do\n {# call gtk_window_get_position #}\n (toWindow self)\n rootXPtr\n rootYPtr\n rootX <- peek rootXPtr\n rootY <- peek rootYPtr\n return (fromIntegral rootX, fromIntegral rootY)\n\n-- | Obtains the current size of the window. If the window is not onscreen, it\n-- returns the size Gtk+ will suggest to the window manager for the initial\n-- window size (but this is not reliably the same as the size the window\n-- manager will actually select). The size obtained by 'windowGetSize' is the\n-- last size received in a 'EventConfigure', that is,\n-- Gtk+ uses its locally-stored size, rather than querying the X server for the\n-- size. As a result, if you call 'windowResize' then immediately call\n-- 'windowGetSize', the size won't have taken effect yet. After the window\n-- manager processes the resize request, Gtk+ receives notification that the\n-- size has changed via a configure event, and the size of the window gets\n-- updated.\n--\n-- Note 1: Nearly any use of this function creates a race condition, because\n-- the size of the window may change between the time that you get the size and\n-- the time that you perform some action assuming that size is the current\n-- size. To avoid race conditions, connect to \\\"configure_event\\\" on the window\n-- and adjust your size-dependent state to match the size delivered in the\n-- 'EventConfigure'.\n--\n-- Note 2: The returned size does \/not\/ include the size of the window\n-- manager decorations (aka the window frame or border). Those are not drawn by\n-- Gtk+ and Gtk+ has no reliable method of determining their size.\n--\n-- Note 3: If you are getting a window size in order to position the window\n-- onscreen, there may be a better way. The preferred way is to simply set the\n-- window's semantic type with 'windowSetTypeHint', which allows the window\n-- manager to e.g. center dialogs. Also, if you set the transient parent of\n-- dialogs with 'windowSetTransientFor' window managers will often center the\n-- dialog over its parent window. It's much preferred to let the window manager\n-- handle these things rather than doing it yourself, because all apps will\n-- behave consistently and according to user prefs if the window manager\n-- handles it. Also, the window manager can take the size of the window\n-- decorations\\\/border into account, while your application cannot.\n--\n-- In any case, if you insist on application-specified window positioning,\n-- there's \/still\/ a better way than doing it yourself - 'windowSetPosition'\n-- will frequently handle the details for you.\n--\nwindowGetSize :: WindowClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwindowGetSize self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_window_get_size #}\n (toWindow self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- | By setting the type hint for the window, you allow the window manager to\n-- decorate and handle the window in a way which is suitable to the function of\n-- the window in your application.\n--\n-- This function should be called before the window becomes visible.\n--\nwindowSetTypeHint :: WindowClass self => self\n -> WindowTypeHint -- ^ @hint@ - the window type\n -> IO ()\nwindowSetTypeHint self hint =\n {# call gtk_window_set_type_hint #}\n (toWindow self)\n ((fromIntegral . fromEnum) hint)\n\n-- | Gets the type hint for this window. See 'windowSetTypeHint'.\n--\nwindowGetTypeHint :: WindowClass self => self\n -> IO WindowTypeHint -- ^ returns the type hint for @window@.\nwindowGetTypeHint self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_window_get_type_hint #}\n (toWindow self)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Presents a window to the user in response to a user interaction. If you\n-- need to present a window without a timestamp, use 'windowPresent'. See\n-- 'windowPresent' for details.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowPresentWithTime :: WindowClass self => self\n -> TimeStamp -- ^ @timestamp@ - the timestamp of the user interaction\n -- (typically a button or key press event) which triggered this\n -- call\n -> IO ()\nwindowPresentWithTime self timestamp =\n {# call gtk_window_present_with_time #}\n (toWindow self)\n (fromIntegral timestamp)\n\n-- | Windows may set a hint asking the desktop environment to draw the users\n-- attention to the window. This function sets this hint.\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowSetUrgencyHint :: WindowClass self => self\n -> Bool -- ^ @setting@ - @True@ to mark this window as urgent\n -> IO ()\nwindowSetUrgencyHint self setting =\n {# call gtk_window_set_urgency_hint #}\n (toWindow self)\n (fromBool setting)\n\n-- | Gets the value set by 'windowSetUrgencyHint'\n--\n-- * Available since Gtk+ version 2.8\n--\nwindowGetUrgencyHint :: WindowClass self => self\n -> IO Bool -- ^ returns @True@ if window is urgent\nwindowGetUrgencyHint self =\n liftM toBool $\n {# call gtk_window_get_urgency_hint #}\n (toWindow self)\n#endif\n\n-- | This function sets up hints about how a window can be resized by the\n-- user. You can set a minimum and maximum size, the allowed resize increments\n-- (e.g. for xterm, you can only resize by the size of a character) and aspect\n-- ratios.\n--\n-- If you set a geometry widget, the hints will apply to the geometry widget\n-- instead of directly to the toplevel window. Of course since the geometry\n-- widget is a child widget of the top level window, constraining the sizing\n-- behaviour of the widget will have a knock-on effect on the sizing of the\n-- toplevel window.\n--\n-- The @minWidth@\\\/@minHeight@\\\/@maxWidth@\\\/@maxHeight@ fields may be set to\n-- @-1@, to use the size request of the window or geometry widget. If the\n-- minimum size hint is not provided, Gtk+ will use the size requisition of the\n-- window (or the geometry widget if it set) as the minimum size. The base size\n-- is treated similarly.\n--\n-- The canonical use-case for 'windowSetGeometryHints' is to get a terminal\n-- widget to resize properly. Here, the terminal text area should be the\n-- geometry widget. Gtk+ will then automatically set the base size of the\n-- terminal window to the size of other widgets in the terminal window, such as\n-- the menubar and scrollbar. Then, the @widthInc@ and @heightInc@ values\n-- should be set to the size of one character in the terminal. Finally, the\n-- base size should be set to the size of one character. The net effect is that\n-- the minimum size of the terminal will have a 1x1 character terminal area,\n-- and only terminal sizes on the \\\"character grid\\\" will be allowed.\n--\n-- The other useful settings are @minAspect@ and @maxAspect@. These specify a\n-- width\\\/height ratio as a floating point number. If a geometry widget is set,\n-- the aspect applies to the geometry widget rather than the entire window. The\n-- most common use of these hints is probably to set @minAspect@ and\n-- @maxAspect@ to the same value, thus forcing the window to keep a constant\n-- aspect ratio.\n--\nwindowSetGeometryHints :: (WindowClass self, WidgetClass widget) =>\n self -- ^ @window@ - the top level window\n -> Maybe widget -- ^ @geometryWidget@ - optionall a widget the geometry\n -- hints will be applied to rather than directly to the\n -- top level window\n -> Maybe (Int, Int) -- ^ @(minWidth, minHeight)@ - minimum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(maxWidth, maxHeight)@ - maximum width and height\n -- of window (or -1 to use requisition)\n -> Maybe (Int, Int) -- ^ @(baseWidth, baseHeight)@ - the allowed window widths\n -- are @base_width + width_inc * N@ for any int @N@.\n -- Similarly, the allowed window widths are @base_height +\n -- height_inc * N@ for any int @N@. For either the base\n -- width or height -1 is allowed as described above.\n -> Maybe (Int, Int) -- ^ @(widthInc, heightInc)@ - width and height resize\n -- increment\n -> Maybe (Double, Double) -- ^ @(minAspect, maxAspect)@ - minimum and maximum\n -- width\\\/height ratio\n -> IO ()\nwindowSetGeometryHints self geometryWidget\n minSize maxSize baseSize incSize aspect =\n allocaBytes {# sizeof GdkGeometry #} $ \\geometryPtr -> do\n minSizeFlag <- case minSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->min_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->min_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMinSize)\n maxSizeFlag <- case maxSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->max_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->max_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintMaxSize)\n baseSizeFlag <- case baseSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->base_width #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->base_height #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintBaseSize)\n incSizeFlag <- case incSize of\n Nothing -> return 0\n Just (width, height) -> do\n {# set GdkGeometry->width_inc #} geometryPtr (fromIntegral width)\n {# set GdkGeometry->height_inc #} geometryPtr (fromIntegral height)\n return (fromEnum GdkHintResizeInc)\n aspectFlag <- case aspect of\n Nothing -> return 0\n Just (min, max) -> do\n {# set GdkGeometry->min_aspect #} geometryPtr (realToFrac min)\n {# set GdkGeometry->max_aspect #} geometryPtr (realToFrac max)\n return (fromEnum GdkHintAspect)\n\n {# call gtk_window_set_geometry_hints #}\n (toWindow self)\n (maybe (Widget nullForeignPtr) toWidget geometryWidget)\n geometryPtr\n (fromIntegral $ minSizeFlag .|. maxSizeFlag .|. baseSizeFlag\n .|. incSizeFlag .|. aspectFlag)\n\n{# enum GdkWindowHints {underscoreToCase} #}\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Request the windowing system to make window partially transparent, with opacity 0 being fully transparent and 1 fully opaque. \n-- (Values of the opacity parameter are clamped to the [0,1] range.) \n-- On X11 this has any effect only on X screens with a compositing manager running.\n-- See 'widgetIsComposited'. On Windows it should work always.\n--\n-- Note that setting a window's opacity after the window has been shown causes it to\n-- flicker once on Windows.\n-- \n-- * Available since Gtk+ version 2.12\n--\nwindowSetOpacity :: WindowClass self => self\n -> Double -- ^ @opacity@ - desired opacity, between 0 and 1 \n -> IO ()\nwindowSetOpacity self opacity =\n {#call window_set_opacity #} (toWindow self) (realToFrac opacity)\n\n-- | Fetches the requested opacity for this window. See 'windowSetOpacity'.\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowGetOpacity :: WindowClass self => self \n -> IO Double -- ^ return the requested opacity for this window. \nwindowGetOpacity self = liftM realToFrac $\n {#call window_get_opacity#} (toWindow self)\n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the group for window or the default group, if window is @Nothing@ or if window does not have an explicit window group.\n-- \n-- * Available since Gtk+ version 2.10\n--\nwindowGetGroup :: WindowClass self => Maybe self\n -> IO WindowGroup -- ^ return the 'WindowGroup' for a window or the default group \nwindowGetGroup self = \n makeNewGObject mkWindowGroup $\n {# call window_get_group #} (maybe (Window nullForeignPtr) toWindow self)\n#endif \n\n--------------------\n-- Attributes\n\n-- | The title of the window.\n--\nwindowTitle :: WindowClass self => Attr self String\nwindowTitle = newAttr\n windowGetTitle\n windowSetTitle\n\n-- | The type of the window.\n--\n-- Default value: 'WindowToplevel'\n--\nwindowType :: WindowClass self => ReadAttr self WindowType\nwindowType = readAttrFromEnumProperty \"type\"\n {# call pure unsafe gtk_window_type_get_type #}\n\n-- | If @True@, the window has no mimimum size. Setting this to @True@ is 99%\n-- of the time a bad idea.\n--\n-- Default value: @False@\n--\nwindowAllowShrink :: WindowClass self => Attr self Bool\nwindowAllowShrink = newAttrFromBoolProperty \"allow-shrink\"\n\n-- | If @True@, users can expand the window beyond its minimum size.\n--\n-- Default value: @True@\n--\nwindowAllowGrow :: WindowClass self => Attr self Bool\nwindowAllowGrow = newAttrFromBoolProperty \"allow-grow\"\n\n-- | If @True@, users can resize the window.\n--\n-- Default value: @True@\n--\nwindowResizable :: WindowClass self => Attr self Bool\nwindowResizable = newAttr\n windowGetResizable\n windowSetResizable\n\n-- | If @True@, the window is modal (other windows are not usable while this\n-- one is up).\n--\n-- Default value: @False@\n--\nwindowModal :: WindowClass self => Attr self Bool\nwindowModal = newAttr\n windowGetModal\n windowSetModal\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The requested opacity of the window. See 'windowSetOpacity' for more details about window opacity.\n--\n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowOpacity :: WindowClass self => Attr self Double\nwindowOpacity = newAttrFromDoubleProperty \"opacity\"\n#endif\n\n-- | If @focus@ is not the current focus widget, and is focusable, sets it as\n-- the focus widget for the window. If @focus@ is @Nothing@, unsets the focus widget for\n-- this window. To set the focus to a particular widget in the toplevel, it is\n-- usually more convenient to use 'widgetGrabFocus' instead of this function.\n--\nwindowFocus :: WindowClass self => Attr self (Maybe Widget)\nwindowFocus = newAttr\n windowGetFocus\n windowSetFocus\n\n-- | (Note: this is a special-purpose function for the framebuffer port, that\n-- causes Gtk+ to draw its own window border. For most applications, you want\n-- 'windowSetDecorated' instead, which tells the window manager whether to draw\n-- the window border.)\n--\n-- If this function is called on a window with setting of @True@, before it\n-- is realized or showed, it will have a \\\"frame\\\" window around\n-- its 'DrawWindow', accessible using 'windowGetFrame'. Using the signal\n-- 'windowFrameEvent' you can receive all events targeted at the frame.\n--\n-- This function is used by the linux-fb port to implement managed windows,\n-- but it could conceivably be used by X-programs that want to do their own\n-- window decorations.\n--\nwindowHasFrame :: WindowClass self => Attr self Bool\nwindowHasFrame = newAttr\n windowGetHasFrame\n windowSetHasFrame\n\n-- | Sets up the icon representing a 'Window'. The icon is used when the\n-- window is minimized (also known as iconified). Some window managers or\n-- desktop environments may also place it in the window frame, or display it in\n-- other contexts.\n--\n-- By passing several sizes, you may improve the final image quality of the\n-- icon, by reducing or eliminating automatic image scaling.\n--\n-- Recommended sizes to provide: 16x16, 32x32, 48x48 at minimum, and larger\n-- images (64x64, 128x128) if you have them.\n--\n-- See also 'windowSetDefaultIconList' to set the icon for all windows in\n-- your application in one go.\n--\n-- Note that transient windows (those who have been set transient for\n-- another window using 'windowSetTransientFor') will inherit their icon from\n-- their transient parent. So there's no need to explicitly set the icon on\n-- transient windows.\n--\nwindowIconList :: WindowClass self => Attr self [Pixbuf]\nwindowIconList = newAttr\n windowGetIconList\n windowSetIconList\n\n-- | The mnemonic modifier for this window.\n--\nwindowMnemonicModifier :: WindowClass self => Attr self [Modifier]\nwindowMnemonicModifier = newAttr\n windowGetMnemonicModifier\n windowSetMnemonicModifier\n\n-- | Unique identifier for the window to be used when restoring a session.\n--\n-- Default value: \"\\\\\"\n--\nwindowRole :: WindowClass self => Attr self String\nwindowRole = newAttrFromStringProperty \"role\"\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | The 'windowStartupId' is a write-only property for setting window's startup notification identifier.\n--\n-- Default value: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.12\n--\nwindowStartupId :: WindowClass self => Attr self String\nwindowStartupId = newAttrFromStringProperty \"startup-id\"\n#endif\n\n-- | The initial position of the window.\n--\n-- Default value: 'WinPosNone'\n--\nwindowWindowPosition :: WindowClass self => Attr self WindowPosition\nwindowWindowPosition = newAttrFromEnumProperty \"window-position\"\n {# call pure unsafe gtk_window_position_get_type #}\n\n-- | The default width of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultWidth :: WindowClass self => Attr self Int\nwindowDefaultWidth = newAttrFromIntProperty \"default-width\"\n\n-- | The default height of the window, used when initially showing the window.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwindowDefaultHeight :: WindowClass self => Attr self Int\nwindowDefaultHeight = newAttrFromIntProperty \"default-height\"\n\n-- | Whether the window frame should have a close button.\n--\n-- Default values: @True@\n--\n-- * Available since Gtk+ version 2.10\n--\nwindowDeletable :: WindowClass self => Attr self Bool\nwindowDeletable = newAttrFromBoolProperty \"deletable\"\n\n-- | If this window should be destroyed when the parent is destroyed.\n--\n-- Default value: @False@\n--\nwindowDestroyWithParent :: WindowClass self => Attr self Bool\nwindowDestroyWithParent = newAttr\n windowGetDestroyWithParent\n windowSetDestroyWithParent\n\n-- | Icon for this window.\n--\nwindowIcon :: WindowClass self => Attr self (Maybe Pixbuf)\nwindowIcon = newAttr\n windowGetIcon\n windowSetIcon\n\n-- | The 'windowIconName' property specifies the name of the themed icon to use as the window icon. See 'IconTheme' for more details.\n--\n-- Default values: \"\\\\\"\n--\n-- * Available since Gtk+ version 2.6\n--\n--\nwindowIconName :: WindowClass self => Attr self String\nwindowIconName = newAttrFromStringProperty \"icon-name\"\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | The screen where this window will be displayed.\n--\nwindowScreen :: WindowClass self => Attr self Screen\nwindowScreen = newAttr\n windowGetScreen\n windowSetScreen\n#endif\n\n-- | Hint to help the desktop environment understand what kind of window this\n-- is and how to treat it.\n--\n-- Default value: 'WindowTypeHintNormal'\n--\nwindowTypeHint :: WindowClass self => Attr self WindowTypeHint\nwindowTypeHint = newAttr\n windowGetTypeHint\n windowSetTypeHint\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | @True@ if the window should not be in the task bar.\n--\n-- Default value: @False@\n--\nwindowSkipTaskbarHint :: WindowClass self => Attr self Bool\nwindowSkipTaskbarHint = newAttr\n windowGetSkipTaskbarHint\n windowSetSkipTaskbarHint\n\n-- | @True@ if the window should not be in the pager.\n--\n-- Default value: @False@\n--\nwindowSkipPagerHint :: WindowClass self => Attr self Bool\nwindowSkipPagerHint = newAttr\n windowGetSkipPagerHint\n windowSetSkipPagerHint\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | @True@ if the window should be brought to the user's attention.\n--\n-- Default value: @False@\n--\nwindowUrgencyHint :: WindowClass self => Attr self Bool\nwindowUrgencyHint = newAttr\n windowGetUrgencyHint\n windowSetUrgencyHint\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | @True@ if the window should receive the input focus.\n--\n-- Default value: @True@\n--\nwindowAcceptFocus :: WindowClass self => Attr self Bool\nwindowAcceptFocus = newAttr\n windowGetAcceptFocus\n windowSetAcceptFocus\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | @True@ if the window should receive the input focus when mapped.\n--\n-- Default value: @True@\n--\nwindowFocusOnMap :: WindowClass self => Attr self Bool\nwindowFocusOnMap = newAttr\n windowGetFocusOnMap\n windowSetFocusOnMap\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether the window should be decorated by the window manager.\n--\n-- Default value: @True@\n--\nwindowDecorated :: WindowClass self => Attr self Bool\nwindowDecorated = newAttr\n windowGetDecorated\n windowSetDecorated\n\n-- | The window gravity of the window. See 'windowMove' and 'Gravity' for more\n-- details about window gravity.\n--\n-- Default value: 'GravityNorthWest'\n--\nwindowGravity :: WindowClass self => Attr self Gravity\nwindowGravity = newAttr\n windowGetGravity\n windowSetGravity\n#endif\n\n-- | Whether the input focus is within this GtkWindow.\n--\n-- Note: If add `window` before `HasToplevelFocus` (has-toplevel-focus attribute)\n-- will conflicts with fucntion `windowHasToplevelFocus`, so we named this attribute \n-- to `windowToplevelFocus`.\n--\n-- Default values: @False@\n--\nwindowToplevelFocus :: WindowClass self => Attr self Bool\nwindowToplevelFocus = newAttrFromBoolProperty \"has-toplevel-focus\"\n\n-- | \\'transientFor\\' property. See 'windowGetTransientFor' and\n-- 'windowSetTransientFor'\n--\nwindowTransientFor :: (WindowClass self, WindowClass parent) => ReadWriteAttr self (Maybe Window) parent\nwindowTransientFor = newAttr\n windowGetTransientFor\n windowSetTransientFor\n\n--------------------\n-- Signals\n\n-- | Observe events that are emitted on the frame of this window.\n-- \nframeEvent :: WindowClass self => Signal self (EventM EAny Bool)\nframeEvent = Signal (\\after obj fun ->\n connect_PTR__BOOL \"frame-event\" after obj (runReaderT fun))\n\n-- | The 'keysChanged' signal gets emitted when the set of accelerators or mnemonics that are associated with window changes.\n--\nkeysChanged :: WindowClass self => Signal self (IO ())\nkeysChanged = Signal (connect_NONE__NONE \"keys-changed\")\n\n-- | Observe a change in input focus.\n--\nsetFocus :: WindowClass self => Signal self (Widget -> IO ())\nsetFocus = Signal (connect_OBJECT__NONE \"set-focus\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Observe a change in input focus.\n--\nonSetFocus, afterSetFocus :: (WindowClass self, WidgetClass foc) => self\n -> (foc -> IO ())\n -> IO (ConnectId self)\nonSetFocus = connect_OBJECT__NONE \"set-focus\" False\nafterSetFocus = connect_OBJECT__NONE \"set-focus\" True\n\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d437fb4a9be0d8e6f59235406c2a7ed03dfc26b2","subject":"Fix a conflict in DrawWindow.","message":"Fix a conflict in DrawWindow.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"68de706d8472ccad5052fa1be08ac9f6621c38d4","subject":"missing import","message":"missing 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 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","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(..), 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":"be9c9b4c5b6161f4ae55c679b63257ddbf13f0c5","subject":"gstreamer: hopefully fix takeObject & peekObject for real this time","message":"gstreamer: hopefully fix takeObject & peekObject for real this time\n\ntakeObject: to be used when a function returns an object that must be unreffed at GC.\n If the object has a floating reference, the float flag is removed.\n\npeekObject: to be used when an object must not be unreffed. A ref is added, and is\n removed at GC. The floating flag is not touched.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n cObjectRef cObject\n takeObject cObject\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat\n newForeignPtr (castPtr cObject) objectFinalizer\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"237064443a8926019a0b441928844d1ee95cf913","subject":"docs","message":"docs\n\ndarcs-hash:20080226163121-0faa6-cd93e2af4e22bbb846d8d75df6fce4da22a5e945.gz\n","repos":"sol\/hexpat,sol\/hexpat","old_file":"Text\/XML\/Expat\/Raw.chs","new_file":"Text\/XML\/Expat\/Raw.chs","new_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n\n-- |This module wraps the Expat API directly. If you use this interface,\n-- you must e.g. free your 'Parser' manually.\n\nmodule Text.XML.Expat.Raw (\n -- ** Parser Setup\n Parser, parserCreate, parserFree, parse,\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler\n) where\n\nimport C2HS\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.\nnewtype Parser = Parser {#type Parser#}\nasParser :: Ptr () -> Parser\nasParser ptr = Parser ptr\nunParser :: Parser -> Ptr ()\nunParser (Parser p) = p\n-- |Create a parser. The parameter is the default character encoding, and can\n-- be one of\n--\n-- - \\\"US-ASCII\\\"\n--\n-- - \\\"UTF-8\\\"\n--\n-- - \\\"UTF-16\\\"\n--\n-- - \\\"ISO-8859-1\\\"\n{#fun unsafe XML_ParserCreate as parserCreate {`String'} -> `Parser' asParser#}\n\n-- |Free a Parser.\n{#fun unsafe XML_ParserFree as parserFree {unParser `Parser'} -> `()'#}\n\nunStatus :: CInt -> Bool\nunStatus 0 = False\nunStatus 1 = True\n-- |@parse data False@ feeds mode data into a 'Parser'. The end of the data\n-- is indicated by passing True for the final parameter. @parse@ returns\n-- False on a parse error.\n{#fun XML_Parse as parse\n {unParser `Parser', `String' &, `Bool'} -> `Bool' unStatus#}\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 = String -> [(String,String)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = String -> 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 = String -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler handler = mkCStartElementHandler h where\n h ptr cname cattrs = do\n name <- peekCString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekCString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler (Parser p) handler = do\n handler' <- wrapStartElementHandler handler\n {#call unsafe XML_SetStartElementHandler as ^#} p handler'\n\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler handler = mkCEndElementHandler h where\n h ptr cname = do\n name <- peekCString cname\n handler name\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler (Parser p) handler = do\n handler' <- wrapEndElementHandler handler\n {#call unsafe XML_SetEndElementHandler as ^#} p handler'\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler handler = mkCCharacterDataHandler h where\n h ptr cdata len = do\n data_ <- peekCStringLen (cdata, fromIntegral len)\n handler data_\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler (Parser p) handler = do\n handler' <- wrapCharacterDataHandler handler\n {#call unsafe XML_SetCharacterDataHandler as ^#} p handler'\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n","old_contents":"module Text.XML.Expat.Raw (\n Parser, parserCreate, parserFree, parse,\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler\n) where\nimport C2HS\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\nnewtype Parser = Parser {#type Parser#}\nasParser :: Ptr () -> Parser\nasParser ptr = Parser ptr\nunParser :: Parser -> Ptr ()\nunParser (Parser p) = p\n{#fun unsafe XML_ParserCreate as parserCreate {`String'} -> `Parser' asParser#}\n{#fun unsafe XML_ParserFree as parserFree {unParser `Parser'} -> `()'#}\n\n{#fun XML_Parse as parse\n {unParser `Parser', `String' &, `Bool'} -> `Int'#}\n\ntype StartElementHandler = String -> [(String,String)] -> IO ()\ntype EndElementHandler = String -> IO ()\ntype CharacterDataHandler = String -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler handler = mkCStartElementHandler h where\n h ptr cname cattrs = do\n name <- peekCString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekCString cattrlist\n handler name (pairwise attrlist)\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler (Parser p) handler = do\n handler' <- wrapStartElementHandler handler\n {#call unsafe XML_SetStartElementHandler as ^#} p handler'\n\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler handler = mkCEndElementHandler h where\n h ptr cname = do\n name <- peekCString cname\n handler name\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler (Parser p) handler = do\n handler' <- wrapEndElementHandler handler\n {#call unsafe XML_SetEndElementHandler as ^#} p handler'\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler handler = mkCCharacterDataHandler h where\n h ptr cdata len = do\n data_ <- peekCStringLen (cdata, fromIntegral len)\n handler data_\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler (Parser p) handler = do\n handler' <- wrapCharacterDataHandler handler\n {#call unsafe XML_SetCharacterDataHandler as ^#} p handler'\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"71ea9d98cbc7cb2ecc38ad431653684502611e20","subject":"Fix documentation and the fileRead function.","message":"Fix documentation and the fileRead function.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"d0287786f1cfe0ca7871db188ec7b4a985ef2336","subject":"Remove usage of addCleanup","message":"Remove usage of addCleanup\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/Layer.chs","new_file":"src\/GDAL\/Internal\/Layer.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n\n#include \"bindings.h\"\n#include \"gdal.h\"\n#include \"ogr_api.h\"\n\nmodule GDAL.Internal.Layer (\n HasLayerTransaction\n , SQLDialect (..)\n , Layer (..)\n , LayerH (..)\n , ROLayer\n , RWLayer\n , OGR\n , OGRConduit\n , OGRSource\n , OGRSink\n , runOGR\n\n , canCreateMultipleGeometryFields\n\n , sourceLayer\n , sourceLayer_\n , conduitInsertLayer\n , conduitInsertLayer_\n , sinkInsertLayer\n , sinkInsertLayer_\n , sinkUpdateLayer\n\n , syncLayerToDisk\n\n , layerSpatialFilter\n , layerSpatialReference\n , setLayerSpatialFilter\n , setLayerSpatialFilterRect\n , clearLayerSpatialFilter\n\n , layerName\n , layerExtent\n , layerFeatureCount\n , layerFeatureDef\n\n , createFeature\n , createFeatureWithFid\n , createFeature_\n , getFeature\n , updateFeature\n , deleteFeature\n\n , unsafeToReadOnlyLayer\n\n , liftOGR\n , closeLayer\n , unLayer\n , layerHasCapability\n , nullLayerH\n , withSQLDialect\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport Data.Conduit ( Conduit, Sink, Source\n , awaitForever, yield\n , bracketP, catchC\n , (=$=))\nimport qualified Data.Conduit.List as CL\nimport Data.Text (Text)\n\nimport Control.Applicative (Applicative, (<$>), (<*>), pure)\nimport Control.Exception (SomeException)\nimport Control.Monad (liftM, when, void, (>=>), (<=<))\nimport Control.Monad.Base (MonadBase)\nimport Control.Monad.Catch (\n MonadThrow(..)\n , MonadCatch\n , MonadMask\n )\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Control (MonadBaseControl(..))\nimport Control.Monad.Trans.Resource (MonadResource)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, withCString)\nimport Foreign.C.Types (CInt(..), CDouble(..))\nimport Foreign.Ptr (nullPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport Foreign.Storable (Storable, peek)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n\n-- A phantom-typed ST-like monad to make sure the layer does not escape its\n-- scope\nnewtype OGR s l a = OGR { unOGR :: GDAL s a}\n\nderiving instance Functor (OGR s l)\nderiving instance Applicative (OGR s l)\nderiving instance Monad (OGR s l)\nderiving instance MonadIO (OGR s l)\nderiving instance MonadThrow (OGR s l)\nderiving instance MonadCatch (OGR s l)\nderiving instance MonadMask (OGR s l)\nderiving instance MonadBase IO (OGR s l)\nderiving instance MonadResource (OGR s l)\n\ninstance MonadBaseControl IO (OGR s l) where\n type StM (OGR s l) a = a\n liftBaseWith runInBase = OGR $ do\n state <- getInternalState\n liftIO $ runInBase ((`runWithInternalState` state) . unOGR)\n restoreM = return\n\nrunOGR :: (forall l. OGR s l a ) -> GDAL s a\nrunOGR (OGR a) = a\n\nliftOGR :: GDAL s a -> OGR s l a\nliftOGR = OGR\n\ntype OGRConduit s l i o = Conduit i (OGR s l) o\ntype OGRSource s l o = Source (OGR s l) o\ntype OGRSink s l i = Sink i (OGR s l)\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s l (t::AccessMode) a) = Layer (ReleaseKey, LayerH)\n\nunLayer :: Layer s l t a -> LayerH\nunLayer (Layer (_,l)) = l\n\ncloseLayer :: MonadIO m => Layer s l t a -> m ()\ncloseLayer (Layer (rk,_)) = release rk\n\ntype ROLayer s l = Layer s l ReadOnly\ntype RWLayer s l = Layer s l ReadWrite\n\nunsafeToReadOnlyLayer :: RWLayer s l a -> ROLayer s l a\nunsafeToReadOnlyLayer = coerce\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = unsafeUseAsCString \"SQLITE\\0\"\nwithSQLDialect OGRDialect = unsafeUseAsCString \"OGRSQL\\0\"\n\n\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it to the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> maybeNewSpatialRefBorrowedHandle\n ({#call unsafe OGR_L_GetSpatialRef as ^#} p)\n <*> pure True\n\nlayerSpatialReference :: Layer s l a t -> GDAL s (Maybe SpatialReference)\nlayerSpatialReference\n = liftIO\n . maybeNewSpatialRefBorrowedHandle\n . {#call unsafe OGR_L_GetSpatialRef as ^#}\n . unLayer\n\n\nsyncLayerToDiskIO :: RWLayer s l a -> IO ()\nsyncLayerToDiskIO =\n checkOGRError \"syncLayerToDisk\" . {#call OGR_L_SyncToDisk as ^#} . unLayer\n\nsyncLayerToDisk :: RWLayer s l a -> GDAL s ()\nsyncLayerToDisk = liftIO . syncLayerToDiskIO\n\ngetLayerSchema :: LayerH -> IO FeatureDefnH\ngetLayerSchema = {#call OGR_L_GetLayerDefn as ^#}\n\ncreateFeatureWithFidIO\n :: OGRFeature a => LayerH -> Maybe Fid -> a -> IO (Maybe Fid)\ncreateFeatureWithFidIO pL fid feat = do\n pFd <- getLayerSchema pL\n featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" ({#call OGR_L_CreateFeature as ^#} pL pF)\n getFid pF\n\ncreateFeatureWithFid\n :: OGRFeature a => RWLayer s l a -> Maybe Fid -> a -> GDAL s (Maybe Fid)\ncreateFeatureWithFid layer fid =\n liftIO . createFeatureWithFidIO (unLayer layer) fid\n\ncreateFeature :: OGRFeature a => RWLayer s l a -> a -> GDAL s Fid\ncreateFeature layer =\n createFeatureWithFid layer Nothing >=>\n maybe (throwBindingException UnexpectedNullFid) return\n\ncreateFeature_ :: OGRFeature a => RWLayer s l a -> a -> GDAL s ()\ncreateFeature_ layer = void . createFeatureWithFid layer Nothing\n\nupdateFeature :: OGRFeature a => RWLayer s l a -> Fid -> a -> GDAL s ()\nupdateFeature layer fid feat = liftIO $ do\n pFd <- getLayerSchema pL\n featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} pL\n where pL = unLayer layer\n\ngetFeature :: OGRFeature a => Layer s l t a -> Fid -> GDAL s (Maybe a)\ngetFeature layer (Fid fid) = liftIO $ do\n when (not (pL `layerHasCapability` RandomRead)) $\n throwBindingException (UnsupportedLayerCapability RandomRead)\n fDef <- layerFeatureDefIO pL\n liftM (fmap snd) $ featureFromHandle fDef $\n checkGDALCall checkIt ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n where\n checkIt (Just GDALException{gdalErrNum=AppDefined}) _ = Nothing\n checkIt e _ = e\n pL = unLayer layer\n\ndeleteFeature :: Layer s l t a -> Fid -> GDAL s ()\ndeleteFeature layer (Fid fid) = liftIO $\n checkOGRError \"DeleteFeature\" $\n {#call OGR_L_DeleteFeature as ^#} (unLayer layer) (fromIntegral fid)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\nlayerName :: Layer s l t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerExtent :: Layer s l t a -> GDAL s EnvelopeReal\nlayerExtent l = liftIO $ alloca $ \\pE -> do\n checkOGRError \"GetExtent\" ({#call OGR_L_GetExtent as ^#} (unLayer l) pE 1)\n peek pE\n\nlayerFeatureDef :: Layer s l t a -> GDAL s FeatureDef\nlayerFeatureDef = liftIO . layerFeatureDefIO . unLayer\n\nlayerFeatureDefIO :: LayerH -> IO FeatureDef\nlayerFeatureDefIO pL = do\n gfd <- layerGeomFieldDef pL\n getLayerSchema pL >>= featureDefFromHandle gfd\n\nlayerFeatureCount :: Layer s l t a -> Bool -> GDAL s (Maybe Int)\nlayerFeatureCount layer force = liftIO $ do\n c <- liftM fromIntegral $\n {#call OGR_L_GetFeatureCount as ^#} (unLayer layer) (fromBool force)\n if c<0 then return Nothing else return (Just c)\n\nlayerSpatialFilter :: Layer s l t a -> GDAL s (Maybe Geometry)\nlayerSpatialFilter l = liftIO $\n {#call unsafe OGR_L_GetSpatialFilter as ^#} (unLayer l) >>= maybeCloneGeometry\n\nsetLayerSpatialFilter :: Layer s l t a -> Geometry -> GDAL s ()\nsetLayerSpatialFilter l g = liftIO $\n withGeometry g $ {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l)\n\nclearLayerSpatialFilter :: Layer s l t a -> GDAL s ()\nclearLayerSpatialFilter l = liftIO $\n {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l) (nullPtr)\n\nsetLayerSpatialFilterRect :: Layer s l t a -> EnvelopeReal -> GDAL s ()\nsetLayerSpatialFilterRect l (Envelope (x0 :+: y0) (x1 :+: y1)) = liftIO $\n {#call unsafe OGR_L_SetSpatialFilterRect as ^#} (unLayer l)\n (realToFrac x0)\n (realToFrac y0)\n (realToFrac x1)\n (realToFrac y1)\n\nsourceLayer\n :: (HasLayerTransaction t, OGRFeature a)\n => GDAL s (Layer s l t a)\n -> OGRSource s l (Maybe Fid, a)\nsourceLayer alloc = layerTransaction alloc' loop\n where\n alloc' = do\n l <- alloc\n liftIO $ {#call OGR_L_ResetReading as ^#} (unLayer l)\n fDef <- layerFeatureDef l\n return (l, fDef)\n\n loop seed = do\n next <- liftIO $\n featureFromHandle (snd seed) $\n {#call OGR_L_GetNextFeature as ^#} (unLayer (fst seed))\n case next of\n Just v -> yield v >> loop seed\n Nothing -> return ()\n\nsourceLayer_\n :: (HasLayerTransaction t, OGRFeature a)\n => GDAL s (Layer s l t a) -> OGRSource s l a\nsourceLayer_ = (=$= (CL.map snd)) . sourceLayer\n\n\nconduitInsertLayer\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l (Maybe Fid, a) (Maybe Fid)\nconduitInsertLayer = flip conduitFromLayer createIt\n where\n createIt (l, pFd) = awaitForever $ \\(fid, feat) -> do\n fid' <- liftIO $ featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" $\n {#call OGR_L_CreateFeature as ^#} (unLayer l) pF\n getFid pF\n yield fid'\n\nconduitInsertLayer_\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l a (Maybe Fid)\nconduitInsertLayer_ = (CL.map (\\i->(Nothing,i)) =$=) . conduitInsertLayer\n\nsinkInsertLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Maybe Fid, a) ()\nsinkInsertLayer = (=$= CL.sinkNull) . conduitInsertLayer\n\nsinkInsertLayer_\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l a ()\nsinkInsertLayer_ =\n ((=$= CL.sinkNull) . ((CL.map (\\i->(Nothing,i))) =$=)) . conduitInsertLayer\n\nsinkUpdateLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Fid, a) ()\nsinkUpdateLayer = flip conduitFromLayer updateIt\n where\n updateIt (l, pFd) = awaitForever $ \\(fid, feat) ->\n liftIO $ featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} (unLayer l)\n\nclass HasLayerTransaction (t :: AccessMode) where\n layerTransaction\n :: GDAL s (Layer s l t a, e)\n -> ((Layer s l t a, e) -> OGRConduit s l i o)\n -> OGRConduit s l i o\n\ninstance HasLayerTransaction ReadWrite where\n layerTransaction alloc inside = do\n state <- lift (liftOGR getInternalState)\n bracketP (alloc' state) free $ \\ seed@(layer,_) -> do\n liftIO $ checkOGRError \"StartTransaction\" $\n {#call OGR_L_StartTransaction as ^#} (unLayer layer)\n\n res <-\n inside seed `catchC`\n \\(e :: SomeException) -> rollback layer >> throwM e\n commit layer\n pure res\n where\n alloc' = runWithInternalState alloc\n free = closeLayer . fst\n commit layer = liftIO $ do\n checkOGRError \"CommitTransaction\" $\n {#call OGR_L_CommitTransaction as ^#} (unLayer layer)\n syncLayerToDiskIO layer\n\n rollback layer = liftIO $\n checkOGRError \"RollbackTransaction\" $\n {#call OGR_L_RollbackTransaction as ^#} (unLayer layer)\n\ninstance HasLayerTransaction ReadOnly where\n layerTransaction alloc inside = do\n state <- lift (liftOGR getInternalState)\n bracketP (alloc' state) free $ \\ seed -> do\n liftIO $ checkOGRError \"StartTransaction\" $\n {#call OGR_L_StartTransaction as ^#} (unLayer (fst seed))\n inside seed\n where\n free = closeLayer . fst\n alloc' = runWithInternalState alloc\n\n\nconduitFromLayer\n :: GDAL s (RWLayer s l a)\n -> ((RWLayer s l a, FeatureDefnH) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nconduitFromLayer alloc = layerTransaction alloc'\n where\n alloc' = do\n l <- alloc\n schema <- liftIO $ getLayerSchema (unLayer l)\n return (l, schema)\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if SUPPORTS_MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n\n#include \"bindings.h\"\n#include \"gdal.h\"\n#include \"ogr_api.h\"\n\nmodule GDAL.Internal.Layer (\n HasLayerTransaction\n , SQLDialect (..)\n , Layer (..)\n , LayerH (..)\n , ROLayer\n , RWLayer\n , OGR\n , OGRConduit\n , OGRSource\n , OGRSink\n , runOGR\n\n , canCreateMultipleGeometryFields\n\n , sourceLayer\n , sourceLayer_\n , conduitInsertLayer\n , conduitInsertLayer_\n , sinkInsertLayer\n , sinkInsertLayer_\n , sinkUpdateLayer\n\n , syncLayerToDisk\n\n , layerSpatialFilter\n , layerSpatialReference\n , setLayerSpatialFilter\n , setLayerSpatialFilterRect\n , clearLayerSpatialFilter\n\n , layerName\n , layerExtent\n , layerFeatureCount\n , layerFeatureDef\n\n , createFeature\n , createFeatureWithFid\n , createFeature_\n , getFeature\n , updateFeature\n , deleteFeature\n\n , unsafeToReadOnlyLayer\n\n , liftOGR\n , closeLayer\n , unLayer\n , layerHasCapability\n , nullLayerH\n , withSQLDialect\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport Data.Conduit ( Conduit, Sink, Source\n , addCleanup, awaitForever, yield\n , bracketP, catchC\n , (=$=))\nimport qualified Data.Conduit.List as CL\nimport Data.Text (Text)\n\nimport Control.Applicative (Applicative, (<$>), (<*>), pure)\nimport Control.Exception (SomeException)\nimport Control.Monad (liftM, when, void, (>=>), (<=<))\nimport Control.Monad.Base (MonadBase)\nimport Control.Monad.Catch (\n MonadThrow(..)\n , MonadCatch\n , MonadMask\n )\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Control (MonadBaseControl(..))\nimport Control.Monad.Trans.Resource (MonadResource)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, withCString)\nimport Foreign.C.Types (CInt(..), CDouble(..))\nimport Foreign.Ptr (nullPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport Foreign.Storable (Storable, peek)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n\n-- A phantom-typed ST-like monad to make sure the layer does not escape its\n-- scope\nnewtype OGR s l a = OGR { unOGR :: GDAL s a}\n\nderiving instance Functor (OGR s l)\nderiving instance Applicative (OGR s l)\nderiving instance Monad (OGR s l)\nderiving instance MonadIO (OGR s l)\nderiving instance MonadThrow (OGR s l)\nderiving instance MonadCatch (OGR s l)\nderiving instance MonadMask (OGR s l)\nderiving instance MonadBase IO (OGR s l)\nderiving instance MonadResource (OGR s l)\n\ninstance MonadBaseControl IO (OGR s l) where\n type StM (OGR s l) a = a\n liftBaseWith runInBase = OGR $ do\n state <- getInternalState\n liftIO $ runInBase ((`runWithInternalState` state) . unOGR)\n restoreM = return\n\nrunOGR :: (forall l. OGR s l a ) -> GDAL s a\nrunOGR (OGR a) = a\n\nliftOGR :: GDAL s a -> OGR s l a\nliftOGR = OGR\n\ntype OGRConduit s l i o = Conduit i (OGR s l) o\ntype OGRSource s l o = Source (OGR s l) o\ntype OGRSink s l i = Sink i (OGR s l)\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s l (t::AccessMode) a) = Layer (ReleaseKey, LayerH)\n\nunLayer :: Layer s l t a -> LayerH\nunLayer (Layer (_,l)) = l\n\ncloseLayer :: MonadIO m => Layer s l t a -> m ()\ncloseLayer (Layer (rk,_)) = release rk\n\ntype ROLayer s l = Layer s l ReadOnly\ntype RWLayer s l = Layer s l ReadWrite\n\nunsafeToReadOnlyLayer :: RWLayer s l a -> ROLayer s l a\nunsafeToReadOnlyLayer = coerce\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = unsafeUseAsCString \"SQLITE\\0\"\nwithSQLDialect OGRDialect = unsafeUseAsCString \"OGRSQL\\0\"\n\n\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it to the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> maybeNewSpatialRefBorrowedHandle\n ({#call unsafe OGR_L_GetSpatialRef as ^#} p)\n <*> pure True\n\nlayerSpatialReference :: Layer s l a t -> GDAL s (Maybe SpatialReference)\nlayerSpatialReference\n = liftIO\n . maybeNewSpatialRefBorrowedHandle\n . {#call unsafe OGR_L_GetSpatialRef as ^#}\n . unLayer\n\n\nsyncLayerToDiskIO :: RWLayer s l a -> IO ()\nsyncLayerToDiskIO =\n checkOGRError \"syncLayerToDisk\" . {#call OGR_L_SyncToDisk as ^#} . unLayer\n\nsyncLayerToDisk :: RWLayer s l a -> GDAL s ()\nsyncLayerToDisk = liftIO . syncLayerToDiskIO\n\ngetLayerSchema :: LayerH -> IO FeatureDefnH\ngetLayerSchema = {#call OGR_L_GetLayerDefn as ^#}\n\ncreateFeatureWithFidIO\n :: OGRFeature a => LayerH -> Maybe Fid -> a -> IO (Maybe Fid)\ncreateFeatureWithFidIO pL fid feat = do\n pFd <- getLayerSchema pL\n featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" ({#call OGR_L_CreateFeature as ^#} pL pF)\n getFid pF\n\ncreateFeatureWithFid\n :: OGRFeature a => RWLayer s l a -> Maybe Fid -> a -> GDAL s (Maybe Fid)\ncreateFeatureWithFid layer fid =\n liftIO . createFeatureWithFidIO (unLayer layer) fid\n\ncreateFeature :: OGRFeature a => RWLayer s l a -> a -> GDAL s Fid\ncreateFeature layer =\n createFeatureWithFid layer Nothing >=>\n maybe (throwBindingException UnexpectedNullFid) return\n\ncreateFeature_ :: OGRFeature a => RWLayer s l a -> a -> GDAL s ()\ncreateFeature_ layer = void . createFeatureWithFid layer Nothing\n\nupdateFeature :: OGRFeature a => RWLayer s l a -> Fid -> a -> GDAL s ()\nupdateFeature layer fid feat = liftIO $ do\n pFd <- getLayerSchema pL\n featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} pL\n where pL = unLayer layer\n\ngetFeature :: OGRFeature a => Layer s l t a -> Fid -> GDAL s (Maybe a)\ngetFeature layer (Fid fid) = liftIO $ do\n when (not (pL `layerHasCapability` RandomRead)) $\n throwBindingException (UnsupportedLayerCapability RandomRead)\n fDef <- layerFeatureDefIO pL\n liftM (fmap snd) $ featureFromHandle fDef $\n checkGDALCall checkIt ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n where\n checkIt (Just GDALException{gdalErrNum=AppDefined}) _ = Nothing\n checkIt e _ = e\n pL = unLayer layer\n\ndeleteFeature :: Layer s l t a -> Fid -> GDAL s ()\ndeleteFeature layer (Fid fid) = liftIO $\n checkOGRError \"DeleteFeature\" $\n {#call OGR_L_DeleteFeature as ^#} (unLayer layer) (fromIntegral fid)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\nlayerName :: Layer s l t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerExtent :: Layer s l t a -> GDAL s EnvelopeReal\nlayerExtent l = liftIO $ alloca $ \\pE -> do\n checkOGRError \"GetExtent\" ({#call OGR_L_GetExtent as ^#} (unLayer l) pE 1)\n peek pE\n\nlayerFeatureDef :: Layer s l t a -> GDAL s FeatureDef\nlayerFeatureDef = liftIO . layerFeatureDefIO . unLayer\n\nlayerFeatureDefIO :: LayerH -> IO FeatureDef\nlayerFeatureDefIO pL = do\n gfd <- layerGeomFieldDef pL\n getLayerSchema pL >>= featureDefFromHandle gfd\n\nlayerFeatureCount :: Layer s l t a -> Bool -> GDAL s (Maybe Int)\nlayerFeatureCount layer force = liftIO $ do\n c <- liftM fromIntegral $\n {#call OGR_L_GetFeatureCount as ^#} (unLayer layer) (fromBool force)\n if c<0 then return Nothing else return (Just c)\n\nlayerSpatialFilter :: Layer s l t a -> GDAL s (Maybe Geometry)\nlayerSpatialFilter l = liftIO $\n {#call unsafe OGR_L_GetSpatialFilter as ^#} (unLayer l) >>= maybeCloneGeometry\n\nsetLayerSpatialFilter :: Layer s l t a -> Geometry -> GDAL s ()\nsetLayerSpatialFilter l g = liftIO $\n withGeometry g $ {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l)\n\nclearLayerSpatialFilter :: Layer s l t a -> GDAL s ()\nclearLayerSpatialFilter l = liftIO $\n {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l) (nullPtr)\n\nsetLayerSpatialFilterRect :: Layer s l t a -> EnvelopeReal -> GDAL s ()\nsetLayerSpatialFilterRect l (Envelope (x0 :+: y0) (x1 :+: y1)) = liftIO $\n {#call unsafe OGR_L_SetSpatialFilterRect as ^#} (unLayer l)\n (realToFrac x0)\n (realToFrac y0)\n (realToFrac x1)\n (realToFrac y1)\n\nsourceLayer\n :: (HasLayerTransaction t, OGRFeature a)\n => GDAL s (Layer s l t a)\n -> OGRSource s l (Maybe Fid, a)\nsourceLayer alloc = layerTransaction alloc' loop\n where\n alloc' = do\n l <- alloc\n liftIO $ {#call OGR_L_ResetReading as ^#} (unLayer l)\n fDef <- layerFeatureDef l\n return (l, fDef)\n\n loop seed = do\n next <- liftIO $\n featureFromHandle (snd seed) $\n {#call OGR_L_GetNextFeature as ^#} (unLayer (fst seed))\n case next of\n Just v -> yield v >> loop seed\n Nothing -> return ()\n\nsourceLayer_\n :: (HasLayerTransaction t, OGRFeature a)\n => GDAL s (Layer s l t a) -> OGRSource s l a\nsourceLayer_ = (=$= (CL.map snd)) . sourceLayer\n\n\nconduitInsertLayer\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l (Maybe Fid, a) (Maybe Fid)\nconduitInsertLayer = flip conduitFromLayer createIt\n where\n createIt (l, pFd) = awaitForever $ \\(fid, feat) -> do\n fid' <- liftIO $ featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" $\n {#call OGR_L_CreateFeature as ^#} (unLayer l) pF\n getFid pF\n yield fid'\n\nconduitInsertLayer_\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l a (Maybe Fid)\nconduitInsertLayer_ = (CL.map (\\i->(Nothing,i)) =$=) . conduitInsertLayer\n\nsinkInsertLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Maybe Fid, a) ()\nsinkInsertLayer = (=$= CL.sinkNull) . conduitInsertLayer\n\nsinkInsertLayer_\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l a ()\nsinkInsertLayer_ =\n ((=$= CL.sinkNull) . ((CL.map (\\i->(Nothing,i))) =$=)) . conduitInsertLayer\n\nsinkUpdateLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Fid, a) ()\nsinkUpdateLayer = flip conduitFromLayer updateIt\n where\n updateIt (l, pFd) = awaitForever $ \\(fid, feat) ->\n liftIO $ featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} (unLayer l)\n\nclass HasLayerTransaction (t :: AccessMode) where\n layerTransaction\n :: GDAL s (Layer s l t a, e)\n -> ((Layer s l t a, e) -> OGRConduit s l i o)\n -> OGRConduit s l i o\n\ninstance HasLayerTransaction ReadWrite where\n layerTransaction alloc inside = do\n state <- lift (liftOGR getInternalState)\n bracketP (alloc' state) free $ \\ seed@(layer,_) -> do\n liftIO $ checkOGRError \"StartTransaction\" $\n {#call OGR_L_StartTransaction as ^#} (unLayer layer)\n addCleanup (\\terminated -> when terminated (commit layer)) $\n inside seed `catchC`\n \\(e :: SomeException) -> rollback layer >> throwM e\n where\n alloc' = runWithInternalState alloc\n free = closeLayer . fst\n commit layer = liftIO $ do\n checkOGRError \"CommitTransaction\" $\n {#call OGR_L_CommitTransaction as ^#} (unLayer layer)\n syncLayerToDiskIO layer\n\n rollback layer = liftIO $\n checkOGRError \"RollbackTransaction\" $\n {#call OGR_L_RollbackTransaction as ^#} (unLayer layer)\n\ninstance HasLayerTransaction ReadOnly where\n layerTransaction alloc inside = do\n state <- lift (liftOGR getInternalState)\n bracketP (alloc' state) free $ \\ seed -> do\n liftIO $ checkOGRError \"StartTransaction\" $\n {#call OGR_L_StartTransaction as ^#} (unLayer (fst seed))\n inside seed\n where\n free = closeLayer . fst\n alloc' = runWithInternalState alloc\n\n\nconduitFromLayer\n :: GDAL s (RWLayer s l a)\n -> ((RWLayer s l a, FeatureDefnH) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nconduitFromLayer alloc = layerTransaction alloc'\n where\n alloc' = do\n l <- alloc\n schema <- liftIO $ getLayerSchema (unLayer l)\n return (l, schema)\n\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if SUPPORTS_MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ee0a691b5116451abc3d88dcb2a60bcc5da2bd9d","subject":"fix fixed types instead of c2hs ones","message":"fix fixed types instead of c2hs ones\n","repos":"IFCA\/opencl,Delan90\/opencl,Delan90\/opencl,IFCA\/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 CLCommandQueueProperty_, getDeviceTypeValue, getDeviceLocalMemType, \n getDeviceMemCacheType, bitmaskToDeviceTypes, bitmaskFromDeviceTypes, \n bitmaskToCommandQueueProperties, bitmaskFromCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability ) \n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( Ptr )\nimport Foreign.C.Types\nimport Data.Maybe( fromMaybe, mapMaybe )\nimport Data.List( foldl' )\nimport Data.Bits( shiftL, complement, (.|.) )\nimport System.GPU.OpenCL.Util( testMask )\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#}\n\nnewtype ErrorCode = ErrorCode CInt deriving( Eq )\n\n-- -----------------------------------------------------------------------------\ndata CLDeviceType = CL_DEVICE_TYPE_CPU \n -- ^ An OpenCL device that is the host processor. The host \n -- processor runs the OpenCL implementations and is a single \n -- or multi-core CPU.\n | CL_DEVICE_TYPE_GPU\t\n -- ^ An OpenCL device that is a GPU. By this we mean that \n -- the device can also be used to accelerate a 3D API such \n -- as OpenGL or DirectX.\n | CL_DEVICE_TYPE_ACCELERATOR\t\n -- ^ Dedicated OpenCL accelerators (for example the IBM CELL \n -- Blade). These devices communicate with the host processor \n -- using a peripheral interconnect such as PCIe.\n | CL_DEVICE_TYPE_DEFAULT \n -- ^ The default OpenCL device in the system. \n | CL_DEVICE_TYPE_ALL\t\n -- ^ All OpenCL devices available in the system.\n deriving( Eq, Show )\n\ndeviceTypeValues :: [(CLDeviceType,CLDeviceType_)]\ndeviceTypeValues = [ \n (CL_DEVICE_TYPE_CPU, 1 `shiftL` 1), (CL_DEVICE_TYPE_GPU, 1 `shiftL` 2), \n (CL_DEVICE_TYPE_ACCELERATOR, 1 `shiftL` 3), (CL_DEVICE_TYPE_DEFAULT, 1 `shiftL` 0),\n (CL_DEVICE_TYPE_ALL, complement 0) ]\ngetDeviceTypeValue :: CLDeviceType -> CLDeviceType_\ngetDeviceTypeValue info = fromMaybe 0 (lookup info deviceTypeValues)\n\ndata CLCommandQueueProperty = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE\t\n -- ^ Determines whether the commands queued in the \n -- command-queue are executed in-order or \n -- out-of-order. If set, the commands in the \n -- command-queue are executed out-of-order. \n -- Otherwise, commands are executed in-order.\n | CL_QUEUE_PROFILING_ENABLE\t\n -- ^ Enable or disable profiling of commands in\n -- the command-queue. If set, the profiling of \n -- commands is enabled. Otherwise profiling of \n -- commands is disabled. See \n -- 'clGetEventProfilingInfo' for more information.\n deriving( Eq, Show )\n\ncommandQueueProperties :: [(CLCommandQueueProperty,CLCommandQueueProperty_)]\ncommandQueueProperties = [\n (CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, 1 `shiftL` 0),\n (CL_QUEUE_PROFILING_ENABLE, 1 `shiftL` 1)]\n\ndata CLDeviceFPConfig = CL_FP_DENORM -- ^ denorms are supported.\n | CL_FP_INF_NAN -- ^ INF and NaNs are supported.\n | CL_FP_ROUND_TO_NEAREST \n -- ^ round to nearest even rounding mode supported.\n | CL_FP_ROUND_TO_ZERO \n -- ^ round to zero rounding mode supported.\n | CL_FP_ROUND_TO_INF \n -- ^ round to +ve and -ve infinity rounding modes \n -- supported.\n | CL_FP_FMA \n -- ^ IEEE754-2008 fused multiply-add is supported.\n deriving( Show )\n \ndeviceFPValues :: [(CLDeviceFPConfig,CLDeviceFPConfig_)]\ndeviceFPValues = [\n (CL_FP_DENORM, 1 `shiftL` 0), (CL_FP_INF_NAN, 1 `shiftL` 1),\n (CL_FP_ROUND_TO_NEAREST, 1 `shiftL` 2), (CL_FP_ROUND_TO_ZERO, 1 `shiftL` 3),\n (CL_FP_ROUND_TO_INF, 1 `shiftL` 4), (CL_FP_FMA, 1 `shiftL` 5)]\n\ndata CLDeviceExecCapability = CL_EXEC_KERNEL \n -- ^ The OpenCL device can execute OpenCL kernels.\n | CL_EXEC_NATIVE_KERNEL\n -- ^ The OpenCL device can execute native kernels.\n deriving( Show )\n\ndeviceExecValues :: [(CLDeviceExecCapability,CLDeviceExecCapability_)]\ndeviceExecValues = [\n (CL_EXEC_KERNEL, 1 `shiftL` 0), (CL_EXEC_NATIVE_KERNEL, 1 `shiftL` 1)]\n \ndata CLDeviceMemCacheType = CL_NONE | CL_READ_ONLY_CACHE | CL_READ_WRITE_CACHE\n deriving( Show )\ndeviceMemCacheTypes :: [(CLDeviceMemCacheType_,CLDeviceMemCacheType)]\ndeviceMemCacheTypes = [\n (0x0,CL_NONE), (0x1,CL_READ_ONLY_CACHE),(0x2,CL_READ_WRITE_CACHE)]\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType val = lookup val deviceMemCacheTypes\n\ndata CLDeviceLocalMemType = CL_LOCAL | CL_GLOBAL deriving( Show )\n\ndeviceLocalMemTypes :: [(CLDeviceLocalMemType_,CLDeviceLocalMemType)]\ndeviceLocalMemTypes = [(0x1,CL_LOCAL), (0x2,CL_GLOBAL)]\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType val = lookup val deviceLocalMemTypes\n\n-- -----------------------------------------------------------------------------\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes mask = map fst . filter (testMask mask) $ deviceTypeValues\n\nbitmaskFromDeviceTypes :: [CLDeviceType] -> CLDeviceType_\nbitmaskFromDeviceTypes = foldl' (.|.) 0 . mapMaybe (`lookup` deviceTypeValues)\n \nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = map fst . filter (testMask mask) $ commandQueueProperties\n \nbitmaskFromCommandQueueProperties :: [CLCommandQueueProperty] -> CLCommandQueueProperty_\nbitmaskFromCommandQueueProperties = foldl' (.|.) 0 . mapMaybe (`lookup` commandQueueProperties)\n\nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig mask = map fst . filter (testMask mask) $ deviceFPValues\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability mask = map fst . filter (testMask mask) $ deviceExecValues\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 CLCommandQueueProperty_, getDeviceTypeValue, getDeviceLocalMemType, \n getDeviceMemCacheType, bitmaskToDeviceTypes, bitmaskFromDeviceTypes, \n bitmaskToCommandQueueProperties, bitmaskFromCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability ) \n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( Ptr )\nimport Foreign.C.Types( CUInt, CInt, CULong, CLong )\nimport Data.Maybe( fromMaybe, mapMaybe )\nimport Data.List( foldl' )\nimport Data.Bits( shiftL, complement, (.|.) )\nimport System.GPU.OpenCL.Util( testMask )\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#}\n\nnewtype ErrorCode = ErrorCode CInt deriving( Eq )\n\n-- -----------------------------------------------------------------------------\ndata CLDeviceType = CL_DEVICE_TYPE_CPU \n -- ^ An OpenCL device that is the host processor. The host \n -- processor runs the OpenCL implementations and is a single \n -- or multi-core CPU.\n | CL_DEVICE_TYPE_GPU\t\n -- ^ An OpenCL device that is a GPU. By this we mean that \n -- the device can also be used to accelerate a 3D API such \n -- as OpenGL or DirectX.\n | CL_DEVICE_TYPE_ACCELERATOR\t\n -- ^ Dedicated OpenCL accelerators (for example the IBM CELL \n -- Blade). These devices communicate with the host processor \n -- using a peripheral interconnect such as PCIe.\n | CL_DEVICE_TYPE_DEFAULT \n -- ^ The default OpenCL device in the system. \n | CL_DEVICE_TYPE_ALL\t\n -- ^ All OpenCL devices available in the system.\n deriving( Eq, Show )\n\ndeviceTypeValues :: [(CLDeviceType,CULong)]\ndeviceTypeValues = [ \n (CL_DEVICE_TYPE_CPU, 1 `shiftL` 1), (CL_DEVICE_TYPE_GPU, 1 `shiftL` 2), \n (CL_DEVICE_TYPE_ACCELERATOR, 1 `shiftL` 3), (CL_DEVICE_TYPE_DEFAULT, 1 `shiftL` 0),\n (CL_DEVICE_TYPE_ALL, complement 0) ]\ngetDeviceTypeValue :: CLDeviceType -> CULong\ngetDeviceTypeValue info = fromMaybe 0 (lookup info deviceTypeValues)\n\ndata CLCommandQueueProperty = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE\t\n -- ^ Determines whether the commands queued in the \n -- command-queue are executed in-order or \n -- out-of-order. If set, the commands in the \n -- command-queue are executed out-of-order. \n -- Otherwise, commands are executed in-order.\n | CL_QUEUE_PROFILING_ENABLE\t\n -- ^ Enable or disable profiling of commands in\n -- the command-queue. If set, the profiling of \n -- commands is enabled. Otherwise profiling of \n -- commands is disabled. See \n -- 'clGetEventProfilingInfo' for more information.\n deriving( Eq, Show )\n\ncommandQueueProperties :: [(CLCommandQueueProperty,CULong)] \ncommandQueueProperties = [\n (CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, 1 `shiftL` 0),\n (CL_QUEUE_PROFILING_ENABLE, 1 `shiftL` 1)]\n\ndata CLDeviceFPConfig = CL_FP_DENORM -- ^ denorms are supported.\n | CL_FP_INF_NAN -- ^ INF and NaNs are supported.\n | CL_FP_ROUND_TO_NEAREST \n -- ^ round to nearest even rounding mode supported.\n | CL_FP_ROUND_TO_ZERO \n -- ^ round to zero rounding mode supported.\n | CL_FP_ROUND_TO_INF \n -- ^ round to +ve and -ve infinity rounding modes \n -- supported.\n | CL_FP_FMA \n -- ^ IEEE754-2008 fused multiply-add is supported.\n deriving( Show )\n \ndeviceFPValues :: [(CLDeviceFPConfig,CLDeviceFPConfig_)]\ndeviceFPValues = [\n (CL_FP_DENORM, 1 `shiftL` 0), (CL_FP_INF_NAN, 1 `shiftL` 1),\n (CL_FP_ROUND_TO_NEAREST, 1 `shiftL` 2), (CL_FP_ROUND_TO_ZERO, 1 `shiftL` 3),\n (CL_FP_ROUND_TO_INF, 1 `shiftL` 4), (CL_FP_FMA, 1 `shiftL` 5)]\n\ndata CLDeviceExecCapability = CL_EXEC_KERNEL \n -- ^ The OpenCL device can execute OpenCL kernels.\n | CL_EXEC_NATIVE_KERNEL\n -- ^ The OpenCL device can execute native kernels.\n deriving( Show )\n\ndeviceExecValues :: [(CLDeviceExecCapability,CLDeviceExecCapability_)]\ndeviceExecValues = [\n (CL_EXEC_KERNEL, 1 `shiftL` 0), (CL_EXEC_NATIVE_KERNEL, 1 `shiftL` 1)]\n \ndata CLDeviceMemCacheType = CL_NONE | CL_READ_ONLY_CACHE | CL_READ_WRITE_CACHE\n deriving( Show )\ndeviceMemCacheTypes :: [(CLDeviceMemCacheType_,CLDeviceMemCacheType)]\ndeviceMemCacheTypes = [\n (0x0,CL_NONE), (0x1,CL_READ_ONLY_CACHE),(0x2,CL_READ_WRITE_CACHE)]\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType val = lookup val deviceMemCacheTypes\n\ndata CLDeviceLocalMemType = CL_LOCAL | CL_GLOBAL deriving( Show )\n\ndeviceLocalMemTypes :: [(CLDeviceLocalMemType_,CLDeviceLocalMemType)]\ndeviceLocalMemTypes = [(0x1,CL_LOCAL), (0x2,CL_GLOBAL)]\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType val = lookup val deviceLocalMemTypes\n\n-- -----------------------------------------------------------------------------\nbitmaskToDeviceTypes :: CULong -> [CLDeviceType]\nbitmaskToDeviceTypes mask = map fst . filter (testMask mask) $ deviceTypeValues\n\nbitmaskFromDeviceTypes :: [CLDeviceType] -> CULong\nbitmaskFromDeviceTypes = foldl' (.|.) 0 . mapMaybe (`lookup` deviceTypeValues)\n \nbitmaskToCommandQueueProperties :: CULong -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = map fst . filter (testMask mask) $ commandQueueProperties\n \nbitmaskFromCommandQueueProperties :: [CLCommandQueueProperty] -> CULong\nbitmaskFromCommandQueueProperties = foldl' (.|.) 0 . mapMaybe (`lookup` commandQueueProperties)\n\nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig mask = map fst . filter (testMask mask) $ deviceFPValues\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability mask = map fst . filter (testMask mask) $ deviceExecValues\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8a767b68403421f8ef906d79b9e2fbdfe1544891","subject":"gstreamer: M.S.G.Core.Bus documentation cleanup","message":"gstreamer: M.S.G.Core.Bus documentation cleanup","repos":"vincenthz\/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 -- | 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":"e0a925e0249b5bcc63eec38520e790f16012be15","subject":"gnomevfs: use c2hs {#enum#} for FilePermissions instead of hand coding it","message":"gnomevfs: use c2hs {#enum#} for FilePermissions instead of hand coding it\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gnomevfs\/System\/Gnome\/VFS\/Types.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Types (\n \n Handle(..),\n withHandle,\n \n Result(..),\n Error(..),\n \n OpenMode(..),\n SeekPosition(..),\n \n FileInfo(..),\n FileFlags(..),\n FileInfoFields(..),\n SetFileInfoMask(..),\n FileInfoOptions(..),\n FilePermissions(..),\n FileSize,\n FileOffset,\n FileType(..),\n InodeNumber,\n IDs,\n \n MonitorHandle(..),\n withMonitorHandle,\n MonitorCallback,\n MonitorType,\n MonitorEventType,\n \n URI(..),\n TextURI,\n newURI,\n withURI,\n ToplevelURI(..),\n newToplevelURI,\n withToplevelURI,\n URIHideOptions(..),\n \n DirectoryHandle(..),\n withDirectoryHandle,\n \n MakeURIDirs(..),\n DirectoryVisitOptions(..),\n DirectoryVisitCallback,\n DirectoryVisitResult(..),\n FindDirectoryKind(..),\n \n XferOptions(..),\n XferProgressStatus(..),\n XferOverwriteMode(..),\n XferOverwriteAction(..),\n XferErrorMode(..),\n XferErrorAction(..),\n XferPhase(..),\n XferProgressInfo(..),\n XferProgressCallback,\n XferErrorCallback,\n XferOverwriteCallback,\n XferDuplicateCallback,\n \n Cancellation(..),\n newCancellation,\n withCancellation,\n \n VolumeOpSuccessCallback,\n VolumeOpFailureCallback,\n CVolumeOpCallback,\n VolumeType(..),\n DeviceType(..),\n \n MIMEType,\n \n module System.Gnome.VFS.Hierarchy,\n \n DriveID,\n newDrive,\n withDrive,\n \n VolumeID,\n newVolume,\n withVolume,\n \n wrapVolumeMonitor,\n withVolumeMonitor\n \n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.Reader\nimport Data.ByteString (ByteString)\nimport Data.Typeable\nimport Data.Word (Word64)\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GObject#} (GObject(..),\n GObjectClass,\n toGObject,\n unsafeCastGObject)\n{#import System.Glib.GType#} (GType,\n typeInstanceIsA)\n{#import System.Gnome.VFS.Hierarchy#}\n\nimport System.Posix.Types (DeviceID, EpochTime)\n\n--------------------------------------------------------------------\n\ngTypeCast :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\ngTypeCast gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n--------------------------------------------------------------------\n\n-- | The result of a file operation.\n{# enum GnomeVFSResult as Result {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show, Typeable) #}\n\nnewtype Error = Error Result\n deriving (Show, Typeable)\n\n-- | A handle to an open file\n{# pointer *GnomeVFSHandle as Handle foreign newtype #}\nwithHandle (Handle cHandle) = withForeignPtr cHandle\n\n-- | Specifies the start position for a seek operation.\n{# enum GnomeVFSSeekPosition as SeekPosition {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n{# enum GnomeVFSOpenMode as OpenMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n--------------------------------------------------------------------\n\n-- | A record type containing information about a file.\ndata FileInfo = FileInfo {\n fileInfoName :: Maybe String, -- ^ the name of the file,\n -- without the path\n fileInfoType :: Maybe FileType, -- ^ the type of the file;\n -- i.e. regular, directory,\n -- block-device, etc.\n fileInfoPermissions :: Maybe [FilePermissions], -- ^ the permissions for the\n -- file\n fileInfoFlags :: Maybe [FileFlags], -- ^ flags providing\n -- additional information\n -- about the file\n fileInfoDevice :: Maybe DeviceID, -- ^ the device the file\n -- resides on\n fileInfoInode :: Maybe InodeNumber, -- ^ the inode number of the\n -- file\n fileInfoLinkCount :: Maybe Int, -- ^ the total number of\n -- hard links to the file\n fileInfoIDs :: Maybe IDs, -- ^ the user and group IDs\n -- owning the file\n fileInfoSize :: Maybe FileSize, -- ^ the size of the file in\n -- bytes\n fileInfoBlockCount :: Maybe FileSize, -- ^ the size of the file in\n -- filesystem blocks\n fileInfoIOBlockSize :: Maybe FileSize, -- ^ the optimal buffer size\n -- for reading from and\n -- writing to the file\n fileInfoATime :: Maybe EpochTime, -- ^ the time of last access\n fileInfoMTime :: Maybe EpochTime, -- ^ the time of last modification\n fileInfoCTime :: Maybe EpochTime, -- ^ the time of last attribute modification\n fileInfoSymlinkName :: Maybe String, -- ^ the location this\n -- symlink points to, if\n -- @fileInfoFlags@ contains 'FileFlagsSymlink'\n fileInfoMIMEType :: Maybe MIMEType -- ^ the MIME-type of the\n -- file\n } deriving (Eq, Show)\n\n{# enum GnomeVFSFileInfoFields as FileInfoFields {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Options for reading information from a file.\n{# enum GnomeVFSFileInfoOptions as FileInfoOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying additional information about a file.\n{# enum GnomeVFSFileFlags as FileFlags {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying the attributes of a file that should be changed.\n{# enum GnomeVFSSetFileInfoMask as SetFileInfoMask {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Identifies the type of a file.\n{# enum GnomeVFSFileType as FileType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ninstance Flags FileInfoOptions\ninstance Flags FileInfoFields\ninstance Flags FileFlags\ninstance Flags SetFileInfoMask\n\n-- | An integral type wide enough to hold the size of a file.\ntype FileSize = Word64\n\n-- | An integral type wide enough to hold an offset into a file.\ntype FileOffset = Word64\n\n-- | An integral type wide enough to hold the inode number of a file.\ntype InodeNumber = Word64\n\n-- | A pair holding the user ID and group ID of a file owner.\ntype IDs = (Int, Int)\n\n-- | UNIX-like permissions for a file.\n{# enum GnomeVFSFilePermissions as FilePermissions {\n GNOME_VFS_PERM_SUID as PermSUID,\n GNOME_VFS_PERM_SGID as PermSGID,\n GNOME_VFS_PERM_STICKY as PermSticky,\n GNOME_VFS_PERM_USER_READ as PermUserRead,\n GNOME_VFS_PERM_USER_WRITE as PermUserWrite,\n GNOME_VFS_PERM_USER_EXEC as PermUserExec,\n GNOME_VFS_PERM_USER_ALL as PermUserAll,\n GNOME_VFS_PERM_GROUP_READ as PermGroupRead,\n GNOME_VFS_PERM_GROUP_WRITE as PermGroupWrite,\n GNOME_VFS_PERM_GROUP_EXEC as PermGroupExec,\n GNOME_VFS_PERM_GROUP_ALL as PermGroupAll,\n GNOME_VFS_PERM_OTHER_READ as PermOtherRead,\n GNOME_VFS_PERM_OTHER_WRITE as PermOtherWrite,\n GNOME_VFS_PERM_OTHER_EXEC as PermOtherExec,\n GNOME_VFS_PERM_OTHER_ALL as PermOtherAll,\n GNOME_VFS_PERM_ACCESS_READABLE as PermAccessReadable,\n GNOME_VFS_PERM_ACCESS_WRITABLE as PermAccessWritable,\n GNOME_VFS_PERM_ACCESS_EXECUTABLE as PermAccessExecutable\n } deriving (Eq, Bounded, Show) #}\ninstance Flags FilePermissions\n\n--------------------------------------------------------------------\n\n-- | A 'URI' is a semi-textual representation of a uniform\n-- resource identifier. It contains the information about a resource\n-- location encoded as canononicalized text, but also holds extra\n-- information about the context in which the URI is used.\n{# pointer *GnomeVFSURI as URI foreign newtype #}\n\nnewURI :: Ptr URI\n -> IO URI\nnewURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr cURI cURIFinalizer\nwrapURI :: Ptr URI\n -> IO URI\nwrapURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr_ cURI\nforeign import ccall \"&gnome_vfs_uri_unref\"\n cURIFinalizer :: FunPtr (Ptr URI -> IO ())\n\nwithURI (URI cURI) = withForeignPtr cURI\n\n-- | The toplevel URI element used to access resources stored on a\n-- remote server.\n{# pointer *GnomeVFSToplevelURI as ToplevelURI foreign newtype #}\nwithToplevelURI (ToplevelURI cToplevelURI) = withForeignPtr cToplevelURI\nnewToplevelURI :: Ptr ToplevelURI\n -> IO ToplevelURI\nnewToplevelURI cToplevelURI = liftM ToplevelURI $ newForeignPtr_ cToplevelURI\n\n-- | Flags specifying which fields of a 'URI' should be hidden when\n-- converted to a string using 'uriToString'.\n{# enum GnomeVFSURIHideOptions as URIHideOptions {\n GNOME_VFS_URI_HIDE_NONE as URIHideNone,\n GNOME_VFS_URI_HIDE_USER_NAME as URIHideUserName,\n GNOME_VFS_URI_HIDE_PASSWORD as URIHidePassword,\n GNOME_VFS_URI_HIDE_HOST_NAME as URIHideHostName,\n GNOME_VFS_URI_HIDE_HOST_PORT as URIHideHostPort,\n GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD as URIHideToplevelMethod,\n GNOME_VFS_URI_HIDE_FRAGMENT_IDENTIFIER as URIHideFragmentIdentifier\n } deriving (Eq, Bounded, Show) #}\ninstance Flags URIHideOptions\n\n-- | A string that can be passed to 'uriFromString' to create a valid\n-- 'URI'.\ntype TextURI = String\n\n--------------------------------------------------------------------\n\n-- | A handle to an open directory.\n{# pointer *GnomeVFSDirectoryHandle as DirectoryHandle foreign newtype #}\nwithDirectoryHandle (DirectoryHandle cDirectoryHandle) = withForeignPtr cDirectoryHandle\n\n-- | Options controlling the way in which a directories are visited.\n{# enum GnomeVFSDirectoryVisitOptions as DirectoryVisitOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags DirectoryVisitOptions\n\n-- | A callback that will be called for each entry when passed to\n-- 'directoryVisit', 'directoryVisitURI', 'directoryVisitFiles', or\n-- 'directoryVisitFilesAtURI'.\ntype DirectoryVisitCallback = String -- ^ the path of the visited file, relative to the base directory\n -> FileInfo -- ^ the 'FileInfo' for the visited file\n -> Bool -- ^ 'True' if returning 'DirectoryVisitRecurse' will cause a loop\n -> IO DirectoryVisitResult -- ^ the next action to be taken\n\n-- | An enumerated value that must be returned from a\n-- 'DirectoryVisitCallback'. The 'directoryVisit' and related\n-- functions will perform the action specified.\ndata DirectoryVisitResult = DirectoryVisitStop -- ^ stop visiting files\n | DirectoryVisitContinue -- ^ continue as normal\n | DirectoryVisitRecurse -- ^ recursively visit the current entry\n deriving (Eq, Enum)\n\n-- | Specifies which kind of directory 'findDirectory' should look for.\n{# enum GnomeVFSFindDirectoryKind as FindDirectoryKind {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n-- | Flags that may be passed to 'makeURIFromInputWithDirs'. If the\n-- path passed is non-absolute (i.e., a relative path), the\n-- directories specified will be searched as well.\n{# enum GnomeVFSMakeURIDirs as MakeURIDirs {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags MakeURIDirs\n\n--------------------------------------------------------------------\n\n-- | A handle to a file-system monitor.\nnewtype MonitorHandle = MonitorHandle (ForeignPtr MonitorHandle, {# type GnomeVFSMonitorCallback #})\nwithMonitorHandle (MonitorHandle (monitorHandleForeignPtr, _)) = withForeignPtr monitorHandleForeignPtr\n\n-- | A callback that must be passed to 'monitorAdd'. It will be\n-- called any time a file or directory is changed.\ntype MonitorCallback = MonitorHandle -- ^ the handle to a filesystem monitor\n -> TextURI -- ^ the URI being monitored\n -> TextURI -- ^ the actual file that was modified\n -> MonitorEventType -- ^ the event that occured\n -> IO ()\n\n-- | The type of filesystem object that is to be monitored.\n{# enum GnomeVFSMonitorType as MonitorType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | The type of event that caused a 'MonitorCallback' to be called.\n{# enum GnomeVFSMonitorEventType as MonitorEventType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\nwrapMonitorHandle :: (Ptr MonitorHandle, {# type GnomeVFSMonitorCallback #})\n -> IO MonitorHandle\nwrapMonitorHandle (cMonitorHandle, cMonitorCallback) =\n do monitorHandleForeignPtr <- newForeignPtr_ cMonitorHandle\n return $ MonitorHandle (monitorHandleForeignPtr, cMonitorCallback)\n\n--------------------------------------------------------------------\n\n-- | Options controlling how the 'System.Gnome.VFS.Xfer.xferURI' and related functions behave.\n{# enum GnomeVFSXferOptions as XferOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags XferOptions\n\n{# enum GnomeVFSXferProgressStatus as XferProgressStatus {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteMode as XferOverwriteMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteAction as XferOverwriteAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorMode as XferErrorMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorAction as XferErrorAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferPhase as XferPhase {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ndata XferProgressInfo = XferProgressInfo {\n xferProgressInfoVFSStatus :: Result, -- ^ current VFS status\n xferProgressInfoPhase :: XferPhase, -- ^ phase of the transfer\n xferProgressInfoSourceName :: Maybe String, -- ^ currently transferring source URI\n xferProgressInfoTargetName :: Maybe String, -- ^ currently transferring target URI\n xferProgressInfoFileIndex :: Word, -- ^ index of the file currently being transferred\n xferProgressInfoFilesTotal :: Word, -- ^ total number of files being transferred\n xferProgressInfoBytesTotal :: FileSize, -- ^ total size of all files in bytes\n xferProgressInfoFileSize :: FileSize, -- ^ size of the file currently being transferred\n xferProgressInfoBytesCopied :: FileSize, -- ^ number of bytes already transferred in the current file\n xferProgressInfoTotalBytesCopied :: FileSize, -- ^ total number of bytes already transferred\n xferProgressInfoTopLevelItem :: Bool -- ^ 'True' if the file being transferred is a top-level item;\n -- 'False' if it is inside a directory\n } deriving (Eq)\n\n-- | The type of the first callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI' and related functions. This\n-- callback will be called periodically during transfers that are\n-- progressing normally.\ntype XferProgressCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO Bool -- ^ return 'Prelude.False' to abort the transfer, 'Prelude.True' otherwise.\n\n-- | The type of the second callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- whenever an error occurs.\ntype XferErrorCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferErrorAction -- ^ the action to be performed in response to the error\n\n-- | The type of the third callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a file would be overwritten.\ntype XferOverwriteCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferOverwriteAction -- ^ the action to be performed when the target file already exists\n\n-- | The type of the fourth callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a duplicate filename is found.\ntype XferDuplicateCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> String -- ^ @duplicateName@ - the name of the target file\n -> Int -- ^ @duplicateCount@ - the number of duplicates that exist\n -> IO (Maybe String) -- ^ the new filename that should be used, or 'Prelude.Nothing' to abort.\n\n--------------------------------------------------------------------\n\n-- | An object that can be used for signalling cancellation of an\n-- operation.\n{# pointer *GnomeVFSCancellation as Cancellation foreign newtype #}\n\nnewCancellation :: Ptr Cancellation\n -> IO Cancellation\nnewCancellation cCancellationPtr | cCancellationPtr \/= nullPtr =\n liftM Cancellation $ newForeignPtr cCancellationPtr cancellationFinalizer\nforeign import ccall unsafe \"&gnome_vfs_cancellation_destroy\"\n cancellationFinalizer :: FunPtr (Ptr Cancellation -> IO ())\nwithCancellation (Cancellation cCancellation) = withForeignPtr cCancellation\n\n--------------------------------------------------------------------\n\nwithVolume (Volume cVolume) = withForeignPtr cVolume\nnewVolume :: Ptr Volume\n -> IO Volume\nnewVolume cVolume | cVolume \/= nullPtr =\n liftM Volume $ newForeignPtr cVolume volumeFinalizer\nforeign import ccall unsafe \"&gnome_vfs_volume_unref\"\n volumeFinalizer :: FunPtr (Ptr Volume -> IO ())\n\n-- | An action to be performed when a volume operation completes successfully.\ntype VolumeOpSuccessCallback = IO ()\n-- | An action to be performed when a volume operation fails.\ntype VolumeOpFailureCallback = String\n -> String\n -> IO ()\n\n-- | Identifies the device type of a 'Volume' or 'Drive'.\n{#enum GnomeVFSDeviceType as DeviceType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n-- | Identifies the type of a 'Volume'.\n{#enum GnomeVFSVolumeType as VolumeType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ntype CVolumeOpCallback = {# type gboolean #}\n -> CString\n -> CString\n -> Ptr ()\n -> IO ()\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Drive'\ntype DriveID = {# type gulong #}\n\nwithDrive (Drive cDrive) = withForeignPtr cDrive\nnewDrive :: Ptr Drive\n -> IO Drive\nnewDrive cDrive | cDrive \/= nullPtr =\n liftM Drive $ newForeignPtr cDrive driveFinalizer\nforeign import ccall unsafe \"&gnome_vfs_drive_unref\"\n driveFinalizer :: FunPtr (Ptr Drive -> IO ())\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Volume'.\ntype VolumeID = {# type gulong #}\n\nwithVolumeMonitor (VolumeMonitor cVolumeMonitor) = withForeignPtr cVolumeMonitor\nwrapVolumeMonitor :: Ptr VolumeMonitor\n -> IO VolumeMonitor\nwrapVolumeMonitor cVolumeMonitor | cVolumeMonitor \/= nullPtr =\n liftM VolumeMonitor $ newForeignPtr_ cVolumeMonitor\n\n--------------------------------------------------------------------\n\n-- | A string that will be treated as a MIME-type.\ntype MIMEType = String\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-- #hide\n\n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Types (\n \n Handle(..),\n withHandle,\n \n Result(..),\n Error(..),\n \n OpenMode(..),\n SeekPosition(..),\n \n FileInfo(..),\n FileFlags(..),\n FileInfoFields(..),\n SetFileInfoMask(..),\n FileInfoOptions(..),\n FilePermissions(..),\n FileSize,\n FileOffset,\n FileType(..),\n InodeNumber,\n IDs,\n \n MonitorHandle(..),\n withMonitorHandle,\n MonitorCallback,\n MonitorType,\n MonitorEventType,\n \n URI(..),\n TextURI,\n newURI,\n withURI,\n ToplevelURI(..),\n newToplevelURI,\n withToplevelURI,\n URIHideOptions(..),\n \n DirectoryHandle(..),\n withDirectoryHandle,\n \n MakeURIDirs(..),\n DirectoryVisitOptions(..),\n DirectoryVisitCallback,\n DirectoryVisitResult(..),\n FindDirectoryKind(..),\n \n XferOptions(..),\n XferProgressStatus(..),\n XferOverwriteMode(..),\n XferOverwriteAction(..),\n XferErrorMode(..),\n XferErrorAction(..),\n XferPhase(..),\n XferProgressInfo(..),\n XferProgressCallback,\n XferErrorCallback,\n XferOverwriteCallback,\n XferDuplicateCallback,\n \n Cancellation(..),\n newCancellation,\n withCancellation,\n \n VolumeOpSuccessCallback,\n VolumeOpFailureCallback,\n CVolumeOpCallback,\n VolumeType(..),\n DeviceType(..),\n \n MIMEType,\n \n module System.Gnome.VFS.Hierarchy,\n \n DriveID,\n newDrive,\n withDrive,\n \n VolumeID,\n newVolume,\n withVolume,\n \n wrapVolumeMonitor,\n withVolumeMonitor\n \n ) where\n\nimport Control.Exception (assert)\nimport Control.Monad\nimport Control.Monad.Reader\nimport Data.ByteString (ByteString)\nimport Data.Typeable\nimport Data.Word (Word64)\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GObject#} (GObject(..),\n GObjectClass,\n toGObject,\n unsafeCastGObject)\n{#import System.Glib.GType#} (GType,\n typeInstanceIsA)\n{#import System.Gnome.VFS.Hierarchy#}\n\nimport System.Posix.Types (DeviceID, EpochTime)\n\n--------------------------------------------------------------------\n\ngTypeCast :: (GObjectClass obj, GObjectClass obj') => GType -> String\n -> (obj -> obj')\n-- The usage of foreignPtrToPtr should be safe as the evaluation will only be\n-- forced if the object is used afterwards\ngTypeCast gtype objTypeName obj =\n case toGObject obj of\n gobj@(GObject objFPtr)\n | typeInstanceIsA ((unsafeForeignPtrToPtr.castForeignPtr) objFPtr) gtype\n -> unsafeCastGObject gobj\n | otherwise -> error $ \"Cannot cast object to \" ++ objTypeName\n\n--------------------------------------------------------------------\n\n-- | The result of a file operation.\n{# enum GnomeVFSResult as Result {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show, Typeable) #}\n\nnewtype Error = Error Result\n deriving (Show, Typeable)\n\n-- | A handle to an open file\n{# pointer *GnomeVFSHandle as Handle foreign newtype #}\nwithHandle (Handle cHandle) = withForeignPtr cHandle\n\n-- | Specifies the start position for a seek operation.\n{# enum GnomeVFSSeekPosition as SeekPosition {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n{# enum GnomeVFSOpenMode as OpenMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n--------------------------------------------------------------------\n\n-- | A record type containing information about a file.\ndata FileInfo = FileInfo {\n fileInfoName :: Maybe String, -- ^ the name of the file,\n -- without the path\n fileInfoType :: Maybe FileType, -- ^ the type of the file;\n -- i.e. regular, directory,\n -- block-device, etc.\n fileInfoPermissions :: Maybe [FilePermissions], -- ^ the permissions for the\n -- file\n fileInfoFlags :: Maybe [FileFlags], -- ^ flags providing\n -- additional information\n -- about the file\n fileInfoDevice :: Maybe DeviceID, -- ^ the device the file\n -- resides on\n fileInfoInode :: Maybe InodeNumber, -- ^ the inode number of the\n -- file\n fileInfoLinkCount :: Maybe Int, -- ^ the total number of\n -- hard links to the file\n fileInfoIDs :: Maybe IDs, -- ^ the user and group IDs\n -- owning the file\n fileInfoSize :: Maybe FileSize, -- ^ the size of the file in\n -- bytes\n fileInfoBlockCount :: Maybe FileSize, -- ^ the size of the file in\n -- filesystem blocks\n fileInfoIOBlockSize :: Maybe FileSize, -- ^ the optimal buffer size\n -- for reading from and\n -- writing to the file\n fileInfoATime :: Maybe EpochTime, -- ^ the time of last access\n fileInfoMTime :: Maybe EpochTime, -- ^ the time of last modification\n fileInfoCTime :: Maybe EpochTime, -- ^ the time of last attribute modification\n fileInfoSymlinkName :: Maybe String, -- ^ the location this\n -- symlink points to, if\n -- @fileInfoFlags@ contains 'FileFlagsSymlink'\n fileInfoMIMEType :: Maybe MIMEType -- ^ the MIME-type of the\n -- file\n } deriving (Eq, Show)\n\n{# enum GnomeVFSFileInfoFields as FileInfoFields {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Options for reading information from a file.\n{# enum GnomeVFSFileInfoOptions as FileInfoOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying additional information about a file.\n{# enum GnomeVFSFileFlags as FileFlags {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Flags specifying the attributes of a file that should be changed.\n{# enum GnomeVFSSetFileInfoMask as SetFileInfoMask {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | Identifies the type of a file.\n{# enum GnomeVFSFileType as FileType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ninstance Flags FileInfoOptions\ninstance Flags FileInfoFields\ninstance Flags FileFlags\ninstance Flags SetFileInfoMask\n\n-- | An integral type wide enough to hold the size of a file.\ntype FileSize = Word64\n\n-- | An integral type wide enough to hold an offset into a file.\ntype FileOffset = Word64\n\n-- | An integral type wide enough to hold the inode number of a file.\ntype InodeNumber = Word64\n\n-- | A pair holding the user ID and group ID of a file owner.\ntype IDs = (Int, Int)\n\n-- | UNIX-like permissions for a file.\ndata FilePermissions = PermSUID -- ^ the set-user-ID bit\n | PermSGID -- ^ the set-group-ID bit\n | PermSticky -- ^ the \\\"sticky\\\" bit\n | PermUserRead -- ^ owner read permission\n | PermUserWrite -- ^ owner write permission\n | PermUserExec -- ^ owner execute permission\n | PermUserAll -- ^ equivalent to\n -- @['PermUserRead', 'PermUserWrite', 'PermUserExec']@\n | PermGroupRead -- ^ group read permission\n | PermGroupWrite -- ^ group write permission\n | PermGroupExec -- ^ group execute permission\n | PermGroupAll -- ^ equivalent to\n -- @['PermGroupRead', 'PermGroupWrite', 'PermGroupExec']@\n | PermOtherRead -- ^ world read permission\n | PermOtherWrite -- ^ world write permission\n | PermOtherExec -- ^ world execute permission\n | PermOtherAll -- ^ equivalent to\n -- @['PermOtherRead', 'PermOtherWrite', 'PermOtherExec']@\n | PermAccessReadable -- ^ readable by the current process\n | PermAccessWritable -- ^ writable by the current process\n | PermAccessExecutable -- ^ executable by the current process\n deriving (Eq, Bounded, Show)\ninstance Flags FilePermissions\ninstance Enum FilePermissions where\n fromEnum PermSUID = 2048\n fromEnum PermSGID = 1024\n fromEnum PermSticky = 512\n fromEnum PermUserRead = 256\n fromEnum PermUserWrite = 128\n fromEnum PermUserExec = 64\n fromEnum PermUserAll = 448\n fromEnum PermGroupRead = 32\n fromEnum PermGroupWrite = 16\n fromEnum PermGroupExec = 8\n fromEnum PermGroupAll = 56\n fromEnum PermOtherRead = 4\n fromEnum PermOtherWrite = 2\n fromEnum PermOtherExec = 1\n fromEnum PermOtherAll = 7\n fromEnum PermAccessReadable = 65536\n fromEnum PermAccessWritable = 131072\n fromEnum PermAccessExecutable = 262144\n \n toEnum 2048 = PermSUID\n toEnum 1024 = PermSGID\n toEnum 512 = PermSticky\n toEnum 256 = PermUserRead\n toEnum 128 = PermUserWrite\n toEnum 64 = PermUserExec\n toEnum 448 = PermUserAll\n toEnum 32 = PermGroupRead\n toEnum 16 = PermGroupWrite\n toEnum 8 = PermGroupExec\n toEnum 56 = PermGroupAll\n toEnum 4 = PermOtherRead\n toEnum 2 = PermOtherWrite\n toEnum 1 = PermOtherExec\n toEnum 7 = PermOtherAll\n toEnum 65536 = PermAccessReadable\n toEnum 131072 = PermAccessWritable\n toEnum 262144 = PermAccessExecutable\n \n toEnum unmatched = error (\"FilePermissions.toEnum: Cannot match \" ++ show unmatched)\n\n--------------------------------------------------------------------\n\n-- | A 'URI' is a semi-textual representation of a uniform\n-- resource identifier. It contains the information about a resource\n-- location encoded as canononicalized text, but also holds extra\n-- information about the context in which the URI is used.\n{# pointer *GnomeVFSURI as URI foreign newtype #}\n\nnewURI :: Ptr URI\n -> IO URI\nnewURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr cURI cURIFinalizer\nwrapURI :: Ptr URI\n -> IO URI\nwrapURI cURI | cURI \/= nullPtr =\n liftM URI $ newForeignPtr_ cURI\nforeign import ccall \"&gnome_vfs_uri_unref\"\n cURIFinalizer :: FunPtr (Ptr URI -> IO ())\n\nwithURI (URI cURI) = withForeignPtr cURI\n\n-- | The toplevel URI element used to access resources stored on a\n-- remote server.\n{# pointer *GnomeVFSToplevelURI as ToplevelURI foreign newtype #}\nwithToplevelURI (ToplevelURI cToplevelURI) = withForeignPtr cToplevelURI\nnewToplevelURI :: Ptr ToplevelURI\n -> IO ToplevelURI\nnewToplevelURI cToplevelURI = liftM ToplevelURI $ newForeignPtr_ cToplevelURI\n\n-- | Flags specifying which fields of a 'URI' should be hidden when\n-- converted to a string using 'uriToString'.\n{# enum GnomeVFSURIHideOptions as URIHideOptions {\n GNOME_VFS_URI_HIDE_NONE as URIHideNone,\n GNOME_VFS_URI_HIDE_USER_NAME as URIHideUserName,\n GNOME_VFS_URI_HIDE_PASSWORD as URIHidePassword,\n GNOME_VFS_URI_HIDE_HOST_NAME as URIHideHostName,\n GNOME_VFS_URI_HIDE_HOST_PORT as URIHideHostPort,\n GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD as URIHideToplevelMethod,\n GNOME_VFS_URI_HIDE_FRAGMENT_IDENTIFIER as URIHideFragmentIdentifier\n } deriving (Eq, Bounded, Show) #}\ninstance Flags URIHideOptions\n\n-- | A string that can be passed to 'uriFromString' to create a valid\n-- 'URI'.\ntype TextURI = String\n\n--------------------------------------------------------------------\n\n-- | A handle to an open directory.\n{# pointer *GnomeVFSDirectoryHandle as DirectoryHandle foreign newtype #}\nwithDirectoryHandle (DirectoryHandle cDirectoryHandle) = withForeignPtr cDirectoryHandle\n\n-- | Options controlling the way in which a directories are visited.\n{# enum GnomeVFSDirectoryVisitOptions as DirectoryVisitOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags DirectoryVisitOptions\n\n-- | A callback that will be called for each entry when passed to\n-- 'directoryVisit', 'directoryVisitURI', 'directoryVisitFiles', or\n-- 'directoryVisitFilesAtURI'.\ntype DirectoryVisitCallback = String -- ^ the path of the visited file, relative to the base directory\n -> FileInfo -- ^ the 'FileInfo' for the visited file\n -> Bool -- ^ 'True' if returning 'DirectoryVisitRecurse' will cause a loop\n -> IO DirectoryVisitResult -- ^ the next action to be taken\n\n-- | An enumerated value that must be returned from a\n-- 'DirectoryVisitCallback'. The 'directoryVisit' and related\n-- functions will perform the action specified.\ndata DirectoryVisitResult = DirectoryVisitStop -- ^ stop visiting files\n | DirectoryVisitContinue -- ^ continue as normal\n | DirectoryVisitRecurse -- ^ recursively visit the current entry\n deriving (Eq, Enum)\n\n-- | Specifies which kind of directory 'findDirectory' should look for.\n{# enum GnomeVFSFindDirectoryKind as FindDirectoryKind {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n-- | Flags that may be passed to 'makeURIFromInputWithDirs'. If the\n-- path passed is non-absolute (i.e., a relative path), the\n-- directories specified will be searched as well.\n{# enum GnomeVFSMakeURIDirs as MakeURIDirs {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags MakeURIDirs\n\n--------------------------------------------------------------------\n\n-- | A handle to a file-system monitor.\nnewtype MonitorHandle = MonitorHandle (ForeignPtr MonitorHandle, {# type GnomeVFSMonitorCallback #})\nwithMonitorHandle (MonitorHandle (monitorHandleForeignPtr, _)) = withForeignPtr monitorHandleForeignPtr\n\n-- | A callback that must be passed to 'monitorAdd'. It will be\n-- called any time a file or directory is changed.\ntype MonitorCallback = MonitorHandle -- ^ the handle to a filesystem monitor\n -> TextURI -- ^ the URI being monitored\n -> TextURI -- ^ the actual file that was modified\n -> MonitorEventType -- ^ the event that occured\n -> IO ()\n\n-- | The type of filesystem object that is to be monitored.\n{# enum GnomeVFSMonitorType as MonitorType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\n\n-- | The type of event that caused a 'MonitorCallback' to be called.\n{# enum GnomeVFSMonitorEventType as MonitorEventType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\nwrapMonitorHandle :: (Ptr MonitorHandle, {# type GnomeVFSMonitorCallback #})\n -> IO MonitorHandle\nwrapMonitorHandle (cMonitorHandle, cMonitorCallback) =\n do monitorHandleForeignPtr <- newForeignPtr_ cMonitorHandle\n return $ MonitorHandle (monitorHandleForeignPtr, cMonitorCallback)\n\n--------------------------------------------------------------------\n\n-- | Options controlling how the 'System.Gnome.VFS.Xfer.xferURI' and related functions behave.\n{# enum GnomeVFSXferOptions as XferOptions {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Bounded, Show) #}\ninstance Flags XferOptions\n\n{# enum GnomeVFSXferProgressStatus as XferProgressStatus {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteMode as XferOverwriteMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferOverwriteAction as XferOverwriteAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorMode as XferErrorMode {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferErrorAction as XferErrorAction {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n{# enum GnomeVFSXferPhase as XferPhase {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ndata XferProgressInfo = XferProgressInfo {\n xferProgressInfoVFSStatus :: Result, -- ^ current VFS status\n xferProgressInfoPhase :: XferPhase, -- ^ phase of the transfer\n xferProgressInfoSourceName :: Maybe String, -- ^ currently transferring source URI\n xferProgressInfoTargetName :: Maybe String, -- ^ currently transferring target URI\n xferProgressInfoFileIndex :: Word, -- ^ index of the file currently being transferred\n xferProgressInfoFilesTotal :: Word, -- ^ total number of files being transferred\n xferProgressInfoBytesTotal :: FileSize, -- ^ total size of all files in bytes\n xferProgressInfoFileSize :: FileSize, -- ^ size of the file currently being transferred\n xferProgressInfoBytesCopied :: FileSize, -- ^ number of bytes already transferred in the current file\n xferProgressInfoTotalBytesCopied :: FileSize, -- ^ total number of bytes already transferred\n xferProgressInfoTopLevelItem :: Bool -- ^ 'True' if the file being transferred is a top-level item;\n -- 'False' if it is inside a directory\n } deriving (Eq)\n\n-- | The type of the first callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI' and related functions. This\n-- callback will be called periodically during transfers that are\n-- progressing normally.\ntype XferProgressCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO Bool -- ^ return 'Prelude.False' to abort the transfer, 'Prelude.True' otherwise.\n\n-- | The type of the second callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- whenever an error occurs.\ntype XferErrorCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferErrorAction -- ^ the action to be performed in response to the error\n\n-- | The type of the third callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a file would be overwritten.\ntype XferOverwriteCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> IO XferOverwriteAction -- ^ the action to be performed when the target file already exists\n\n-- | The type of the fourth callback that is passed to\n-- 'System.Gnome.VFS.Xfer.xferURI'. This callback will be called\n-- when a duplicate filename is found.\ntype XferDuplicateCallback = XferProgressInfo -- ^ @info@ - information about the progress of the current transfer\n -> String -- ^ @duplicateName@ - the name of the target file\n -> Int -- ^ @duplicateCount@ - the number of duplicates that exist\n -> IO (Maybe String) -- ^ the new filename that should be used, or 'Prelude.Nothing' to abort.\n\n--------------------------------------------------------------------\n\n-- | An object that can be used for signalling cancellation of an\n-- operation.\n{# pointer *GnomeVFSCancellation as Cancellation foreign newtype #}\n\nnewCancellation :: Ptr Cancellation\n -> IO Cancellation\nnewCancellation cCancellationPtr | cCancellationPtr \/= nullPtr =\n liftM Cancellation $ newForeignPtr cCancellationPtr cancellationFinalizer\nforeign import ccall unsafe \"&gnome_vfs_cancellation_destroy\"\n cancellationFinalizer :: FunPtr (Ptr Cancellation -> IO ())\nwithCancellation (Cancellation cCancellation) = withForeignPtr cCancellation\n\n--------------------------------------------------------------------\n\nwithVolume (Volume cVolume) = withForeignPtr cVolume\nnewVolume :: Ptr Volume\n -> IO Volume\nnewVolume cVolume | cVolume \/= nullPtr =\n liftM Volume $ newForeignPtr cVolume volumeFinalizer\nforeign import ccall unsafe \"&gnome_vfs_volume_unref\"\n volumeFinalizer :: FunPtr (Ptr Volume -> IO ())\n\n-- | An action to be performed when a volume operation completes successfully.\ntype VolumeOpSuccessCallback = IO ()\n-- | An action to be performed when a volume operation fails.\ntype VolumeOpFailureCallback = String\n -> String\n -> IO ()\n\n-- | Identifies the device type of a 'Volume' or 'Drive'.\n{#enum GnomeVFSDeviceType as DeviceType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n-- | Identifies the type of a 'Volume'.\n{#enum GnomeVFSVolumeType as VolumeType {underscoreToCase} with prefix = \"GNOME_VFS\" deriving (Eq, Show) #}\n\ntype CVolumeOpCallback = {# type gboolean #}\n -> CString\n -> CString\n -> Ptr ()\n -> IO ()\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Drive'\ntype DriveID = {# type gulong #}\n\nwithDrive (Drive cDrive) = withForeignPtr cDrive\nnewDrive :: Ptr Drive\n -> IO Drive\nnewDrive cDrive | cDrive \/= nullPtr =\n liftM Drive $ newForeignPtr cDrive driveFinalizer\nforeign import ccall unsafe \"&gnome_vfs_drive_unref\"\n driveFinalizer :: FunPtr (Ptr Drive -> IO ())\n\n--------------------------------------------------------------------\n\n-- | Identifies a 'Volume'.\ntype VolumeID = {# type gulong #}\n\nwithVolumeMonitor (VolumeMonitor cVolumeMonitor) = withForeignPtr cVolumeMonitor\nwrapVolumeMonitor :: Ptr VolumeMonitor\n -> IO VolumeMonitor\nwrapVolumeMonitor cVolumeMonitor | cVolumeMonitor \/= nullPtr =\n liftM VolumeMonitor $ newForeignPtr_ cVolumeMonitor\n\n--------------------------------------------------------------------\n\n-- | A string that will be treated as a MIME-type.\ntype MIMEType = String\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"5931417b31602d69813ec170d14dbb15fd3e5da2","subject":"Adapt to the safer dw_tag","message":"Adapt to the safer dw_tag\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 #-}\nmodule LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems, unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\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\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\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\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\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 :: 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#}\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 ByteString\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 ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\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 ByteString\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 ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\n-- cMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeCompileUnit = 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#}\ncMetaUnknownRepr :: InternString m => MetaPtr -> m ByteString\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 :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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\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 #-}\nmodule LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems, unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\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\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\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\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\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 :: 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#}\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 = dw_tag <$> {#get CMeta->tag#} p\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 ByteString\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 ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\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 ByteString\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 ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m ByteString\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 ByteString\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 ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m ByteString\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 ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\n-- cMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeCompileUnit = 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#}\ncMetaUnknownRepr :: InternString m => MetaPtr -> m ByteString\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 :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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\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":"38b1d3c5d67b15bd304081040f251a8244ec9e0c","subject":"Add waitForStatus and initialMetadata to Rpc monad.","message":"Add waitForStatus and initialMetadata to Rpc monad.\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\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 putStrLn \"clientWaitForInitialMetadata(..)\"\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 putStrLn (\"metadata: \" ++ show md)\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err -> do\n putStrLn \"clientWaitForInitialMetadata: callBatch failed\"\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n putStrLn \"clientReadInitialMetadata(..)\"\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n putStrLn \"clientRead(..)\"\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n putStrLn \"recvMessage(..)\"\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\nclientSendClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendClose 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\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\nsendClose :: Rpc req resp ()\nsendClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ncallBidi :: ClientContext -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _ deadline) method = 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 []\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","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 putStrLn \"clientWaitForInitialMetadata(..)\"\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 putStrLn (\"metadata: \" ++ show md)\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err -> do\n putStrLn \"clientWaitForInitialMetadata: callBatch failed\"\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n putStrLn \"clientReadInitialMetadata(..)\"\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n putStrLn \"clientRead(..)\"\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n putStrLn \"recvMessage(..)\"\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 ())\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n callBatch crw [ OpX recvStatusOp ]\n Just _ -> return (RpcOk ())\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n -- clientWaitForStatus crw\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\nclientSendClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendClose 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\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\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\nsendClose :: Rpc req resp ()\nsendClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ncallBidi :: ClientContext -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _ deadline) method = 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 []\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":"cd93f76e861eeefee8fc187d385888c07e17fe09","subject":"gnomevfs: add function S.G.V.Volume.volumeUnmount","message":"gnomevfs: add function S.G.V.Volume.volumeUnmount\n\ndarcs-hash:20070929170420-21862-5fcd58f24a353ba128fd3997af1f003728373906.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"4050ece9fbdc850581d53d86e43fbfa276a0f25c","subject":"Context objects directly","message":"Context objects directly\n\nIgnore-this: be6b905dfc70471ef7f6f12c03301170\n\ndarcs-hash:20091211032435-9241b-2a625f3d4c5744ed2e81f47ddff5af77c6e678d6.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Context.chs","new_file":"Foreign\/CUDA\/Driver\/Context.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Context\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Context management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Context\n (\n Context, ContextFlag(..),\n create, attach, detach, destroy, current, pop, push, sync\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A device context\n--\nnewtype Context = Context { useContext :: {# type CUcontext #}}\n\n\n-- |\n-- Context creation flags\n--\n{# enum CUctx_flags as ContextFlag\n { underscoreToCase }\n with prefix=\"CU_CTX\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Context management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new CUDA context and associate it with the calling thread\n--\ncreate :: Device -> [ContextFlag] -> IO (Either String Context)\ncreate dev flags = resultIfOk `fmap` cuCtxCreate flags dev\n\n{# fun unsafe cuCtxCreate\n { alloca- `Context' peekCtx*\n , combineBitMasks `[ContextFlag]'\n , useDevice `Device' } -> `Status' cToEnum #}\n where peekCtx = liftM Context . peek\n\n\n-- |\n-- Increments the usage count of the context. API: no context flags are\n-- currently supported, so this parameter must be empty.\n--\nattach :: Context -> [ContextFlag] -> IO (Maybe String)\nattach ctx flags = nothingIfOk `fmap` cuCtxAttach ctx flags\n\n{# fun unsafe cuCtxAttach\n { withCtx* `Context'\n , combineBitMasks `[ContextFlag]' } -> `Status' cToEnum #}\n where withCtx = with . useContext\n\n\n-- |\n-- Detach the context, and destroy if no longer used\n--\ndetach :: Context -> IO (Maybe String)\ndetach ctx = nothingIfOk `fmap` cuCtxDetach ctx\n\n{# fun unsafe cuCtxDetach\n { useContext `Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy the specified context. This fails if the context is more than a\n-- single attachment (including that from initial creation).\n--\ndestroy :: Context -> IO (Maybe String)\ndestroy ctx = nothingIfOk `fmap` cuCtxDestroy ctx\n\n{# fun unsafe cuCtxDestroy\n { useContext `Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device of the currently active context\n--\ncurrent :: IO (Either String Device)\ncurrent = resultIfOk `fmap` cuCtxGetDevice\n\n{# fun unsafe cuCtxGetDevice\n { alloca- `Device' dev* } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Pop the current CUDA context from the CPU thread. The context must have a\n-- single usage count (matching calls to attach\/detach). If successful, the new\n-- context is returned, and the old may be attached to a different CPU.\n--\npop :: IO (Either String Context)\npop = resultIfOk `fmap` cuCtxPopCurrent\n\n{# fun unsafe cuCtxPopCurrent\n { alloca- `Context' peekCtx* } -> `Status' cToEnum #}\n where peekCtx = liftM Context . peek\n\n\n-- |\n-- Push the given context onto the CPU's thread stack of current contexts. The\n-- context must be floating (via `pop'), i.e. not attached to any thread.\n--\npush :: Context -> IO (Maybe String)\npush ctx = nothingIfOk `fmap` cuCtxPushCurrent ctx\n\n{# fun unsafe cuCtxPushCurrent\n { useContext `Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Block until the device has completed all preceding requests\n--\nsync :: IO (Maybe String)\nsync = nothingIfOk `fmap` cuCtxSynchronize\n\n{# fun unsafe cuCtxSynchronize\n { } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Context\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Context management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Context\n (\n Context, ContextFlag(..),\n create, attach, detach, destroy, current, pop, push, sync\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A device context\n--\n{# pointer *CUcontext as Context foreign newtype #}\nwithContext :: Context -> (Ptr Context -> IO a) -> IO a\n\n--\n-- XXX: Probably want to add a finaliser to `destroy' the context before\n-- releasing its reference. Not done as this may flag an error, which could be\n-- picked up by later driver calls.\n--\nnewContext :: IO Context\nnewContext = Context `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\n\n\n-- |\n-- Context creation flags\n--\n{# enum CUctx_flags as ContextFlag\n { underscoreToCase }\n with prefix=\"CU_CTX\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Context management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new CUDA context and associate it with the calling thread\n--\ncreate :: Device -> [ContextFlag] -> IO (Either String Context)\ncreate dev flags =\n newContext >>= \\ctx -> withContext ctx $ \\p ->\n cuCtxCreate p flags dev >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right ctx\n Just e -> Left e\n\n{# fun unsafe cuCtxCreate\n { id `Ptr Context'\n , combineBitMasks `[ContextFlag]'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Increments the usage count of the context. API: no context flags are\n-- currently supported, so this parameter must be empty.\n--\nattach :: Context -> [ContextFlag] -> IO (Maybe String)\nattach ctx flags = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxAttach p flags)\n\n{# fun unsafe cuCtxAttach\n { id `Ptr Context'\n , combineBitMasks `[ContextFlag]' } -> `Status' cToEnum #}\n\n\n-- |\n-- Detach the context, and destroy if no longer used\n--\ndetach :: Context -> IO (Maybe String)\ndetach ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxDetach p)\n\n{# fun unsafe cuCtxDetach\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy the specified context. This fails if the context is more than a\n-- single attachment (including that from initial creation).\n--\ndestroy :: Context -> IO (Maybe String)\ndestroy ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxDestroy p)\n\n{# fun unsafe cuCtxDestroy\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device of the currently active context\n--\ncurrent :: IO (Either String Device)\ncurrent = resultIfOk `fmap` cuCtxGetDevice\n\n{# fun unsafe cuCtxGetDevice\n { alloca- `Device' dev* } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Pop the current CUDA context from the CPU thread. The context must have a\n-- single usage count (matching calls to attach\/detach). If successful, the new\n-- context is returned, and the old may be attached to a different CPU.\n--\npop :: IO (Either String Context)\npop =\n newContext >>= \\ctx -> withContext ctx $ \\p ->\n cuCtxPopCurrent p >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right ctx\n Just e -> Left e\n\n{# fun unsafe cuCtxPopCurrent\n { id `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Push the given context onto the CPU's thread stack of current contexts. The\n-- context must be floating (via `pop'), i.e. not attached to any thread.\n--\npush :: Context -> IO (Maybe String)\npush ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxPushCurrent p)\n\n{# fun unsafe cuCtxPushCurrent\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Block until the device has completed all preceding requests\n--\nsync :: IO (Maybe String)\nsync = nothingIfOk `fmap` cuCtxSynchronize\n\n{# fun unsafe cuCtxSynchronize\n { } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"86124b46e73da9240a6e36b03561880bb4c8a697","subject":"flInput and flPassword now return the user's input","message":"flInput and flPassword now return the user's input\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input as flInput' { unsafeToCString `T.Text' } -> `T.Text' unsafeFromCString #}\nflInput :: T.Text -> IO T.Text\nflInput = flInput'\n\n{# fun flc_password as flPassword' { unsafeToCString `T.Text' } -> `T.Text' unsafeFromCString #}\nflPassword :: T.Text -> IO T.Text\nflPassword = flPassword'\n\n{# fun flc_message as flMessage' { unsafeToCString `T.Text' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage = flMessage'\n\n{# fun flc_alert as flAlert' { unsafeToCString `T.Text' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert = flAlert'\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input as flInput' { unsafeToCString `T.Text' } -> `()' #}\nflInput :: T.Text -> IO ()\nflInput = flInput'\n\n{# fun flc_password as flPassword' { unsafeToCString `T.Text' } -> `()' #}\nflPassword :: T.Text -> IO ()\nflPassword = flPassword'\n\n{# fun flc_message as flMessage' { unsafeToCString `T.Text' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage = flMessage'\n\n{# fun flc_alert as flAlert' { unsafeToCString `T.Text' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert = flAlert'\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"b60db02d21decc91429a28c1a1990a07a205a441","subject":"removed unused import","message":"removed unused import\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/DataType.chs","new_file":"src\/GDAL\/Internal\/DataType.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.DataType (\n GDALType (..)\n , KnownDataType\n , DataType (..)\n , CDataTypeT\n , GType\n\n , dataType\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n) where\n\n#include \"gdal.h\"\n#include \"bindings.h\"\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Data.Int (Int8, Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types\nimport Foreign.C.String (withCString)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (toEnumC, fromEnumC)\n\n\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\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\n------------------------------------------------------------------------------\n-- GDALType\n------------------------------------------------------------------------------\ntype CDataTypeT a = GType (DataTypeT a)\n\nclass (Eq a , Storable a , KnownDataType (DataTypeT a)) => GDALType a where\n type DataTypeT a :: DataType\n toGType :: St.Vector a -> St.Vector (CDataTypeT a)\n fromGType :: St.Vector (CDataTypeT a) -> St.Vector a\n toGTypeM :: St.MVector s a -> St.MVector s (CDataTypeT a)\n fromGTypeM :: St.MVector s (CDataTypeT a) -> St.MVector s a\n\n toCDouble :: a -> CDouble\n fromCDouble :: CDouble -> a\n\ntype family GType (k :: DataType) where\n GType 'GDT_Byte = CUChar\n GType 'GDT_UInt16 = CUShort\n GType 'GDT_UInt32 = CUInt\n GType 'GDT_Int16 = CShort\n GType 'GDT_Int32 = CInt\n GType 'GDT_Float32 = CFloat\n GType 'GDT_Float64 = CDouble\n GType 'GDT_CInt16 = CComplex CShort\n GType 'GDT_CInt32 = CComplex CInt\n GType 'GDT_CFloat32 = CComplex CFloat\n GType 'GDT_CFloat64 = CComplex CDouble\n\nnewtype CComplex a = CComplex (Complex a)\n deriving (Eq, Show)\n\nclass (Storable (GType k), Eq (GType k)) => KnownDataType (k :: DataType) where\n dataTypeVal :: Proxy (k :: DataType) -> DataType\n\ndataType :: forall a. GDALType a => Proxy a -> DataType\ndataType _ = dataTypeVal (Proxy :: Proxy (DataTypeT a))\n{-# INLINE dataType #-}\n\ninstance KnownDataType 'GDT_Byte where dataTypeVal _ = GDT_Byte\ninstance KnownDataType 'GDT_UInt16 where dataTypeVal _ = GDT_UInt16\ninstance KnownDataType 'GDT_UInt32 where dataTypeVal _ = GDT_UInt32\ninstance KnownDataType 'GDT_Int16 where dataTypeVal _ = GDT_Int16\ninstance KnownDataType 'GDT_Int32 where dataTypeVal _ = GDT_Int32\ninstance KnownDataType 'GDT_Float32 where dataTypeVal _ = GDT_Float32\ninstance KnownDataType 'GDT_Float64 where dataTypeVal _ = GDT_Float64\ninstance KnownDataType 'GDT_CInt16 where dataTypeVal _ = GDT_CInt16\ninstance KnownDataType 'GDT_CInt32 where dataTypeVal _ = GDT_CInt32\ninstance KnownDataType 'GDT_CFloat32 where dataTypeVal _ = GDT_CFloat32\ninstance KnownDataType 'GDT_CFloat64 where dataTypeVal _ = GDT_CFloat64\n\n\ninstance GDALType Word8 where\n type DataTypeT Word8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n type DataTypeT Word16 = 'GDT_UInt16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n type DataTypeT Word32 = 'GDT_UInt32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int8 where\n type DataTypeT Int8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = St.unsafeCast\n fromGType = St.unsafeCast\n toGTypeM = Stm.unsafeCast\n fromGTypeM = Stm.unsafeCast\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n type DataTypeT Int16 = 'GDT_Int16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n type DataTypeT Int32 = 'GDT_Int32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n type DataTypeT Float = 'GDT_Float32\n fromCDouble = realToFrac\n toCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n type DataTypeT Double = 'GDT_Float64\n toCDouble = realToFrac\n fromCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\n\nderiving instance Storable a => Storable (CComplex a)\n\ninstance GDALType (Complex Int16) where\n type DataTypeT (Complex Int16) = 'GDT_CInt16\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n type DataTypeT (Complex Int32) = 'GDT_CInt32\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n type DataTypeT (Complex Float) = 'GDT_CFloat32\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n type DataTypeT (Complex Double) = 'GDT_CFloat64\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.DataType (\n GDALType (..)\n , KnownDataType\n , DataType (..)\n , CDataTypeT\n , GType\n\n , dataType\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n) where\n\n#include \"gdal.h\"\n#include \"bindings.h\"\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Data.Int (Int8, Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (Coercible, coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types\nimport Foreign.C.String (withCString)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (toEnumC, fromEnumC)\n\n\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\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\n------------------------------------------------------------------------------\n-- GDALType\n------------------------------------------------------------------------------\ntype CDataTypeT a = GType (DataTypeT a)\n\nclass (Eq a , Storable a , KnownDataType (DataTypeT a)) => GDALType a where\n type DataTypeT a :: DataType\n toGType :: St.Vector a -> St.Vector (CDataTypeT a)\n fromGType :: St.Vector (CDataTypeT a) -> St.Vector a\n toGTypeM :: St.MVector s a -> St.MVector s (CDataTypeT a)\n fromGTypeM :: St.MVector s (CDataTypeT a) -> St.MVector s a\n\n toCDouble :: a -> CDouble\n fromCDouble :: CDouble -> a\n\ntype family GType (k :: DataType) where\n GType 'GDT_Byte = CUChar\n GType 'GDT_UInt16 = CUShort\n GType 'GDT_UInt32 = CUInt\n GType 'GDT_Int16 = CShort\n GType 'GDT_Int32 = CInt\n GType 'GDT_Float32 = CFloat\n GType 'GDT_Float64 = CDouble\n GType 'GDT_CInt16 = CComplex CShort\n GType 'GDT_CInt32 = CComplex CInt\n GType 'GDT_CFloat32 = CComplex CFloat\n GType 'GDT_CFloat64 = CComplex CDouble\n\nnewtype CComplex a = CComplex (Complex a)\n deriving (Eq, Show)\n\nclass (Storable (GType k), Eq (GType k)) => KnownDataType (k :: DataType) where\n dataTypeVal :: Proxy (k :: DataType) -> DataType\n\ndataType :: forall a. GDALType a => Proxy a -> DataType\ndataType _ = dataTypeVal (Proxy :: Proxy (DataTypeT a))\n{-# INLINE dataType #-}\n\ninstance KnownDataType 'GDT_Byte where dataTypeVal _ = GDT_Byte\ninstance KnownDataType 'GDT_UInt16 where dataTypeVal _ = GDT_UInt16\ninstance KnownDataType 'GDT_UInt32 where dataTypeVal _ = GDT_UInt32\ninstance KnownDataType 'GDT_Int16 where dataTypeVal _ = GDT_Int16\ninstance KnownDataType 'GDT_Int32 where dataTypeVal _ = GDT_Int32\ninstance KnownDataType 'GDT_Float32 where dataTypeVal _ = GDT_Float32\ninstance KnownDataType 'GDT_Float64 where dataTypeVal _ = GDT_Float64\ninstance KnownDataType 'GDT_CInt16 where dataTypeVal _ = GDT_CInt16\ninstance KnownDataType 'GDT_CInt32 where dataTypeVal _ = GDT_CInt32\ninstance KnownDataType 'GDT_CFloat32 where dataTypeVal _ = GDT_CFloat32\ninstance KnownDataType 'GDT_CFloat64 where dataTypeVal _ = GDT_CFloat64\n\n\ninstance GDALType Word8 where\n type DataTypeT Word8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n type DataTypeT Word16 = 'GDT_UInt16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n type DataTypeT Word32 = 'GDT_UInt32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int8 where\n type DataTypeT Int8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = St.unsafeCast\n fromGType = St.unsafeCast\n toGTypeM = Stm.unsafeCast\n fromGTypeM = Stm.unsafeCast\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n type DataTypeT Int16 = 'GDT_Int16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n type DataTypeT Int32 = 'GDT_Int32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n type DataTypeT Float = 'GDT_Float32\n fromCDouble = realToFrac\n toCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n type DataTypeT Double = 'GDT_Float64\n toCDouble = realToFrac\n fromCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\n\nderiving instance Storable a => Storable (CComplex a)\n\ninstance GDALType (Complex Int16) where\n type DataTypeT (Complex Int16) = 'GDT_CInt16\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n type DataTypeT (Complex Int32) = 'GDT_CInt32\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n type DataTypeT (Complex Float) = 'GDT_CFloat32\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n type DataTypeT (Complex Double) = 'GDT_CFloat64\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"adb3a53e7af4e6b9aac06f738ba6a16359799113","subject":"implementation TODO","message":"implementation TODO\n\nIgnore-this: 2f4662d94eca082c928ff44826b7658b\n\ndarcs-hash:20091125030216-9241b-ee90cb44ec3f8413f1dd5727f06c79908685ad43.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Context.chs","new_file":"Foreign\/CUDA\/Driver\/Context.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Context\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Context management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Context\n (\n Context, ContextFlags(..),\n create, attach, detach, destroy, current, pop, push, sync\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *CUcontext as Context foreign newtype #}\nwithContext :: Context -> (Ptr Context -> IO a) -> IO a\n\n--\n-- XXX: Probably want to add a finaliser to `destroy' the context before\n-- releasing its reference. Not done as this may flag an error, which could be\n-- picked up by later driver calls.\n--\nnewContext :: IO Context\nnewContext = Context `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\n\n\n-- |\n-- Context creation flags\n--\n{# enum CUctx_flags as ContextFlags\n { underscoreToCase }\n with prefix=\"CU_CTX\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Context management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new CUDA context and associate it with the calling thread\n--\ncreate :: Device -> [ContextFlags] -> IO (Either String Context)\ncreate dev flags =\n newContext >>= \\ctx -> withContext ctx $ \\p ->\n cuCtxCreate p flags dev >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right ctx\n Just e -> Left e\n\n{# fun unsafe cuCtxCreate\n { id `Ptr Context'\n , combineBitMasks `[ContextFlags]'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Increments the usage count of the context\n--\nattach :: Context -> IO (Maybe String)\nattach ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxAttach p 0)\n\n{# fun unsafe cuCtxAttach\n { id `Ptr Context'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Detach the context, and destroy if no longer used\n--\ndetach :: Context -> IO (Maybe String)\ndetach ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxDetach p)\n\n{# fun unsafe cuCtxDetach\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy the specified context. This fails if the context is more than a\n-- single attachment (including that from initial creation).\n--\ndestroy :: Context -> IO (Maybe String)\ndestroy ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxDestroy p)\n\n{# fun unsafe cuCtxDestroy\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device of the currently active context\n--\ncurrent :: IO (Either String Device)\ncurrent = resultIfOk `fmap` cuCtxGetDevice\n\n{# fun unsafe cuCtxGetDevice\n { alloca- `Device' dev* } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Pop the current CUDA context from the CPU thread. The context must have a\n-- single usage count (matching calls to attach\/detach). If successful, the new\n-- context is returned, and the old may be attached to a different CPU.\n--\npop :: IO (Either String Context)\npop =\n newContext >>= \\ctx -> withContext ctx $ \\p ->\n cuCtxPopCurrent p >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right ctx\n Just e -> Left e\n\n{# fun unsafe cuCtxPopCurrent\n { id `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Push the given context onto the CPU's thread stack of current contexts. The\n-- context must be floating (via `pop'), i.e. not attached to any thread.\n--\npush :: Context -> IO (Maybe String)\npush ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxPushCurrent p)\n\n{# fun unsafe cuCtxPushCurrent\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Block until the device has completed all preceding requests\n--\nsync :: IO (Maybe String)\nsync = nothingIfOk `fmap` cuCtxSynchronize\n\n{# fun unsafe cuCtxSynchronize\n { } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Context\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Context management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Context\n (\n Context, ContextFlags(..),\n create, attach, detach, destroy, current, pop, push, sync\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *CUcontext as Context foreign newtype #}\nwithContext :: Context -> (Ptr Context -> IO a) -> IO a\n\nnewContext :: IO Context\nnewContext = Context `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\n\n\n-- |\n-- Context creation flags\n--\n{# enum CUctx_flags as ContextFlags\n { underscoreToCase }\n with prefix=\"CU_CTX\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Context management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new CUDA context and associate it with the calling thread\n--\ncreate :: Device -> [ContextFlags] -> IO (Either String Context)\ncreate dev flags =\n newContext >>= \\ctx -> withContext ctx $ \\p ->\n cuCtxCreate p flags dev >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right ctx\n Just e -> Left e\n\n{# fun unsafe cuCtxCreate\n { id `Ptr Context'\n , combineBitMasks `[ContextFlags]'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Increments the usage count of the context\n--\nattach :: Context -> IO (Maybe String)\nattach ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxAttach p 0)\n\n{# fun unsafe cuCtxAttach\n { id `Ptr Context'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Detach the context, and destroy if no longer used\n--\ndetach :: Context -> IO (Maybe String)\ndetach ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxDetach p)\n\n{# fun unsafe cuCtxDetach\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy the specified context. This fails if the context is more than a\n-- single attachment (including that from initial creation).\n--\ndestroy :: Context -> IO (Maybe String)\ndestroy ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxDestroy p)\n\n{# fun unsafe cuCtxDestroy\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device of the currently active context\n--\ncurrent :: IO (Either String Device)\ncurrent = resultIfOk `fmap` cuCtxGetDevice\n\n{# fun unsafe cuCtxGetDevice\n { alloca- `Device' dev* } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Pop the current CUDA context from the CPU thread. The context must have a\n-- single usage count (matching calls to attach\/detach). If successful, the new\n-- context is returned, and the old may be attached to a different CPU.\n--\npop :: IO (Either String Context)\npop =\n newContext >>= \\ctx -> withContext ctx $ \\p ->\n cuCtxPopCurrent p >>= \\rv ->\n return $ case nothingIfOk rv of\n Nothing -> Right ctx\n Just e -> Left e\n\n{# fun unsafe cuCtxPopCurrent\n { id `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Push the given context onto the CPU's thread stack of current contexts. The\n-- context must be floating (via `pop'), i.e. not attached to any thread.\n--\npush :: Context -> IO (Maybe String)\npush ctx = withContext ctx $ \\p -> (nothingIfOk `fmap` cuCtxPushCurrent p)\n\n{# fun unsafe cuCtxPushCurrent\n { castPtr `Ptr Context' } -> `Status' cToEnum #}\n\n\n-- |\n-- Block until the device has completed all preceding requests\n--\nsync :: IO (Maybe String)\nsync = nothingIfOk `fmap` cuCtxSynchronize\n\n{# fun unsafe cuCtxSynchronize\n { } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5e525b4c47430b33a072a1d4b73e995c2a1482ef","subject":"Adjust webResourceGetEncoding.","message":"Adjust webResourceGetEncoding.","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b2628d5d0c6d27fa0fdeb566de165ac695a89189","subject":"Adjust webResourceGetFrameName.","message":"Adjust webResourceGetFrameName.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"91bf45e8b71571bb27e79ee834de43010833c376","subject":"Fix webSettingsFantasyFontFamily attr","message":"Fix webSettingsFantasyFontFamily attr\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/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":"259c3fe08b8989a30b2c3f1c974cfbe3ac4560f3","subject":"Bits and pieces of Internal haddock","message":"Bits and pieces of Internal haddock\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@ 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, tagVal, 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 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*- #}\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 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, tagVal, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, isendPtr, ibsendPtr, issendPtr, irecv,\n 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\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*- #}\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{- 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 , mpiErrorCode :: CInt\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 code\n\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":"b267d3cd4ba1259f1f11a1d667905cc61702e695","subject":"bug fix: typo","message":"bug fix: typo\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Context\/Primary.chs","new_file":"Foreign\/CUDA\/Driver\/Context\/Primary.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TemplateHaskell #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Context.Primary\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Primary context management for low-level driver interface. The primary\n-- context is unique per device and shared with the Runtime API. This\n-- allows integration with other libraries using CUDA.\n--\n-- Since: CUDA-7.0\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Context.Primary (\n\n status, setup, reset, retain, release,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Context.Base\nimport Foreign.CUDA.Driver.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Control.Exception\nimport Control.Monad\nimport Foreign\nimport Foreign.C\n\n\n--------------------------------------------------------------------------------\n-- Primary context management\n--------------------------------------------------------------------------------\n\n\n-- |\n-- Get the status of the primary context. Returns whether the current\n-- context is active, and the flags it was (or will be) created with.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE status #-}\nstatus :: Device -> IO (Bool, [ContextFlag])\n#if CUDA_VERSION < 7000\nstatus _ = requireSDK 'status 7.0\n#else\nstatus !dev =\n cuDevicePrimaryCtxGetState dev >>= \\(rv, !flags, !active) ->\n case rv of\n Success -> return (active, flags)\n _ -> throwIO (ExitCode rv)\n\n{# fun unsafe cuDevicePrimaryCtxGetState\n { useDevice `Device'\n , alloca- `[ContextFlag]' peekFlags*\n , alloca- `Bool' peekBool*\n } -> `Status' cToEnum #}\n where\n peekFlags = liftM extractBitMasks . peek\n#endif\n\n\n-- |\n-- Specify the flags that the primary context should be created with. Note\n-- that this is an error if the primary context is already active.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE setup #-}\nsetup :: Device -> [ContextFlag] -> IO ()\n#if CUDA_VERSION < 7000\nsetup _ _ = requireSDK 'setup 7.0\n#else\nsetup !dev !flags = nothingIfOk =<< cuDevicePrimaryCtxSetFlags dev flags\n\n{-# INLINE cuDevicePrimaryCtxSetFlags #-}\n{# fun unsafe cuDevicePrimaryCtxSetFlags\n { useDevice `Device'\n , combineBitMasks `[ContextFlag]'\n } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Destroy all allocations and reset all state on the primary context of\n-- the given device in the current process. Requires cuda-7.0\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE reset #-}\nreset :: Device -> IO ()\n#if CUDA_VERSION < 7000\nreset _ = requireSDK 'reset 7.0\n#else\nreset !dev = nothingIfOk =<< cuDevicePrimaryCtxReset dev\n\n{-# INLINE cuDevicePrimaryCtxReset #-}\n{# fun unsafe cuDevicePrimaryCtxReset\n { useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Release the primary context on the given device. If there are no more\n-- references to the primary context it will be destroyed, regardless of\n-- how many threads it is current to.\n--\n-- Unlike 'Foreign.CUDA.Driver.Context.Base.pop' this does not pop the\n-- context from the stack in any circumstances.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE release #-}\nrelease :: Device -> IO ()\n#if CUDA_VERSION < 7000\nrelease _ = requireSDK 'release 7.0\n#else\nrelease !dev = nothingIfOk =<< cuDevicePrimaryCtxRelease dev\n\n{-# INLINE cuDevicePrimaryCtxRelease #-}\n{# fun unsafe cuDevicePrimaryCtxRelease\n { useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Retain the primary context for the given device, creating it if\n-- necessary, and increasing its usage count. The caller must call\n-- 'release' when done using the context. Unlike\n-- 'Foreign.CUDA.Driver.Context.Base.create' the newly retained context is\n-- not pushed onto the stack.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE retain #-}\nretain :: Device -> IO Context\n#if CUDA_VERSION < 7000\nretain _ = requireSDK 'retain 7.0\n#else\nretain !dev = resultIfOk =<< cuDevicePrimaryCtxRetain dev\n\n{-# INLINE cuDevicePrimaryCtxRetain #-}\n{# fun unsafe cuDevicePrimaryCtxRetain\n { alloca- `Context' peekCtx*\n , useDevice `Device'\n } -> `Status' cToEnum #}\n where\n peekCtx = liftM Context . peek\n#endif\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TemplateHaskell #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Context.Primary\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Primary context management for low-level driver interface. The primary\n-- context is unique per device and shared with the Runtime API. This\n-- allows integration with other libraries using CUDA.\n--\n-- Since: CUDA-7.0\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Context.Primary (\n\n status, setup, reset, retain, release,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Context.Base\nimport Foreign.CUDA.Driver.Device\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Control.Exception\nimport Control.Monad\nimport Foreign\nimport Foreign.C\n\n\n--------------------------------------------------------------------------------\n-- Primary context management\n--------------------------------------------------------------------------------\n\n\n-- |\n-- Get the status of the primary context. Returns whether the current\n-- context is active, and the flags it was (or will be) created with.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE status #-}\nstatus :: Device -> IO (Bool, [ContextFlag])\n#if CUDA_VERSION < 7000\nstatus _ = requireSDK 'staus 7.0\n#else\nstatus !dev =\n cuDevicePrimaryCtxGetState dev >>= \\(rv, !flags, !active) ->\n case rv of\n Success -> return (active, flags)\n _ -> throwIO (ExitCode rv)\n\n{# fun unsafe cuDevicePrimaryCtxGetState\n { useDevice `Device'\n , alloca- `[ContextFlag]' peekFlags*\n , alloca- `Bool' peekBool*\n } -> `Status' cToEnum #}\n where\n peekFlags = liftM extractBitMasks . peek\n#endif\n\n\n-- |\n-- Specify the flags that the primary context should be created with. Note\n-- that this is an error if the primary context is already active.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE setup #-}\nsetup :: Device -> [ContextFlag] -> IO ()\n#if CUDA_VERSION < 7000\nsetup _ _ = requireSDK 'setup 7.0\n#else\nsetup !dev !flags = nothingIfOk =<< cuDevicePrimaryCtxSetFlags dev flags\n\n{-# INLINE cuDevicePrimaryCtxSetFlags #-}\n{# fun unsafe cuDevicePrimaryCtxSetFlags\n { useDevice `Device'\n , combineBitMasks `[ContextFlag]'\n } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Destroy all allocations and reset all state on the primary context of\n-- the given device in the current process. Requires cuda-7.0\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE reset #-}\nreset :: Device -> IO ()\n#if CUDA_VERSION < 7000\nreset _ = requireSDK 'reset 7.0\n#else\nreset !dev = nothingIfOk =<< cuDevicePrimaryCtxReset dev\n\n{-# INLINE cuDevicePrimaryCtxReset #-}\n{# fun unsafe cuDevicePrimaryCtxReset\n { useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Release the primary context on the given device. If there are no more\n-- references to the primary context it will be destroyed, regardless of\n-- how many threads it is current to.\n--\n-- Unlike 'Foreign.CUDA.Driver.Context.Base.pop' this does not pop the\n-- context from the stack in any circumstances.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE release #-}\nrelease :: Device -> IO ()\n#if CUDA_VERSION < 7000\nrelease _ = requireSDK 'release 7.0\n#else\nrelease !dev = nothingIfOk =<< cuDevicePrimaryCtxRelease dev\n\n{-# INLINE cuDevicePrimaryCtxRelease #-}\n{# fun unsafe cuDevicePrimaryCtxRelease\n { useDevice `Device' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Retain the primary context for the given device, creating it if\n-- necessary, and increasing its usage count. The caller must call\n-- 'release' when done using the context. Unlike\n-- 'Foreign.CUDA.Driver.Context.Base.create' the newly retained context is\n-- not pushed onto the stack.\n--\n-- Requires CUDA-7.0.\n--\n-- \n--\n{-# INLINEABLE retain #-}\nretain :: Device -> IO Context\n#if CUDA_VERSION < 7000\nretain _ = requireSDK 'retain 7.0\n#else\nretain !dev = resultIfOk =<< cuDevicePrimaryCtxRetain dev\n\n{-# INLINE cuDevicePrimaryCtxRetain #-}\n{# fun unsafe cuDevicePrimaryCtxRetain\n { alloca- `Context' peekCtx*\n , useDevice `Device'\n } -> `Status' cToEnum #}\n where\n peekCtx = liftM Context . peek\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e5c14d5973ec5978cd2892429268522ca316ae39","subject":"Added missing Num constraints.","message":"Added missing Num constraints.\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Types.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Types.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 DeriveDataTypeable #-}\nmodule Control.Parallel.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLMemObjectType_, CLMemInfo_, CLImageInfo_, CLMapFlags_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..), CLMapFlag(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLMapFlags_ = {#type cl_map_flags#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n-- -----------------------------------------------------------------------------\n\n-- * NOTE: Apple lags behind official Khronos header files\n#c\nenum CLError {\n#ifdef __APPLE__\n cL_PLATFORM_NOT_FOUND_KHR=-1001,\n#else\n cL_PLATFORM_NOT_FOUND_KHR=CL_PLATFORM_NOT_FOUND_KHR,\n#endif\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_PLATFORM_NOT_FOUND_khr', Returned when no .icd (platform drivers)\n can be properly loaded.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMapFlag {\n cL_MAP_READ=CL_MAP_READ,\n cL_MAP_WRITE=CL_MAP_WRITE\n };\n#endc\n{#enum CLMapFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b, Num b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b, Num b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes =\n\tbitmaskToFlags \n\t\t[CL_DEVICE_TYPE_CPU\n\t\t,CL_DEVICE_TYPE_GPU\n\t\t,CL_DEVICE_TYPE_ACCELERATOR\n\t\t,CL_DEVICE_TYPE_DEFAULT\n\t\t,CL_DEVICE_TYPE_ALL\n\t\t]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\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 DeriveDataTypeable #-}\nmodule Control.Parallel.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLMemObjectType_, CLMemInfo_, CLImageInfo_, CLMapFlags_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..), CLMapFlag(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLMapFlags_ = {#type cl_map_flags#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n-- -----------------------------------------------------------------------------\n\n-- * NOTE: Apple lags behind official Khronos header files\n#c\nenum CLError {\n#ifdef __APPLE__\n cL_PLATFORM_NOT_FOUND_KHR=-1001,\n#else\n cL_PLATFORM_NOT_FOUND_KHR=CL_PLATFORM_NOT_FOUND_KHR,\n#endif\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_PLATFORM_NOT_FOUND_khr', Returned when no .icd (platform drivers)\n can be properly loaded.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMapFlag {\n cL_MAP_READ=CL_MAP_READ,\n cL_MAP_WRITE=CL_MAP_WRITE\n };\n#endc\n{#enum CLMapFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes =\n\tbitmaskToFlags \n\t\t[CL_DEVICE_TYPE_CPU\n\t\t,CL_DEVICE_TYPE_GPU\n\t\t,CL_DEVICE_TYPE_ACCELERATOR\n\t\t,CL_DEVICE_TYPE_DEFAULT\n\t\t,CL_DEVICE_TYPE_ALL\n\t\t]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"951f81bc36f38de86eda5793e83a979a1784d746","subject":"Annotated capstone.h header","message":"Annotated capstone.h header\n","repos":"ibabushkin\/hapstone","old_file":"src\/Hapstone\/Internal\/Capstone.chs","new_file":"src\/Hapstone\/Internal\/Capstone.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-|\nModule : Hapstone.Internal.Capstone\nDescription : capstone's API header ported using C2HS + some boilerplate\nCopyright : (c) Inokentiy Babushkin, 2016\nLicense : BSD3\nMaintainer : Inokentiy Babushkin \nStability : experimental\n\nThis module contains capstone's public API, with the necessary datatypes and\nfunctions, and some boilerplate to make it usable. Thus, it exposes an IO-based\ninterface to capstone, which is a rough 1:1 translation of the capstone C\nheader to Haskell. Obviously, it isn't very ideomatic to use, so a higher-level\nAPI is present in \"Hapstone.Capstone\". The approach there is to wrap all\nnecessary cleanup and initialization and expose an ideomatic (but heavily\nabstracted) interface to capstone.\n\nThis module, on the other hand, is intended to be used when performance is more\ncritical or greater versatility is needed. This means that the abstractions\nintroduced in the C version of the library are still present, but their use has\nbeen restricted to provide more reasonable levels of safety.\n-}\nmodule Hapstone.Internal.Capstone \n ( -- * Datatypes\n Csh\n , CsArch(..)\n , CsSupport(..)\n , CsMode(..)\n , CsOption(..)\n , CsOptionState(..)\n , CsOperand(..)\n , CsGroup(..)\n -- * Skipdata setup\n -- $skipdata\n , CsSkipdataCallback\n , CsSkipdataStruct(..)\n , csSetSkipdata\n -- * Instruction representation\n , ArchInfo(..)\n -- $instructions\n , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , peekArch\n , peekArrayArch\n -- * Capstone API\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#include \n\n{#context lib = \"capstone\"#}\n\nimport Control.Monad (join, (>=>))\n\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String ( CString, peekCString\n , newCString, castCharToCChar, castCCharToChar)\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}\n deriving (Show, Eq, Bounded)#}\n\n-- | support constants\n{#enum define CsSupport\n { CS_SUPPORT_DIET as CsSupportDiet\n , CS_SUPPORT_X86_REDUCE as CsSupportX86Reduce}\n deriving (Show, Eq, Bounded)#}\n\n-- | working modes\n{#enum cs_mode as CsMode {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- TODO: we will skip user defined dynamic memory routines for now\n\n-- TODO: add cs_opt_mnem struct (yay for naming)\n\n-- | options are, interestingly, represented by different types: an option\n{#enum cs_opt_type as CsOption {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n-- | ... and a state of an option\n{#enum cs_opt_value as CsOptionState {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- | arch-uniting operand type\n{#enum cs_op_type as CsOperand {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- TODO: find a place for cs_ac_type\n\n-- | arch-uniting instruction group type\n{#enum cs_group_type as CsGroup {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- $skipdata\n-- SKIPDATA is an option supported by the capstone disassembly engine, that\n-- allows to skip data which can't be disassembled and to represent it in form\n-- of pseudo-instructions. The types and functions given here attempt to mirror\n-- capstone's setup of this option, and a more high-level interface is\n-- available in \"Hapstone.Capstone\".\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 deriving (Show, Eq)\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) = do\n csOption h CsOptSkipdata CsOptOn\n with s (csOption h CsOptSkipdataSetup . fromIntegral . ptrToWordPtr)\n\n-- | architecture specific information\ndata ArchInfo\n = X86 X86.CsX86 -- ^ x86 architecture\n | Arm64 Arm64.CsArm64 -- ^ ARM64 architecture\n | Arm Arm.CsArm -- ^ ARM architecture\n | Mips Mips.CsMips -- ^ MIPS architecture\n | Ppc Ppc.CsPpc -- ^ PPC architecture\n | Sparc Sparc.CsSparc -- ^ SPARC architecture\n | SysZ SystemZ.CsSysZ -- ^ SystemZ architecture\n | XCore XCore.CsXCore -- ^ XCore architecture\n deriving (Show, Eq)\n\n-- | instruction information\ndata CsDetail = CsDetail\n { regsRead :: [Word8] -- ^ registers read by this instruction\n , regsWrite :: [Word8] -- ^ registers written by this instruction\n , groups :: [Word8] -- ^ instruction groups this instruction belongs to\n , archInfo :: Maybe ArchInfo -- ^ (optional) architecture-specific info\n } deriving (Show, Eq)\n\n-- $instructions\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 corresponding C code would do. Thus, the\n-- peek implementation does not get architecture information, use peekDetail\n-- for that.\n\ninstance Storable CsDetail where\n sizeOf _ = 1528\n alignment _ = 8\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 -- ^ instruction ID\n , address :: Word64 -- ^ instruction's address in memory\n , bytes :: [Word8] -- ^ raw byte representation\n , mnemonic :: String -- ^ instruction's mnemonic\n , opStr :: String -- ^ operands\n , detail :: Maybe CsDetail -- ^ (optional) detailed info\n } deriving (Show, Eq)\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 <*> ((map castCCharToChar . takeWhile (\/=0)) <$>\n peekArray 32 (plusPtr p {#offsetof cs_insn->mnemonic#}))\n <*> ((map castCCharToChar . takeWhile (\/=0)) <$>\n peekArray 160 (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 do pokeArray (plusPtr p {#offsetof cs_insn.mnemonic#})\n (map castCharToCChar m)\n poke (plusPtr p ({#offsetof cs_insn.mnemonic#} + length m))\n (0 :: Word8)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else do pokeArray (plusPtr p {#offsetof cs_insn.op_str#})\n (map castCharToCChar o)\n poke (plusPtr p ({#offsetof cs_insn.op_str#} + length o))\n (0 :: Word8)\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 \npeekArch :: CsArch -> Ptr CsInsn -> IO CsInsn\npeekArch 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-- | an arch-sensitive peekElemOff for cs_insn\npeekElemOffArch :: CsArch -> Ptr CsInsn -> Int -> IO CsInsn\npeekElemOffArch arch ptr off =\n peekArch arch (plusPtr ptr (off * sizeOf (undefined :: CsInsn)))\n\n-- | an arch-sensitive peekArray for cs_insn\npeekArrayArch :: CsArch -> Int -> Ptr CsInsn -> IO [CsInsn]\npeekArrayArch arch num ptr\n | num <= 0 = return []\n | otherwise = f (num-1) []\n where\n f 0 acc = do e <- peekElemOffArch arch ptr 0; return (e:acc)\n f n acc = do e <- peekElemOffArch arch ptr n; f (n-1) (e:acc)\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}\n deriving (Show, Eq, Bounded)#}\n\n-- | get the library version\n{#fun pure cs_version as ^\n {alloca- `Int' peekNum*, alloca- `Int' peekNum*} -> `Int'#}\n\nforeign import ccall \"capstone\/capstone.h cs_support\"\n csSupport' :: CInt -> Bool\n-- | get information on supported features\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 csClose' {id `Ptr Csh'} -> `CsErr'#}\ncsClose :: Csh -> IO CsErr\ncsClose = new >=> csClose'\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 pure cs_strerror as ^ {`CsErr'} -> `String'#}\n\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\n-- | disassemble a buffer\ncsDisasm :: CsArch -> Csh -> [Word8] -> Word64 -> Int -> IO [CsInsn]\ncsDisasm arch 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 <- peekArrayArch arch 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 structure\n{#fun cs_malloc as ^ {`Csh'} -> `Ptr CsInsn' castPtr#}\n\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\n-- | disassemble one instruction at a time\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 <- new array\n sizePtr <- new . fromIntegral $ length bytes\n addrPtr <- new $ 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\nforeign import ccall \"capstone\/capstone.h cs_insn_group\"\n csInsnGroup' :: Csh -> Ptr CsInsn -> IO Bool\n-- | check whether an instruction is member of a group\ncsInsnGroup :: Csh -> CsInsn -> Bool\ncsInsnGroup h i = unsafePerformIO . withCast i $ csInsnGroup' h\n\nforeign import ccall \"capstone\/capstone.h cs_reg_read\"\n csRegRead' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\n-- | check whether an instruction reads from a register\ncsRegRead :: Csh -> CsInsn -> Int -> Bool\ncsRegRead h i =\n unsafePerformIO . withCast i . flip (csRegRead' h) . fromIntegral\n\nforeign import ccall \"capstone\/capstone.h cs_reg_write\"\n csRegWrite' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\n-- | check whether an instruction writes to a register\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\n-- TODO: bind to cs_regs_access\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-|\nModule : Hapstone.Internal.Capstone\nDescription : capstone's API header ported using C2HS + some boilerplate\nCopyright : (c) Inokentiy Babushkin, 2016\nLicense : BSD3\nMaintainer : Inokentiy Babushkin \nStability : experimental\n\nThis module contains capstone's public API, with the necessary datatypes and\nfunctions, and some boilerplate to make it usable. Thus, it exposes an IO-based\ninterface to capstone, which is a rough 1:1 translation of the capstone C\nheader to Haskell. Obviously, it isn't very ideomatic to use, so a higher-level\nAPI is present in \"Hapstone.Capstone\". The approach there is to wrap all\nnecessary cleanup and initialization and expose an ideomatic (but heavily\nabstracted) interface to capstone.\n\nThis module, on the other hand, is intended to be used when performance is more\ncritical or greater versatility is needed. This means that the abstractions\nintroduced in the C version of the library are still present, but their use has\nbeen restricted to provide more reasonable levels of safety.\n-}\nmodule Hapstone.Internal.Capstone \n ( -- * Datatypes\n Csh\n , CsArch(..)\n , CsSupport(..)\n , CsMode(..)\n , CsOption(..)\n , CsOptionState(..)\n , CsOperand(..)\n , CsGroup(..)\n -- * Skipdata setup\n -- $skipdata\n , CsSkipdataCallback\n , CsSkipdataStruct(..)\n , csSetSkipdata\n -- * Instruction representation\n , ArchInfo(..)\n -- $instructions\n , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , peekArch\n , peekArrayArch\n -- * Capstone API\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#include \n\n{#context lib = \"capstone\"#}\n\nimport Control.Monad (join, (>=>))\n\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String ( CString, peekCString\n , newCString, castCharToCChar, castCCharToChar)\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}\n deriving (Show, Eq, Bounded)#}\n\n-- | support constants\n{#enum define CsSupport\n { CS_SUPPORT_DIET as CsSupportDiet\n , CS_SUPPORT_X86_REDUCE as CsSupportX86Reduce}\n deriving (Show, Eq, Bounded)#}\n\n-- | working modes\n{#enum cs_mode as CsMode {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- TODO: we will skip user defined dynamic memory routines for now\n\n-- | options are, interestingly, represented by different types: an option\n{#enum cs_opt_type as CsOption {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n-- | ... and a state of an option\n{#enum cs_opt_value as CsOptionState {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- | arch-uniting operand type\n{#enum cs_op_type as CsOperand {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- | arch-uniting instruction group type\n{#enum cs_group_type as CsGroup {underscoreToCase}\n deriving (Show, Eq, Bounded)#}\n\n-- $skipdata\n-- SKIPDATA is an option supported by the capstone disassembly engine, that\n-- allows to skip data which can't be disassembled and to represent it in form\n-- of pseudo-instructions. The types and functions given here attempt to mirror\n-- capstone's setup of this option, and a more high-level interface is\n-- available in \"Hapstone.Capstone\".\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 deriving (Show, Eq)\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) = do\n csOption h CsOptSkipdata CsOptOn\n with s (csOption h CsOptSkipdataSetup . fromIntegral . ptrToWordPtr)\n\n-- | architecture specific information\ndata ArchInfo\n = X86 X86.CsX86 -- ^ x86 architecture\n | Arm64 Arm64.CsArm64 -- ^ ARM64 architecture\n | Arm Arm.CsArm -- ^ ARM architecture\n | Mips Mips.CsMips -- ^ MIPS architecture\n | Ppc Ppc.CsPpc -- ^ PPC architecture\n | Sparc Sparc.CsSparc -- ^ SPARC architecture\n | SysZ SystemZ.CsSysZ -- ^ SystemZ architecture\n | XCore XCore.CsXCore -- ^ XCore architecture\n deriving (Show, Eq)\n\n-- | instruction information\ndata CsDetail = CsDetail\n { regsRead :: [Word8] -- ^ registers read by this instruction\n , regsWrite :: [Word8] -- ^ registers written by this instruction\n , groups :: [Word8] -- ^ instruction groups this instruction belongs to\n , archInfo :: Maybe ArchInfo -- ^ (optional) architecture-specific info\n } deriving (Show, Eq)\n\n-- $instructions\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 corresponding C code would do. Thus, the\n-- peek implementation does not get architecture information, use peekDetail\n-- for that.\n\ninstance Storable CsDetail where\n sizeOf _ = 1528\n alignment _ = 8\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 -- ^ instruction ID\n , address :: Word64 -- ^ instruction's address in memory\n , bytes :: [Word8] -- ^ raw byte representation\n , mnemonic :: String -- ^ instruction's mnemonic\n , opStr :: String -- ^ operands\n , detail :: Maybe CsDetail -- ^ (optional) detailed info\n } deriving (Show, Eq)\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 <*> ((map castCCharToChar . takeWhile (\/=0)) <$>\n peekArray 32 (plusPtr p {#offsetof cs_insn->mnemonic#}))\n <*> ((map castCCharToChar . takeWhile (\/=0)) <$>\n peekArray 160 (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 do pokeArray (plusPtr p {#offsetof cs_insn.mnemonic#})\n (map castCharToCChar m)\n poke (plusPtr p ({#offsetof cs_insn.mnemonic#} + length m))\n (0 :: Word8)\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else do pokeArray (plusPtr p {#offsetof cs_insn.op_str#})\n (map castCharToCChar o)\n poke (plusPtr p ({#offsetof cs_insn.op_str#} + length o))\n (0 :: Word8)\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 \npeekArch :: CsArch -> Ptr CsInsn -> IO CsInsn\npeekArch 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-- | an arch-sensitive peekElemOff for cs_insn\npeekElemOffArch :: CsArch -> Ptr CsInsn -> Int -> IO CsInsn\npeekElemOffArch arch ptr off =\n peekArch arch (plusPtr ptr (off * sizeOf (undefined :: CsInsn)))\n\n-- | an arch-sensitive peekArray for cs_insn\npeekArrayArch :: CsArch -> Int -> Ptr CsInsn -> IO [CsInsn]\npeekArrayArch arch num ptr\n | num <= 0 = return []\n | otherwise = f (num-1) []\n where\n f 0 acc = do e <- peekElemOffArch arch ptr 0; return (e:acc)\n f n acc = do e <- peekElemOffArch arch ptr n; f (n-1) (e:acc)\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}\n deriving (Show, Eq, Bounded)#}\n\n-- | get the library version\n{#fun pure cs_version as ^\n {alloca- `Int' peekNum*, alloca- `Int' peekNum*} -> `Int'#}\n\nforeign import ccall \"capstone\/capstone.h cs_support\"\n csSupport' :: CInt -> Bool\n-- | get information on supported features\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 csClose' {id `Ptr Csh'} -> `CsErr'#}\ncsClose :: Csh -> IO CsErr\ncsClose = new >=> csClose'\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 pure cs_strerror as ^ {`CsErr'} -> `String'#}\n\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\n-- | disassemble a buffer\ncsDisasm :: CsArch -> Csh -> [Word8] -> Word64 -> Int -> IO [CsInsn]\ncsDisasm arch 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 <- peekArrayArch arch 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 structure\n{#fun cs_malloc as ^ {`Csh'} -> `Ptr CsInsn' castPtr#}\n\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\n-- | disassemble one instruction at a time\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 <- new array\n sizePtr <- new . fromIntegral $ length bytes\n addrPtr <- new $ 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\nforeign import ccall \"capstone\/capstone.h cs_insn_group\"\n csInsnGroup' :: Csh -> Ptr CsInsn -> IO Bool\n-- | check whether an instruction is member of a group\ncsInsnGroup :: Csh -> CsInsn -> Bool\ncsInsnGroup h i = unsafePerformIO . withCast i $ csInsnGroup' h\n\nforeign import ccall \"capstone\/capstone.h cs_reg_read\"\n csRegRead' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\n-- | check whether an instruction reads from a register\ncsRegRead :: Csh -> CsInsn -> Int -> Bool\ncsRegRead h i =\n unsafePerformIO . withCast i . flip (csRegRead' h) . fromIntegral\n\nforeign import ccall \"capstone\/capstone.h cs_reg_write\"\n csRegWrite' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\n-- | check whether an instruction writes to a register\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":"bcddbfe6d0445b05e3b43c016cb4d41c473531da","subject":"fix foreign pointer finaliser calling into haskell code","message":"fix foreign pointer finaliser calling into haskell code\n\nIgnore-this: 865b4fdd021b9a57931b71c805b163dd\n\ndarcs-hash:20090724060600-115f9-b9bc63c4ca12c44ddd70462e7dd1600554190511.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/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 free,\n malloc,\n-- malloc2D,\n-- malloc3D,\n memset,\n-- memset2D,\n-- memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr hiding (newForeignPtr)\nimport Foreign.Concurrent (newForeignPtr)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = newForeignPtr p (free_ p)\n--newDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\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\n -- ** Dynamic allocation\n free,\n malloc,\n-- malloc2D,\n-- malloc3D,\n memset,\n-- memset2D,\n-- memset3D,\n\n -- ** Marshalling\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n new,\n with,\n newArray,\n withArray,\n\n -- ** Copying\n )\n where\n\nimport Data.Int\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 :: Ptr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` cudaFree p\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO a\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO 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 -> F.peek hptr\n Just s -> moduleErr \"peek\" 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 [a]\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO [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 -> F.peekArray n hptr\n Just s -> moduleErr \"peekArray\" s\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO ()\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"poke\" s\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO ()\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO ()\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 >>= \\rv ->\n case rv of\n Nothing -> return ()\n Just s -> moduleErr \"pokeArray\" s\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\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 >> return dptr\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device\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 >> return dptr\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 new v >>= \\dptr ->\n f dptr >>= return\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 v f =\n newArray v >>= \\dptr ->\n f dptr >>= return\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":"c9d160e3863b59c57fd520d0f1fafeea17f48b78","subject":"Fix signature of callbacks that may pass NULL objects.","message":"Fix signature of callbacks that may pass NULL objects.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Widget -> IO ())\nparentSet = Signal (connect_OBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Widget -> IO ())\nhierarchyChanged = Signal (connect_OBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"741baa94d5980bc9bcc6371959755c37e36c3068","subject":"Added webResourceGetData","message":"Added webResourceGetData\n\nThis requires glib with GString patch applied.\n","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebResource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetData,\n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Returns the data of the WebResource.\nwebResourceGetData :: WebResourceClass self => self -> IO (Maybe String)\nwebResourceGetData wr =\n {#call web_resource_get_data#} (toWebResource wr) >>= readGString\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebResource\n-- Author : Andy Stewart\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-- Function `webkit_web_resource_get_data` haven't binding\n-- no idea how to handle `GString`.\n--\n-- Access to the WebKit Web Resource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebResource (\n-- * Description\n-- | A web resource encapsulates the data of the download as well as the URI, MIME type and frame name of\n-- the resource.\n\n-- * Types\n WebResource,\n WebResourceClass,\n\n-- * Constructors\n webResourceNew,\n\n-- * Methods \n webResourceGetEncoding,\n webResourceGetFrameName,\n webResourceGetMimeType,\n webResourceGetUri,\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 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-- | Returns a new WebKitWebResource. \n-- The @encoding@ can be empty. \n-- The @frameName@ can be used if the resource represents contents of an\n-- entire HTML frame, otherwise pass empty.\nwebResourceNew :: String -> Int -> String -> String -> String -> String -> IO WebResource\nwebResourceNew resData size uri mimeType encoding frameName =\n withCString resData $ \\dataPtr -> \n withCString uri $ \\uriPtr ->\n withCString mimeType $ \\mimePtr ->\n withCString encoding $ \\encodingPtr ->\n withCString frameName $ \\framePtr -> \n wrapNewGObject mkWebResource $ \n {#call web_resource_new#} dataPtr (fromIntegral size) uriPtr mimePtr encodingPtr framePtr\n\n-- | Get encoding.\nwebResourceGetEncoding :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetEncoding wr =\n {#call web_resource_get_encoding#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get frame name.\nwebResourceGetFrameName :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetFrameName wr =\n {#call web_resource_get_frame_name#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get mime type.\nwebResourceGetMimeType :: \n WebResourceClass self => self\n -> IO (Maybe String)\nwebResourceGetMimeType wr =\n {#call web_resource_get_mime_type#} (toWebResource wr) >>= maybePeek peekCString\n\n-- | Get uri.\nwebResourceGetUri :: \n WebResourceClass self => self\n -> IO String\nwebResourceGetUri wr =\n {#call web_resource_get_uri#} (toWebResource wr) >>= peekCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b16f8e1583079678150750724579a1e6d3acc456","subject":"Add Show instances to Enums.","message":"Add Show instances to Enums.\n\ndarcs-hash:20080123125608-e1dd6-dec1ef34cc2a9713292b55b9f93feda77adefdee.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Enums.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Enums.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Enumerations\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon\n--\n-- Created: 13 Januar 1999\n--\n-- Copyright (C) 1999-2005 Manuel M. T. Chakravarty, 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-- General enumeration types.\n--\nmodule Graphics.UI.Gtk.Gdk.Enums (\n CapStyle(..),\n CrossingMode(..),\n Dither(..),\n DragProtocol(..),\n DragAction(..),\n EventMask(..),\n ExtensionMode(..),\n Fill(..),\n Function(..),\n InputCondition(..),\n JoinStyle(..),\n LineStyle(..),\n NotifyType(..),\n ScrollDirection(..),\n SubwindowMode(..),\n VisibilityState(..),\n WindowState(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n GrabStatus(..),\n ) where\n\nimport System.Glib.Flags\t(Flags)\n\n{#context lib=\"gdk\" prefix =\"gdk\"#}\n\n-- | Specify the how the ends of a line is drawn.\n--\n{#enum CapStyle {underscoreToCase}#}\n\n-- | How focus is crossing the widget.\n--\n{#enum CrossingMode {underscoreToCase} deriving(Show) #}\n\n-- | Used in 'Graphics.UI.Gtk.Gdk.Drag.DragContext' to indicate the protocol according to which DND is done.\n--\n{#enum DragProtocol {underscoreToCase} deriving (Bounded,Show)#}\n\n-- | Specify the kind of action performed on a drag event.\n{#enum DragAction {underscoreToCase} deriving (Bounded,Show)#}\n\ninstance Flags DragAction\n\n-- | Specify how to dither colors onto the screen.\n--\n{#enum RgbDither as Dither {underscoreToCase} deriving(Show) #}\n\n-- | specify which events a widget will emit signals on\n--\n{#enum EventMask {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags EventMask\n\n-- | specify which input extension a widget desires\n--\n{#enum ExtensionMode {underscoreToCase} deriving(Bounded,Show)#}\n\ninstance Flags ExtensionMode\n\n-- | How objects are filled.\n--\n{#enum Fill {underscoreToCase} deriving(Show) #}\n\n-- | Determine how bitmap operations are carried out.\n--\n{#enum Function {underscoreToCase} deriving(Show) #}\n\n-- | Specify on what file condition a callback should be\n-- done.\n--\n{#enum InputCondition {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags InputCondition\n\n-- | Determines how adjacent line ends are drawn.\n--\n{#enum JoinStyle {underscoreToCase}#}\n\n-- | Determines if a line is solid or dashed.\n--\n{#enum LineStyle {underscoreToCase}#}\n\n-- | Information on from what level of the widget hierarchy the mouse\n-- cursor came.\n--\n-- ['NotifyAncestor'] The window is entered from an ancestor or left towards\n-- an ancestor.\n--\n-- ['NotifyVirtual'] The pointer moves between an ancestor and an inferior\n-- of the window.\n--\n-- ['NotifyInferior'] The window is entered from an inferior or left\n-- towards an inferior.\n--\n-- ['NotifyNonlinear'] The window is entered from or left towards a\n-- window which is neither an ancestor nor an inferior.\n--\n-- ['NotifyNonlinearVirtual'] The pointer moves between two windows which\n-- are not ancestors of each other and the window is part of the ancestor\n-- chain between one of these windows and their least common ancestor.\n--\n-- ['NotifyUnknown'] The level change does not fit into any of the other\n-- categories or could not be determined.\n--\n{#enum NotifyType {underscoreToCase} deriving(Show) #}\n\n-- | in which direction was scrolled?\n--\n{#enum ScrollDirection {underscoreToCase} deriving(Show) #}\n\n-- | Determine if child widget may be overdrawn.\n--\n{#enum SubwindowMode {underscoreToCase} deriving(Show) #}\n\n-- | visibility of a window\n--\n{#enum VisibilityState {underscoreToCase,\n\t\t\tVISIBILITY_PARTIAL as VisibilityPartialObscured}\n\t\t\t deriving(Show) #}\n\n-- | The state a @DrawWindow@ is in.\n--\n{#enum WindowState {underscoreToCase} deriving (Bounded,Show)#}\n\ninstance Flags WindowState\n\n-- | Determines a window edge or corner.\n--\n{#enum WindowEdge {underscoreToCase} deriving(Show) #}\n\n-- | These are hints for the window manager that indicate what type of function\n-- the window has. The window manager can use this when determining decoration\n-- and behaviour of the window. The hint must be set before mapping the window.\n--\n-- See the extended window manager hints specification for more details about\n-- window types.\n--\n{#enum WindowTypeHint {underscoreToCase} #}\n\n-- | Defines the reference point of a window and the meaning of coordinates\n-- passed to 'Graphics.UI.Gtk.Windows.Window.windowMove'. See\n-- 'Graphics.UI.Gtk.Windows.Window.windowMove' and the \"implementation notes\"\n-- section of the extended window manager hints specification for more details.\n--\n{#enum Gravity {underscoreToCase} deriving(Show) #}\n\n-- | Returned by 'pointerGrab' and 'keyboardGrab' to indicate success or the\n-- reason for the failure of the grab attempt.\n--\n-- [@GrabSuccess@] the resource was successfully grabbed.\n--\n-- [@GrabAlreadyGrabbed@] the resource is actively grabbed by another client.\n--\n-- [@GrabInvalidTime@] the resource was grabbed more recently than the\n-- specified time.\n--\n-- [@GrabNotViewable@] the grab window or the confine_to window are not\n-- viewable.\n--\n-- [@GrabFrozen@] the resource is frozen by an active grab of another client.\n--\n{#enum GrabStatus {underscoreToCase} deriving(Show) #}\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Enumerations\n--\n-- Author : Manuel M. T. Chakravarty, Axel Simon\n--\n-- Created: 13 Januar 1999\n--\n-- Copyright (C) 1999-2005 Manuel M. T. Chakravarty, 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-- General enumeration types.\n--\nmodule Graphics.UI.Gtk.Gdk.Enums (\n CapStyle(..),\n CrossingMode(..),\n Dither(..),\n DragProtocol(..),\n DragAction(..),\n EventMask(..),\n ExtensionMode(..),\n Fill(..),\n Function(..),\n InputCondition(..),\n JoinStyle(..),\n LineStyle(..),\n NotifyType(..),\n ScrollDirection(..),\n SubwindowMode(..),\n VisibilityState(..),\n WindowState(..),\n WindowEdge(..),\n WindowTypeHint(..),\n Gravity(..),\n GrabStatus(..),\n ) where\n\nimport System.Glib.Flags\t(Flags)\n\n{#context lib=\"gdk\" prefix =\"gdk\"#}\n\n-- | Specify the how the ends of a line is drawn.\n--\n{#enum CapStyle {underscoreToCase}#}\n\n-- | How focus is crossing the widget.\n--\n{#enum CrossingMode {underscoreToCase}#}\n\n-- | Used in 'Graphics.UI.Gtk.Gdk.Drag.DragContext' to indicate the protocol according to which DND is done.\n--\n{#enum DragProtocol {underscoreToCase} deriving (Bounded)#}\n\n-- | Specify the kind of action performed on a drag event.\n{#enum DragAction {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags DragAction\n\n-- | Specify how to dither colors onto the screen.\n--\n{#enum RgbDither as Dither {underscoreToCase}#}\n\n-- | specify which events a widget will emit signals on\n--\n{#enum EventMask {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags EventMask\n\n-- | specify which input extension a widget desires\n--\n{#enum ExtensionMode {underscoreToCase} deriving(Bounded)#}\n\ninstance Flags ExtensionMode\n\n-- | How objects are filled.\n--\n{#enum Fill {underscoreToCase}#}\n\n-- | Determine how bitmap operations are carried out.\n--\n{#enum Function {underscoreToCase}#}\n\n-- | Specify on what file condition a callback should be\n-- done.\n--\n{#enum InputCondition {underscoreToCase} deriving(Bounded) #}\n\ninstance Flags InputCondition\n\n-- | Determines how adjacent line ends are drawn.\n--\n{#enum JoinStyle {underscoreToCase}#}\n\n-- | Determines if a line is solid or dashed.\n--\n{#enum LineStyle {underscoreToCase}#}\n\n-- | Information on from what level of the widget hierarchy the mouse\n-- cursor came.\n--\n-- ['NotifyAncestor'] The window is entered from an ancestor or left towards\n-- an ancestor.\n--\n-- ['NotifyVirtual'] The pointer moves between an ancestor and an inferior\n-- of the window.\n--\n-- ['NotifyInferior'] The window is entered from an inferior or left\n-- towards an inferior.\n--\n-- ['NotifyNonlinear'] The window is entered from or left towards a\n-- window which is neither an ancestor nor an inferior.\n--\n-- ['NotifyNonlinearVirtual'] The pointer moves between two windows which\n-- are not ancestors of each other and the window is part of the ancestor\n-- chain between one of these windows and their least common ancestor.\n--\n-- ['NotifyUnknown'] The level change does not fit into any of the other\n-- categories or could not be determined.\n--\n{#enum NotifyType {underscoreToCase}#}\n\n-- | in which direction was scrolled?\n--\n{#enum ScrollDirection {underscoreToCase}#}\n\n-- | Determine if child widget may be overdrawn.\n--\n{#enum SubwindowMode {underscoreToCase}#}\n\n-- | visibility of a window\n--\n{#enum VisibilityState {underscoreToCase,\n\t\t\tVISIBILITY_PARTIAL as VisibilityPartialObscured}#}\n\n-- | The state a @DrawWindow@ is in.\n--\n{#enum WindowState {underscoreToCase} deriving (Bounded)#}\n\ninstance Flags WindowState\n\n-- | Determines a window edge or corner.\n--\n{#enum WindowEdge {underscoreToCase} #}\n\n-- | These are hints for the window manager that indicate what type of function\n-- the window has. The window manager can use this when determining decoration\n-- and behaviour of the window. The hint must be set before mapping the window.\n--\n-- See the extended window manager hints specification for more details about\n-- window types.\n--\n{#enum WindowTypeHint {underscoreToCase} #}\n\n-- | Defines the reference point of a window and the meaning of coordinates\n-- passed to 'Graphics.UI.Gtk.Windows.Window.windowMove'. See\n-- 'Graphics.UI.Gtk.Windows.Window.windowMove' and the \"implementation notes\"\n-- section of the extended window manager hints specification for more details.\n--\n{#enum Gravity {underscoreToCase} #}\n\n-- | Returned by 'pointerGrab' and 'keyboardGrab' to indicate success or the\n-- reason for the failure of the grab attempt.\n--\n-- [@GrabSuccess@] the resource was successfully grabbed.\n--\n-- [@GrabAlreadyGrabbed@] the resource is actively grabbed by another client.\n--\n-- [@GrabInvalidTime@] the resource was grabbed more recently than the\n-- specified time.\n--\n-- [@GrabNotViewable@] the grab window or the confine_to window are not\n-- viewable.\n--\n-- [@GrabFrozen@] the resource is frozen by an active grab of another client.\n--\n{#enum GrabStatus {underscoreToCase} #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1f955f31091344051459d19d330b7e48a1bb3f95","subject":"gconf: S.G.G.GConfValue: remove -fallow-overlapping-instances (it's handled in the makefile)","message":"gconf: S.G.G.GConfValue: remove -fallow-overlapping-instances (it's handled in the makefile)\n\ndarcs-hash:20090111160247-21862-7571a4eb3a7299962be7cefe342374ffbc433d01.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_contents":"-- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Control.Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","old_contents":"{-# OPTIONS -fallow-overlapping-instances #-} -- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Control.Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"5a4d35926d61f847939f20bcdb9d7819349961d7","subject":"Missing link","message":"Missing link\n\ndarcs-hash:20080601160318-1ef02-9105ea0caee61d7f7174051436761cd9c6dbb1eb.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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and mainGUI then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"ccdb903589b683d946d3e78cf52042b0c467e70e","subject":"force the result","message":"force the result\n\notherwise multiple calls to 'flInput' or 'flPassword' may appear to\nhave the same result even if the user typed different things.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input as flInput' { unsafeToCString `T.Text' } -> `Maybe T.Text' unsafeFromMaybeCString #}\nflInput :: T.Text -> IO (Maybe T.Text)\nflInput msg = do\n r <- flInput' msg\n\n -- force the result, otherwise multiple calls to 'flInput' may appear to have\n -- the same result even if the user typed different things\n r `seq` return r\n\n{# fun flc_password as flPassword' { unsafeToCString `T.Text' } -> `Maybe T.Text' unsafeFromMaybeCString #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- flPassword' msg\n\n -- force the result, otherwise multiple calls to 'flPassword' may appear to have\n -- the same result even if the user typed different things\n r `seq` return r\n\n{# fun flc_message as flMessage' { unsafeToCString `T.Text' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage = flMessage'\n\n{# fun flc_alert as flAlert' { unsafeToCString `T.Text' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert = flAlert'\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input as flInput' { unsafeToCString `T.Text' } -> `Maybe T.Text' unsafeFromMaybeCString #}\nflInput :: T.Text -> IO (Maybe T.Text)\nflInput = flInput'\n\n{# fun flc_password as flPassword' { unsafeToCString `T.Text' } -> `Maybe T.Text' unsafeFromMaybeCString #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword = flPassword'\n\n{# fun flc_message as flMessage' { unsafeToCString `T.Text' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage = flMessage'\n\n{# fun flc_alert as flAlert' { unsafeToCString `T.Text' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert = flAlert'\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"330cf8640d4086c0da7136e7d56aa344628b9e5f","subject":"Fix the bug of `iconInfoGetEmbeddedRect`","message":"Fix the bug of `iconInfoGetEmbeddedRect`\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> Rectangle -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates; coordinates are only stored when this function \n -> IO Bool -- ^ returns 'True' if the icon has an embedded rectangle\niconInfoGetEmbeddedRect self rectangle =\n liftM toBool $\n with rectangle $ \\ rectanglePtr -> \n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectanglePtr)\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1589798e6542c7d125be0affdaeca15770b8aac3","subject":"Tests've shown that \"wait\" was not working with OpenMPI.","message":"Tests've shown that \"wait\" was not working with OpenMPI.\n\nReason: in OpenMPI, MPI_Request is a pointer to some structure.\nMPI_Wait expected arg of type (MPI_Request*), that is - pointer to\npointer to structure.\n\nHowever, castPtr was silenty casting one pointer to another, wreaking\nhavoc.\n\nFix: extra level of pointerness added as needed. Incidentally, code\nfor \"wait\" is now similar for both implementations (OpenMPI and\nMPICH2) and works (according to tests).\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , getFutureStatus\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\ngetFutureStatus :: Future a -> IO Status\ngetFutureStatus = readMVar . futureStatus\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n s <- peek statusPtr\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n","old_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , getFutureStatus\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\ngetFutureStatus :: Future a -> IO Status\ngetFutureStatus = readMVar . futureStatus\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\n#ifdef MPICH2\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n#else\nwait request =\n alloca $ \\statusPtr -> do\n checkError $ Internal.wait (castPtr request) (castPtr statusPtr)\n peek statusPtr\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"82acf6199993c03086a0aad50892303a3a35449d","subject":"refs #8: add clEnqueueCopyImage clEnqueueCopyImageToBuffer clEnqueueCopyBufferToImage","message":"refs #8: add clEnqueueCopyImage clEnqueueCopyImageToBuffer clEnqueueCopyBufferToImage\n","repos":"IFCA\/opencl,Delan90\/opencl,Delan90\/opencl,IFCA\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.chs","new_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.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.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, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ Must be a valid\n -- command-queue. The OpenCL\n -- context associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ Must be a valid\n -- command-queue. The OpenCL\n -- context associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO 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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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":"{- 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.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, clEnqueueReadImage, \n clEnqueueWriteImage,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a => CLCommandQueue -- ^ Refers to the\n -- command-queue in which the\n -- read command will be\n -- queued. command_queue and\n -- image must be created with\n -- the same OpenCL contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a => CLCommandQueue -- ^ Refers to the\n -- command-queue in which\n -- the write command will be\n -- queued. command_queue and\n -- image must be created\n -- with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO 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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c87405027961bbb7846da3bbbf86d4a7a7c9b869","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\/DataType.chs","new_file":"src\/GDAL\/Internal\/DataType.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.DataType (\n GDALType (..)\n , KnownDataType\n , DataType (..)\n , CDataTypeT\n , GType\n\n , dataType\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n) where\n\n#include \"gdal.h\"\n#include \"bindings.h\"\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Data.Int (Int8, Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types\nimport Foreign.C.String (withCString)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (toEnumC, fromEnumC)\n\n\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\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\n------------------------------------------------------------------------------\n-- GDALType\n------------------------------------------------------------------------------\ntype CDataTypeT a = GType (DataTypeT a)\n\nclass (Eq a , Storable a , KnownDataType (DataTypeT a)) => GDALType a where\n type DataTypeT a :: DataType\n toGType :: St.Vector a -> St.Vector (CDataTypeT a)\n fromGType :: St.Vector (CDataTypeT a) -> St.Vector a\n toGTypeM :: St.MVector s a -> St.MVector s (CDataTypeT a)\n fromGTypeM :: St.MVector s (CDataTypeT a) -> St.MVector s a\n\n toCDouble :: a -> CDouble\n fromCDouble :: CDouble -> a\n\ntype family GType (k :: DataType) where\n GType 'GDT_Byte = CUChar\n GType 'GDT_UInt16 = CUShort\n GType 'GDT_UInt32 = CUInt\n GType 'GDT_Int16 = CShort\n GType 'GDT_Int32 = CInt\n GType 'GDT_Float32 = CFloat\n GType 'GDT_Float64 = CDouble\n GType 'GDT_CInt16 = CComplex CShort\n GType 'GDT_CInt32 = CComplex CInt\n GType 'GDT_CFloat32 = CComplex CFloat\n GType 'GDT_CFloat64 = CComplex CDouble\n\nnewtype CComplex a = CComplex (Complex a)\n deriving (Eq, Show)\n\nclass (Storable (GType k), Eq (GType k)) => KnownDataType (k :: DataType) where\n dataTypeVal :: Proxy (k :: DataType) -> DataType\n\ndataType :: forall a. GDALType a => Proxy a -> DataType\ndataType _ = dataTypeVal (Proxy :: Proxy (DataTypeT a))\n{-# INLINE dataType #-}\n\ninstance KnownDataType 'GDT_Byte where dataTypeVal _ = GDT_Byte\ninstance KnownDataType 'GDT_UInt16 where dataTypeVal _ = GDT_UInt16\ninstance KnownDataType 'GDT_UInt32 where dataTypeVal _ = GDT_UInt32\ninstance KnownDataType 'GDT_Int16 where dataTypeVal _ = GDT_Int16\ninstance KnownDataType 'GDT_Int32 where dataTypeVal _ = GDT_Int32\ninstance KnownDataType 'GDT_Float32 where dataTypeVal _ = GDT_Float32\ninstance KnownDataType 'GDT_Float64 where dataTypeVal _ = GDT_Float64\n#ifdef STORABLE_COMPLEX\ninstance KnownDataType 'GDT_CInt16 where dataTypeVal _ = GDT_CInt16\ninstance KnownDataType 'GDT_CInt32 where dataTypeVal _ = GDT_CInt32\ninstance KnownDataType 'GDT_CFloat32 where dataTypeVal _ = GDT_CFloat32\ninstance KnownDataType 'GDT_CFloat64 where dataTypeVal _ = GDT_CFloat64\n#endif\n\n\ninstance GDALType Word8 where\n type DataTypeT Word8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n type DataTypeT Word16 = 'GDT_UInt16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n type DataTypeT Word32 = 'GDT_UInt32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int8 where\n type DataTypeT Int8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = St.unsafeCast\n fromGType = St.unsafeCast\n toGTypeM = Stm.unsafeCast\n fromGTypeM = Stm.unsafeCast\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n type DataTypeT Int16 = 'GDT_Int16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n type DataTypeT Int32 = 'GDT_Int32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n type DataTypeT Float = 'GDT_Float32\n fromCDouble = realToFrac\n toCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n type DataTypeT Double = 'GDT_Float64\n toCDouble = realToFrac\n fromCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\n\nderiving instance Storable a => Storable (CComplex a)\n\ninstance GDALType (Complex Int16) where\n type DataTypeT (Complex Int16) = 'GDT_CInt16\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n type DataTypeT (Complex Int32) = 'GDT_CInt32\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n type DataTypeT (Complex Float) = 'GDT_CFloat32\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n type DataTypeT (Complex Double) = 'GDT_CFloat64\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\nmodule GDAL.Internal.DataType (\n GDALType (..)\n , KnownDataType\n , DataType (..)\n , CDataTypeT\n , GType\n\n , dataType\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n) where\n\n#include \"gdal.h\"\n#include \"bindings.h\"\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Data.Int (Int8, Int16, Int32)\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Word (Word8, Word16, Word32)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types\nimport Foreign.C.String (withCString)\nimport Foreign.Marshal.Utils (toBool)\nimport Foreign.Ptr (Ptr)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (toEnumC, fromEnumC)\n\n\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\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\n------------------------------------------------------------------------------\n-- GDALType\n------------------------------------------------------------------------------\ntype CDataTypeT a = GType (DataTypeT a)\n\nclass (Eq a , Storable a , KnownDataType (DataTypeT a)) => GDALType a where\n type DataTypeT a :: DataType\n toGType :: St.Vector a -> St.Vector (CDataTypeT a)\n fromGType :: St.Vector (CDataTypeT a) -> St.Vector a\n toGTypeM :: St.MVector s a -> St.MVector s (CDataTypeT a)\n fromGTypeM :: St.MVector s (CDataTypeT a) -> St.MVector s a\n\n toCDouble :: a -> CDouble\n fromCDouble :: CDouble -> a\n\ntype family GType (k :: DataType) where\n GType 'GDT_Byte = CUChar\n GType 'GDT_UInt16 = CUShort\n GType 'GDT_UInt32 = CUInt\n GType 'GDT_Int16 = CShort\n GType 'GDT_Int32 = CInt\n GType 'GDT_Float32 = CFloat\n GType 'GDT_Float64 = CDouble\n GType 'GDT_CInt16 = CComplex CShort\n GType 'GDT_CInt32 = CComplex CInt\n GType 'GDT_CFloat32 = CComplex CFloat\n GType 'GDT_CFloat64 = CComplex CDouble\n\nnewtype CComplex a = CComplex (Complex a)\n deriving (Eq, Show)\n\nclass (Storable (GType k), Eq (GType k)) => KnownDataType (k :: DataType) where\n dataTypeVal :: Proxy (k :: DataType) -> DataType\n\ndataType :: forall a. GDALType a => Proxy a -> DataType\ndataType _ = dataTypeVal (Proxy :: Proxy (DataTypeT a))\n{-# INLINE dataType #-}\n\ninstance KnownDataType 'GDT_Byte where dataTypeVal _ = GDT_Byte\ninstance KnownDataType 'GDT_UInt16 where dataTypeVal _ = GDT_UInt16\ninstance KnownDataType 'GDT_UInt32 where dataTypeVal _ = GDT_UInt32\ninstance KnownDataType 'GDT_Int16 where dataTypeVal _ = GDT_Int16\ninstance KnownDataType 'GDT_Int32 where dataTypeVal _ = GDT_Int32\ninstance KnownDataType 'GDT_Float32 where dataTypeVal _ = GDT_Float32\ninstance KnownDataType 'GDT_Float64 where dataTypeVal _ = GDT_Float64\ninstance KnownDataType 'GDT_CInt16 where dataTypeVal _ = GDT_CInt16\ninstance KnownDataType 'GDT_CInt32 where dataTypeVal _ = GDT_CInt32\ninstance KnownDataType 'GDT_CFloat32 where dataTypeVal _ = GDT_CFloat32\ninstance KnownDataType 'GDT_CFloat64 where dataTypeVal _ = GDT_CFloat64\n\n\ninstance GDALType Word8 where\n type DataTypeT Word8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n type DataTypeT Word16 = 'GDT_UInt16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n type DataTypeT Word32 = 'GDT_UInt32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int8 where\n type DataTypeT Int8 = 'GDT_Byte\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = St.unsafeCast\n fromGType = St.unsafeCast\n toGTypeM = Stm.unsafeCast\n fromGTypeM = Stm.unsafeCast\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n type DataTypeT Int16 = 'GDT_Int16\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n type DataTypeT Int32 = 'GDT_Int32\n toCDouble = fromIntegral\n fromCDouble = truncate\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n type DataTypeT Float = 'GDT_Float32\n fromCDouble = realToFrac\n toCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n type DataTypeT Double = 'GDT_Float64\n toCDouble = realToFrac\n fromCDouble = realToFrac\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\n\nderiving instance Storable a => Storable (CComplex a)\n\ninstance GDALType (Complex Int16) where\n type DataTypeT (Complex Int16) = 'GDT_CInt16\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n type DataTypeT (Complex Int32) = 'GDT_CInt32\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n type DataTypeT (Complex Float) = 'GDT_CFloat32\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n type DataTypeT (Complex Double) = 'GDT_CFloat64\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n toGType = coerce\n fromGType = coerce\n toGTypeM = coerce\n fromGTypeM = coerce\n {-# INLINE toGTypeM #-}\n {-# INLINE fromGTypeM #-}\n {-# INLINE toGType #-}\n {-# INLINE fromGType #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"98df73b65b5b1226d00b1072961e54519d3479ce","subject":"Remove extra file with conflicting case","message":"Remove extra file with conflicting case\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/GlWIndow.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/GlWIndow.chs","new_contents":"","old_contents":"{-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.GlWindow ()\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_Gl_WindowC.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 Graphics.UI.FLTK.LowLevel.Hierarchy\n\n{# fun Fl_DerivedGl_Window_flush as flush' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) GlWindow 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 ()) GlWindow 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 ()) GlWindow 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 ()) GlWindow 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 ()) GlWindow 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 ()) GlWindow 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","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"6159b658a28fc7bd2174ac1520f1263d3ffbf24c","subject":"Haddock for ComparisonResult","message":"Haddock for ComparisonResult\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/ComparisonResult.chs","new_file":"src\/Control\/Parallel\/MPI\/ComparisonResult.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"comparison_result.h\"\n\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.ComparisonResult\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\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-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.ComparisonResult (ComparisonResult (..)) where\n\n{# context prefix = \"MPI\" #}\n\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"comparison_result.h\"\n\nmodule Control.Parallel.MPI.ComparisonResult (ComparisonResult (..)) where\n\n{# context prefix = \"MPI\" #}\n\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6434fe750561c49e46d986baf7713a56c615ed6a","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","repos":"vincenthz\/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":"0eba63388bb5ac9580b078d26a853805748b2801","subject":"cleanup","message":"cleanup\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OSR.chs","new_file":"src\/GDAL\/Internal\/OSR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n\nmodule GDAL.Internal.OSR (\n SpatialReference\n , CoordinateTransformation\n\n , srsFromWkt\n , srsFromProj4\n , srsFromEPSG\n , srsFromXML\n\n , srsToWkt\n , srsToProj4\n , srsToXML\n\n , isGeographic\n , isLocal\n , isProjected\n , isSameGeogCS\n , isSame\n\n , getAngularUnits\n , getLinearUnits\n\n , coordinateTransformation\n\n , cleanup\n , initialize\n , srsFromWktIO\n , withSpatialReference\n , withMaybeSRAsCString\n , withMaybeSpatialReference\n , withCoordinateTransformation\n , newSpatialRefHandle\n , newSpatialRefBorrowedHandle\n , maybeNewSpatialRefHandle\n , maybeNewSpatialRefBorrowedHandle\n) where\n\n#include \"ogr_srs_api.h\"\n\n{# context lib = \"gdal\" prefix = \"OSR\" #}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception (catch, bracketOnError, try)\nimport Control.Monad (liftM, (>=>), when, void)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\n\nimport Foreign.C.String (CString, peekCString)\nimport Foreign.C.Types (CInt(..), CDouble(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLString (peekCPLString)\n\n{#pointer OGRSpatialReferenceH as SpatialReference foreign newtype#}\n\ninstance Show SpatialReference where\n show = show . srsToWkt\n\nsrsToWkt :: SpatialReference -> ByteString\nsrsToWkt s = exportWith fun s\n where\n fun s' p = {#call unsafe ExportToPrettyWkt as ^#} s' p 1\n\nsrsToProj4 :: SpatialReference -> ByteString\nsrsToProj4 = exportWith {#call unsafe ExportToProj4 as ^#}\n\nsrsToXML :: SpatialReference -> ByteString\nsrsToXML = exportWith fun\n where\n fun s' p = {#call unsafe ExportToXML as ^#} s' p (castPtr nullPtr)\n\nexportWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CInt)\n -> SpatialReference\n -> ByteString\nexportWith fun srs =\n unsafePerformIO $\n withSpatialReference srs $ \\pSrs ->\n peekCPLString $\n checkOGRError . fun pSrs\n{-# NOINLINE exportWith #-}\n\n\nforeign import ccall \"ogr_srs_api.h &OSRRelease\"\n c_release :: FunPtr (Ptr SpatialReference -> IO ())\n\nnewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefHandle = maybeNewSpatialRefHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefHandle alloc = bracketOnError alloc freeIfNotNull go\n where\n go p\n | p==nullPtr = return Nothing\n | otherwise = liftM (Just . SpatialReference) (newForeignPtr c_release p)\n freeIfNotNull p\n | p\/=nullPtr = {#call unsafe OSRRelease as ^#} p\n | otherwise = return ()\n\nnewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefBorrowedHandle =\n maybeNewSpatialRefBorrowedHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefBorrowedHandle alloc = maybeNewSpatialRefHandle $ do\n p <- alloc\n when (p \/= nullPtr) (void ({#call unsafe OSRReference as ^#} p))\n return p\n\nemptySpatialRef :: IO SpatialReference\nemptySpatialRef =\n newSpatialRefHandle ({#call unsafe NewSpatialReference as ^#} nullPtr)\n\nsrsFromWkt, srsFromProj4, srsFromXML\n :: ByteString -> Either OGRException SpatialReference\nsrsFromWkt = unsafePerformIO . (flip unsafeUseAsCString srsFromWktIO)\n{-# NOINLINE srsFromWkt #-}\n\nsrsFromWktIO :: CString -> IO (Either OGRException SpatialReference)\nsrsFromWktIO a =\n (liftM Right\n (newSpatialRefHandle ({#call unsafe NewSpatialReference as ^#} a)))\n `catch` (return . Left)\n\nsrsFromProj4 = fromImporter importFromProj4\n{-# NOINLINE srsFromProj4 #-}\n\nsrsFromXML = fromImporter importFromXML\n{-# NOINLINE srsFromXML #-}\n\nsrsFromEPSG :: Int -> Either OGRException SpatialReference\nsrsFromEPSG = fromImporter importFromEPSG\n{-# NOINLINE srsFromEPSG #-}\n\nfromImporter\n :: (SpatialReference -> a -> IO CInt) -> a\n -> Either OGRException SpatialReference\nfromImporter f s = unsafePerformIO $ do\n r <- emptySpatialRef\n try (checkOGRError (f r s) >> return r)\n{-# NOINLINE fromImporter #-}\n\n\n{#fun ImportFromProj4 as ^\n { withSpatialReference* `SpatialReference'\n , unsafeUseAsCString* `ByteString'} -> `CInt' #}\n\n{#fun ImportFromEPSG as ^\n {withSpatialReference* `SpatialReference', `Int'} -> `CInt' #}\n\n{#fun ImportFromXML as ^\n { withSpatialReference* `SpatialReference'\n , unsafeUseAsCString* `ByteString'} -> `CInt' #}\n\n{#fun pure unsafe IsGeographic as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsLocal as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsProjected as ^\n {withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSameGeogCS as ^\n { withSpatialReference* `SpatialReference'\n , withSpatialReference* `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSame as ^\n { withSpatialReference* `SpatialReference'\n , withSpatialReference* `SpatialReference'} -> `Bool'#}\n\ninstance Eq SpatialReference where\n (==) = isSame\n\ngetLinearUnits :: SpatialReference -> (Double, String)\ngetLinearUnits =\n unsafePerformIO . getUnitsWith {#call unsafe OSRGetLinearUnits as ^#}\n\ngetAngularUnits :: SpatialReference -> (Double, String)\ngetAngularUnits =\n unsafePerformIO . getUnitsWith {#call unsafe OSRGetAngularUnits as ^#}\n\ngetUnitsWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CDouble)\n -> SpatialReference\n -> IO (Double, String)\ngetUnitsWith fun s = alloca $ \\p -> do\n value <- withSpatialReference s (\\s' -> fun s' p)\n ptr <- peek p\n units <- peekCString ptr\n return (realToFrac value, units)\n\nwithMaybeSRAsCString :: Maybe SpatialReference -> (CString -> IO a) -> IO a\nwithMaybeSRAsCString Nothing = ($ nullPtr)\nwithMaybeSRAsCString (Just srs) = unsafeUseAsCString (srsToWkt srs)\n\nwithMaybeSpatialReference\n :: Maybe SpatialReference -> (Ptr SpatialReference -> IO a) -> IO a\nwithMaybeSpatialReference Nothing = ($ nullPtr)\nwithMaybeSpatialReference (Just s) = withSpatialReference s\n\n{#pointer OGRCoordinateTransformationH as CoordinateTransformation\n foreign newtype#}\n\ncoordinateTransformation\n :: SpatialReference -> SpatialReference -> Maybe CoordinateTransformation\ncoordinateTransformation source =\n unsafePerformIO . coordinateTransformationIO source\n{-# NOINLINE coordinateTransformation #-}\n\ncoordinateTransformationIO\n :: SpatialReference\n -> SpatialReference\n -> IO (Maybe CoordinateTransformation)\ncoordinateTransformationIO source target =\n bracketOnError alloc freeIfNotNull go\n where\n alloc =\n withSpatialReference source $ \\pSource ->\n withSpatialReference target $ \\pTarget ->\n {#call unsafe OCTNewCoordinateTransformation as ^#} pSource pTarget\n\n go p\n | p==nullPtr = return Nothing\n | otherwise = liftM (Just . CoordinateTransformation)\n (newForeignPtr c_destroyCT p)\n freeIfNotNull p\n | p\/=nullPtr = {#call unsafe OCTDestroyCoordinateTransformation as ^#} p\n | otherwise = return ()\n\nforeign import ccall \"ogr_srs_api.h &OCTDestroyCoordinateTransformation\"\n c_destroyCT :: FunPtr (Ptr CoordinateTransformation -> IO ())\n\n{#fun OSRCleanup as cleanup {} -> `()'#}\n\n-- | GDAL doesn't call ogr\/ogrct.cpp:LoadProj4Library in a thread-safe way\n-- (at least in 1.11.2). We indirectly make sure it is called at startup\n-- in the main thread (via 'withGDAL') with this function which creates\n-- a dummy 'CoordinateTransformation'\ninitialize :: IO ()\ninitialize = do\n dummy <- emptySpatialRef\n void (coordinateTransformationIO dummy dummy)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule GDAL.Internal.OSR (\n SpatialReference\n , CoordinateTransformation\n\n , srsFromWkt\n , srsFromProj4\n , srsFromEPSG\n , srsFromXML\n\n , srsToWkt\n , srsToProj4\n , srsToXML\n\n , coordinateTransformation\n\n , isGeographic\n , isLocal\n , isProjected\n , isSameGeogCS\n , isSame\n\n , getAngularUnits\n , getLinearUnits\n\n , cleanup\n , initialize\n , srsFromWktIO\n , withSpatialReference\n , withMaybeSRAsCString\n , withMaybeSpatialReference\n , withCoordinateTransformation\n , newSpatialRefHandle\n , newSpatialRefBorrowedHandle\n , maybeNewSpatialRefHandle\n , maybeNewSpatialRefBorrowedHandle\n) where\n\n#include \"ogr_srs_api.h\"\n\n{# context lib = \"gdal\" prefix = \"OSR\" #}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception (catch, bracketOnError, try)\nimport Control.Monad (liftM, (>=>), when, void)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\n\nimport Foreign.C.String (CString, peekCString)\nimport Foreign.C.Types (CInt(..), CDouble(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.CPLError hiding (None)\nimport GDAL.Internal.CPLString (peekCPLString)\nimport GDAL.Internal.CPLConv (cplFree)\n\n{#pointer OGRSpatialReferenceH as SpatialReference foreign newtype#}\n\ninstance Show SpatialReference where\n show = show . srsToWkt\n\nsrsToWkt :: SpatialReference -> ByteString\nsrsToWkt s = exportWith fun s\n where\n fun s' p = {#call unsafe ExportToPrettyWkt as ^#} s' p 1\n\nsrsToProj4 :: SpatialReference -> ByteString\nsrsToProj4 = exportWith {#call unsafe ExportToProj4 as ^#}\n\nsrsToXML :: SpatialReference -> ByteString\nsrsToXML = exportWith fun\n where\n fun s' p = {#call unsafe ExportToXML as ^#} s' p (castPtr nullPtr)\n\nexportWith\n :: (Ptr SpatialReference -> Ptr CString -> IO CInt)\n -> SpatialReference\n -> ByteString\nexportWith fun srs =\n unsafePerformIO $\n withSpatialReference srs $ \\pSrs ->\n peekCPLString $\n checkOGRError . fun pSrs\n{-# NOINLINE exportWith #-}\n\n\nforeign import ccall \"ogr_srs_api.h &OSRRelease\"\n c_release :: FunPtr (Ptr SpatialReference -> IO ())\n\nnewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefHandle = maybeNewSpatialRefHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefHandle alloc = bracketOnError alloc freeIfNotNull go\n where\n go p\n | p==nullPtr = return Nothing\n | otherwise = liftM (Just . SpatialReference) (newForeignPtr c_release p)\n freeIfNotNull p\n | p\/=nullPtr = {#call unsafe OSRRelease as ^#} p\n | otherwise = return ()\n\nnewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO SpatialReference\nnewSpatialRefBorrowedHandle =\n maybeNewSpatialRefBorrowedHandle >=> maybe exc return\n where exc = throwBindingException NullSpatialReference\n\nmaybeNewSpatialRefBorrowedHandle\n :: IO (Ptr SpatialReference) -> IO (Maybe SpatialReference)\nmaybeNewSpatialRefBorrowedHandle alloc = maybeNewSpatialRefHandle $ do\n p <- alloc\n when (p \/= nullPtr) (void ({#call unsafe OSRReference as ^#} p))\n return p\n\nemptySpatialRef :: IO SpatialReference\nemptySpatialRef =\n newSpatialRefHandle ({#call unsafe NewSpatialReference as ^#} nullPtr)\n\nsrsFromWkt, srsFromProj4, srsFromXML\n :: ByteString -> Either OGRException SpatialReference\nsrsFromWkt = unsafePerformIO . (flip unsafeUseAsCString srsFromWktIO)\n{-# NOINLINE srsFromWkt #-}\n\nsrsFromWktIO :: CString -> IO (Either OGRException SpatialReference)\nsrsFromWktIO a =\n (liftM Right\n (newSpatialRefHandle ({#call unsafe NewSpatialReference as ^#} a)))\n `catch` (return . Left)\n\nsrsFromProj4 = fromImporter importFromProj4\n{-# NOINLINE srsFromProj4 #-}\n\nsrsFromXML = fromImporter importFromXML\n{-# NOINLINE srsFromXML #-}\n\nsrsFromEPSG :: Int -> Either OGRException SpatialReference\nsrsFromEPSG = fromImporter importFromEPSG\n{-# NOINLINE srsFromEPSG #-}\n\nfromImporter\n :: (SpatialReference -> a -> IO CInt)\n -> a\n -> Either OGRException SpatialReference\nfromImporter f s = unsafePerformIO $ do\n r <- emptySpatialRef\n try (checkOGRError (f r s) >> return r)\n\n\n{#fun ImportFromProj4 as ^\n { withSpatialReference* `SpatialReference'\n , unsafeUseAsCString* `ByteString'} -> `CInt' id #}\n\n{#fun ImportFromEPSG as ^\n {withSpatialReference* `SpatialReference', `Int'} -> `CInt' id #}\n\n{#fun ImportFromXML as ^\n { withSpatialReference* `SpatialReference'\n , unsafeUseAsCString* `ByteString'} -> `CInt' id #}\n\n{#fun pure unsafe IsGeographic as ^\n {withSpatialReference * `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsLocal as ^\n {withSpatialReference * `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsProjected as ^\n {withSpatialReference * `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSameGeogCS as ^\n { withSpatialReference * `SpatialReference'\n , withSpatialReference * `SpatialReference'} -> `Bool'#}\n\n{#fun pure unsafe IsSame as ^\n { withSpatialReference * `SpatialReference'\n , withSpatialReference * `SpatialReference'} -> `Bool'#}\n\ninstance Eq SpatialReference where\n (==) = isSame\n\ngetLinearUnits :: SpatialReference -> (Double, String)\ngetLinearUnits = getUnitsWith {#call unsafe OSRGetLinearUnits as ^#}\n\ngetAngularUnits :: SpatialReference -> (Double, String)\ngetAngularUnits = getUnitsWith {#call unsafe OSRGetAngularUnits as ^#}\n\ngetUnitsWith ::\n (Ptr SpatialReference -> Ptr CString -> IO CDouble)\n -> SpatialReference\n -> (Double, String)\ngetUnitsWith fun s = unsafePerformIO $\n alloca $ \\p -> do\n value <- withSpatialReference s (\\s' -> fun s' p)\n ptr <- peek p\n units <- peekCString ptr\n return (realToFrac value, units)\n\nwithMaybeSRAsCString :: Maybe SpatialReference -> (CString -> IO a) -> IO a\nwithMaybeSRAsCString Nothing = ($ nullPtr)\nwithMaybeSRAsCString (Just srs) = unsafeUseAsCString (srsToWkt srs)\n\nwithMaybeSpatialReference\n :: Maybe SpatialReference -> (Ptr SpatialReference -> IO a) -> IO a\nwithMaybeSpatialReference Nothing = ($ nullPtr)\nwithMaybeSpatialReference (Just s) = withSpatialReference s\n\n{#pointer OGRCoordinateTransformationH as CoordinateTransformation\n foreign newtype#}\n\ncoordinateTransformation\n :: SpatialReference -> SpatialReference -> Maybe CoordinateTransformation\ncoordinateTransformation source target =\n unsafePerformIO $\n withSpatialReference source $ \\pSource ->\n withSpatialReference target $ \\pTarget ->\n maybeNewCoordinateTransformation pSource pTarget\n{-# NOINLINE coordinateTransformation #-}\n\nmaybeNewCoordinateTransformation\n :: Ptr SpatialReference\n -> Ptr SpatialReference\n -> IO (Maybe CoordinateTransformation)\nmaybeNewCoordinateTransformation pSource pTarget =\n bracketOnError alloc freeIfNotNull go\n where\n alloc =\n {#call unsafe OCTNewCoordinateTransformation as ^#} pSource pTarget\n go p\n | p==nullPtr = return Nothing\n | otherwise = liftM (Just . CoordinateTransformation)\n (newForeignPtr c_destroyCT p)\n freeIfNotNull p\n | p\/=nullPtr = {#call unsafe OCTDestroyCoordinateTransformation as ^#} p\n | otherwise = return ()\n\nforeign import ccall \"ogr_srs_api.h &OCTDestroyCoordinateTransformation\"\n c_destroyCT :: FunPtr (Ptr CoordinateTransformation -> IO ())\n\n{#fun OSRCleanup as cleanup {} -> `()'#}\n\ninitialize :: IO ()\ninitialize =\n void (maybeNewCoordinateTransformation nullPtr nullPtr)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f08dfc6be0e8259bc93aac9d67810e302dfbc551","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\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit","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":"8236e3514c9029d32f7cadcdc96c7e01ecbcfc05","subject":"miset_slice_scaling_flag and TODO.","message":"miset_slice_scaling_flag and TODO.\n","repos":"carlohamalainen\/hminc","old_file":"Data\/Minc\/Raw\/Base.chs","new_file":"Data\/Minc\/Raw\/Base.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Data.Minc.Raw.Base where\n\nimport Data.Minc.Utils\nimport Data.Minc.Types\n\nimport Foreign hiding (unsafePerformIO)\nimport Foreign.C\nimport System.IO.Unsafe (unsafePerformIO)\nimport Control.Monad (liftM)\n\n#include \n\n-- VOLUME FUNCTIONS\n\n-- extern int micreate_volume(const char *filename, int number_of_dimensions,\n-- midimhandle_t dimensions[],\n-- mitype_t volume_type,\n-- miclass_t volume_class,\n-- mivolumeprops_t create_props,\n-- mihandle_t *volume);\n{#fun micreate_volume{ `String', `Int',\n allocaDims- `[Ptr ()]' peekDims*,\n toCInt `MincMiType',\n toCInt `MincMiClass',\n id `Ptr ()',\n alloca- `Ptr ()' peek* } -> `Int' #}\n\n-- extern int micreate_volume_image(mihandle_t volume);\n{#fun micreate_volume_image{ id `Ptr ()' } -> `Int' #}\n\n-- FIXME How do we make a mivolumeprops_t?\n\ntoCInt :: Enum a => a -> CInt\ntoCInt = toEnum . fromEnum\n\ntoCUInt :: Enum a => a -> CUInt\ntoCUInt = toEnum . fromEnum\n\ntoCULLong :: Enum a => a -> CULLong\ntoCULLong = toEnum . fromEnum\n\n-- toCULongLong :: Enum a => a -> CULongLong\n-- toCULongLong = toEnum . fromEnum\n\n-- extern int miget_volume_dimension_count(mihandle_t volume, midimclass_t dimclass, midimattr_t attr, int *number_of_dimensions);\n{#fun miget_volume_dimension_count{ id `Ptr ()', toCInt `MincDimClass', toCUInt `MincDimAttribute', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- extern int miget_volume_voxel_count(mihandle_t volume, int *number_of_voxels);\n{#fun miget_volume_voxel_count{ id `Ptr ()', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- extern int miopen_volume(const char *filename, int mode, mihandle_t *volume);\n{#fun miopen_volume{ `String', `Int', alloca- `Ptr ()' peek* } -> `Int' #}\n\n-- extern int miclose_volume(mihandle_t volume);\n{#fun miclose_volume{ id `Ptr ()' } -> `Int' #}\n\n-- extern int miget_slice_scaling_flag(mihandle_t volume, miboolean_t *slice_scaling_flag);\n-- FIXME Might be nicer to use a Bool marshalling thing instead of a CInt (miboolean_t is just int).\n{#fun miget_slice_scaling_flag{ id `Ptr ()', alloca- `CInt' peek* } -> `Int' #}\n\n-- extern int miset_slice_scaling_flag(mihandle_t volume, miboolean_t slice_scaling_flag);\n{#fun miset_slice_scaling_flag{ id `Ptr ()', `CInt' } -> `Int' #}\n\n-- extern int miget_volume_dimensions(mihandle_t volume, midimclass_t dimclass, midimattr_t attr,\n-- miorder_t order, int array_length,\n-- midimhandle_t dimensions[]);\n{#fun miget_volume_dimensions{ id `Ptr ()', toCInt `MincDimClass', toCUInt `MincDimAttribute',\n toCInt `MincDimOrder', toCInt `Int', allocaDims- `[Ptr ()]' peekDims* } -> `Int' #}\n\n-- int miget_dimension_sizes(const midimhandle_t dimensions[], misize_t array_length,\n-- misize_t sizes[]);\n{#fun miget_dimension_sizes{ withArray* `[Ptr ()]', toCULLong `Int', allocaDimSizes- `[Int]' peekDimSizes* } -> `Int' #}\n\n\n-- int miget_dimension_separations(const midimhandle_t dimensions[],\n-- mivoxel_order_t voxel_order,\n-- misize_t array_length,\n-- double separations[]);\n{#fun miget_dimension_separations{ withArray* `[Ptr ()]', toCInt `MincVoxelOrder', toCULLong `Int',\n allocaSeparations- `[CDouble]' peekSeparations* } -> `Int' #}\n\n\n-- int miget_dimension_starts(const midimhandle_t dimensions[], mivoxel_order_t voxel_order,\n-- misize_t array_length, double starts[]);\n{#fun miget_dimension_starts{ withArray* `[Ptr ()]', toCInt `MincVoxelOrder', toCULLong `Int',\n allocaStarts- `[CDouble]' peekStarts* } -> `Int' #}\n\n-- int miget_dimension_name(midimhandle_t dimension, char **name_ptr);\n{#fun miget_dimension_name{ id `Ptr ()', alloca- `CString' peek*} -> `Int' #}\n\n-- withArrayInts :: Storable a => [a] -> (Ptr a -> IO b) -> IO b\nwithArrayInts x = withArray (map toCULLong x)\n\n-- int miget_real_value_hyperslab(mihandle_t volume,\n-- mitype_t buffer_data_type,\n-- const misize_t start[],\n-- const misize_t count[],\n-- void *buffer);\n{#fun miget_real_value_hyperslab{ id `Ptr ()',\n toCInt `MincType',\n withArrayInts* `[Int]',\n withArrayInts* `[Int]',\n id `Ptr ()' } -> `Int' #}\n\n-- int miget_data_type(mihandle_t vol, mitype_t *volume_data_type);\n{#fun miget_data_type{ id `Ptr ()', alloca- `MincType' peekMincType* } -> `Int' #}\n\n-- int miget_hyperslab_size(mitype_t volume_data_type,\n-- int n_dimensions,\n-- const hsize_t count[],\n-- misize_t *size_ptr);\n{#fun miget_hyperslab_size{ toCInt `MincType',\n toCInt `Int',\n withArrayInts* `[Int]',\n alloca- `CULLong' peekIntConv* } -> `Int' #}\n\n{-\n\nTODO\n\nint miget_slice_dimension_count(mihandle_t volume, midimclass_t dimclass,\n midimattr_t attr, int *number_of_dimensions);\n\n\/** Create a volume property list. The new list will be returned in the\n * \\a props parameter. When the program is finished\n * using the property list it should call mifree_volume_props() to free the\n * memory associated with the list.\n * \\param props A pointer to the returned volume properties handle.\n * \\ingroup mi2VPrp\n *\/\nint minew_volume_props(mivolumeprops_t *props);\n\n\/** Destroy a volume property list.\n * \\param props The volume property list to delete.\n * \\ingroup mi2VPrp\n *\/\nint mifree_volume_props(mivolumeprops_t props);\n\n\/** Get a copy of the volume property list. When the program is finished\n * using the property list it should call mifree_volume_props() to free the\n * memory associated with the list.\n * \\param volume A volume handle\n * \\param props A pointer to the returned volume properties handle.\n * \\ingroup mi2VPrp\n *\/\nint miget_volume_props(mihandle_t vol, mivolumeprops_t *props);\n\n\n\/** Set multi-resolution properties. The \\a enable_flag determines\n * whether or not thumbnail images will be calculated at all. The \\a\n * depth parameter determines the lowest-resolution image that will be\n * available. The full resolution image is considered to be image #0,\n * the half resolution image is image #1, the quarter-resolution image\n * is #2, etc. Therefore a \\a depth value of 2 implies both the half\n * and quarter resolution thumbnails will be calculated and stored in\n * the file.\n * \\param props A volume property list handle\n * \\param enable_flag TRUE if multiresolution support should be enabled in\n * this file.\n * \\param depth The maximum depth of multiresolution data\n * to support.\n * \\ingroup mi2VPrp\n *\/\nint miset_props_multi_resolution(mivolumeprops_t props, miboolean_t enable_flag,\n int depth);\n\n\n\n\/** Get multi-resolution properties. Returns the value of the \\a enable_flag\n * and \\a depth parameters.\n * \\param props A volume property list handle\n * \\param enable_flag Pointer to a boolean which will be set to TRUE if\n * multiresolution has been enabled.\n * \\param depth Pointer to a integer which will contain the maximum resolution\n * depth enabled if multiresolution is enabled.\n * \\ingroup mi2VPrp\n *\/\nint miget_props_multi_resolution(mivolumeprops_t props, miboolean_t *enable_flag,\n int *depth);\n\n\n\/** Select a different resolution from a multi-resolution image.\n * \\ingroup mi2VPrp\n *\/\nint miselect_resolution(mihandle_t volume, int depth);\n\n\n\/** Compute or recompute all resolution groups.\n *\n * \\ingroup mi2VPrp\n *\/\nint miflush_from_resolution(mihandle_t volume, int depth);\n\n\/** Set compression type for a volume property list\n * Note that enabling compression will automatically\n * enable blocking with default parameters.\n * \\param props A volume properties list\n * \\param compression_type The type of compression to use (MI_COMPRESS_NONE\n * or MI_COMPRESS_ZLIB)\n * \\ingroup mi2VPrp\n *\/\nint miset_props_compression_type(mivolumeprops_t props, micompression_t compression_type);\n\n\n\/** Get compression type for a volume property list\n * \\param props A volume property list handle\n * \\param compression_type A pointer to a variable to which the current\n * compression type will be assigned.\n * \\ingroup mi2VPrp\n *\/\nint miget_props_compression_type(mivolumeprops_t props, micompression_t *compression_type);\n\n\n\/** Set zlib compression properties for a volume list. The \\a zlib_level\n * parameter may range from 1 to 9, where higher numbers request that the\n * library attempt to use more memory (and possibly processing power) to\n * achieve the highest possible compression ratio.\n *\n * \\param props A volume property list handle\n * \\param zlib_level An integer specifying the desired compression level.\n * \\ingroup mi2VPrp\n *\/\nint miset_props_zlib_compression(mivolumeprops_t props, int zlib_level);\n\n\n\/** Get zlib compression properties from a volume property list.\n * \\param props A volume property list handle\n * \\param zlib_level Pointer to an integer variable that will receive the\n * current compression level.\n * \\ingroup mi2VPrp\n *\/\nint miget_props_zlib_compression(mivolumeprops_t props, int *zlib_level);\n\n\n\/** Set blocking structure properties for the volume\n * \\param props A volume property list handle\n * \\param edge_count\n * \\param edge_lengths\n * \\ingroup mi2VPrp\n *\/\nint miset_props_blocking(mivolumeprops_t props, int edge_count, const int *edge_lengths);\n\n\n\/** Get blocking structure properties for the volume\n * \\param props The properties structure from which to get the information\n * \\param edge_count Returns the number of edges (dimensions) in a block\n * \\param edge_lengths The lengths of the edges\n * \\param max_lengths The number of elements of the edge_lengths array\n * \\ingroup mi2VPrp\n *\/\nint miget_props_blocking(mivolumeprops_t props, int *edge_count, int *edge_lengths,\n int max_lengths);\n\n\n\/** Set properties for uniform\/nonuniform record dimension\n * \\ingroup mi2VPrp\n *\/\nint miset_props_record(mivolumeprops_t props, misize_t record_length, char *record_name);\n\n\n\/** Set the template volume flag\n * \\ingroup mi2VPrp\n *\/\nint miset_props_template(mivolumeprops_t props, int template_flag);\n\n\/** \\defgroup mi2Slice SLICE\/VOLUME SCALE FUNCTIONS *\/\n\/**\n * This function sets \\a slice_max to the maximum real value of\n * voxels in the slice containing the coordinates \\a start_positions.\n * The \\a array_length may be less than or equal to the number of dimensions\n * in the volume, extra coordinates will be ignored. Specifying too few\n * coordinates will trigger an error.\n * Coordinates must always be specified in raw file order.\n * \\ingroup mi2Slice\n *\/\nint miget_slice_max(mihandle_t volume,\n const misize_t start_positions[],\n size_t array_length, double *slice_max);\n\n\/**\n * This function sets minimum real value of\n * values in the slice containing the coordinates \\a start_positions.\n * The \\a array_length may be less than or equal to the number of dimensions\n * in the volume, extra coordinates will be ignored. Specifying too few\n * coordinates will trigger an error.\n * Coordinates must always be specified in raw file order.\n * \\ingroup mi2Slice\n *\/\nint miset_slice_max(mihandle_t volume,\n const misize_t start_positions[],\n size_t array_length, double slice_max);\n\n\n\/**\n * This function sets \\a slice_min to the minimum real value of\n * voxels in the slice containing the coordinates \\a start_positions.\n * The \\a array_length may be less than or equal to the number of dimensions\n * in the volume, extra coordinates will be ignored. Specifying too few\n * coordinates will trigger an error.\n * Coordinates must always be specified in raw file order.\n * \\ingroup mi2Slice\n *\/\nint miget_slice_min(mihandle_t volume,\n const misize_t start_positions[],\n size_t array_length, double *slice_min);\n\n\n\/**\n * This function sets minimum real value of\n * values in the slice containing the coordinates \\a start_positions.\n * The \\a array_length may be less than or equal to the number of dimensions\n * in the volume, extra coordinates will be ignored. Specifying too few\n * coordinates will trigger an error.\n * Coordinates must always be specified in raw file order.\n * \\ingroup mi2Slice\n *\/\nint miset_slice_min(mihandle_t volume,\n const misize_t start_positions[],\n size_t array_length, double slice_min);\n\n\n\/**\n * This function gets both the minimum and\n * maximum real value of voxels in the slice containing the coordinates\n * \\a start_positions. The \\a array_length may be less than or equal to\n * the number of dimensions in the volume, extra coordinates will be\n * ignored. Specifying too few coordinates will trigger an error.\n * Coordinates must always be specified in raw file order.\n * \\ingroup mi2Slice\n *\/\nint miget_slice_range(mihandle_t volume,\n const misize_t start_positions[],\n size_t array_length, double *slice_max,\n double *slice_min);\n\n\n\/**\n * This function the minimum and maximum real value of voxels in the\n * slice containing the coordinates \\a start_positions. The \\a\n * array_length may be less than or equal to the number of dimensions in\n * the volume, extra coordinates will be ignored. Specifying too few\n * coordinates will trigger an error. Coordinates must always be\n * specified in raw file order.\n * \\ingroup mi2Slice\n *\/\nint miset_slice_range(mihandle_t volume,\n const misize_t start_positions[],\n size_t array_length, double slice_max,\n double slice_min);\n\n\/**\n * This function returns the maximum real value of\n * voxels in the entire \\a volume. If per-slice scaling is enabled, this\n * function will return an error.\n * \\ingroup mi2Slice\n *\/\nint miget_volume_max(mihandle_t volume, double *slice_max);\n\n\n\/**\n * This function sets the maximum real value of\n * voxels in the entire \\a volume. If per-slice scaling is enabled, this\n * function will return an error.\n * \\ingroup mi2Slice\n *\/\nint miset_volume_max(mihandle_t volume, double slice_max);\n\n\n\/**\n * This function returns the minimum real value of\n * voxels in the entire \\a volume. If per-slice scaling is enabled, this\n * function will return an error.\n * \\ingroup mi2Slice\n *\/\nint miget_volume_min(mihandle_t volume, double *slice_min);\n\n\n\/**\n * This function sets the minimum real value of\n * voxels in the entire \\a volume. If per-slice scaling is enabled, this\n * function will return an error.\n * \\ingroup mi2Slice\n *\/\nint miset_volume_min(mihandle_t volume, double slice_min);\n\n\n\/**\n * This function retrieves the maximum and minimum real values of\n * voxels in the entire \\a volume. If per-slice scaling is enabled, this\n * function will return an error.\n * \\ingroup mi2Slice\n *\/\nint miget_volume_range(mihandle_t volume, double *volume_max,\n double *volume_min);\n\n\/**\n * This function sets the maximum and minimum real values of\n * voxels in the entire \\a volume. If per-slice scaling is enabled, this\n * function will return an error.\n * \\ingroup mi2Slice\n *\/\nint miset_volume_range(mihandle_t volume, double volume_max,\n double volume_min);\n\n\n\/** \\defgroup mi2Hyper HYPERSLAB FUNCTIONS *\/\n\n\/** Calculates and returns the number of bytes required to store the\n * hyperslab specified by the \\a n_dimensions and the\n * \\a count parameters, using hdf type id\n * \\ingroup mi2Hyper\n *\/\nvoid miget_hyperslab_size_hdf(hid_t hdf_type_id, int n_dimensions,\n const hsize_t count[],\n misize_t *size_ptr);\n\n\n\/** Reads the real values in the volume from the interval min through\n * max, mapped to the maximum representable range for the requested\n * data type. Float types is mapped to 0.0 1.0\n * \\ingroup mi2Hyper\n *\/\nint miget_hyperslab_normalized(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n double min,\n double max,\n void *buffer);\n\n\/** Writes the real values in the volume from the interval min through\n * max, mapped to the maximum representable range for the requested\n * data type. Float types is mapped to 0.0 1.0\n * \\ingroup mi2Hyper\n *\/\nint miset_hyperslab_normalized(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n double min,\n double max,\n void *buffer);\n\n\/** Get a hyperslab from the file,\n * converting voxel values into real values\n * \\ingroup mi2Hyper\n *\/\nint miget_hyperslab_with_icv(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n void *buffer);\n\n\/** Write a hyperslab to the file, converting real values into voxel values\n * \\ingroup mi2Hyper\n *\/\nint miset_hyperslab_with_icv(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n void *buffer);\n\n\/** Write a hyperslab to the file from the preallocated buffer,\n * converting from the stored \"voxel\" data range to the desired\n * \"real\" (float or double) data range, same as miset_hyperslab_with_icv\n * \\ingroup mi2Hyper\n *\/\nint miset_real_value_hyperslab(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n void *buffer);\n\n\/** Read a hyperslab from the file into the preallocated buffer,\n * with no range conversions or normalization. Type conversions will\n * be performed if necessary.\n * \\ingroup mi2Hyper\n *\/\nint miget_voxel_value_hyperslab(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n void *buffer);\n\n\/** Write a hyperslab to the file from the preallocated buffer,\n * with no range conversions or normalization. Type conversions will\n * be performed if necessary.\n * \\ingroup mi2Hyper\n *\/\nint miset_voxel_value_hyperslab(mihandle_t volume,\n mitype_t buffer_data_type,\n const misize_t start[],\n const misize_t count[],\n void *buffer);\n\n\n\/** \\defgroup mi2Cvt CONVERT FUNCTIONS *\/\n\n\/** Convert values between real (scaled) values and voxel (unscaled)\n * values. The voxel value is the unscaled value, and corresponds to the\n * value actually stored in the file, whereas the \"real\" value is the\n * value at the given location after scaling has been applied.\n *\n * The \\a coords parameter specifies the location at which the\n * conversion is performed. This is needed because MINC supports\n * per-slice scaling, therefore a conversion performed at one location\n * may differ from that performed at another location.\n *\n * \\param volume A volume handle\n * \\param coords The position for which to perform the conversion.\n * \\param ncoords The length of the \\a coords array.\n * \\param real_value The original real value, to be converted to voxel.\n * \\param voxel_value_ptr A pointer to the converted voxel value.\n * \\ingroup mi2Cvt\n *\/\nint miconvert_real_to_voxel(mihandle_t volume,\n const misize_t coords[],\n size_t ncoords,\n double real_value,\n double *voxel_value_ptr);\n\n\/** Convert values between real (scaled) values and voxel (unscaled)\n * values. The voxel value is the unscaled value, and corresponds to the\n * value actually stored in the file, whereas the \"real\" value is the\n * value at the given location after scaling has been applied.\n *\n * The \\a coords parameter specifies the location at which the\n * conversion is performed. This is needed because MINC supports\n * per-slice scaling, therefore a conversion performed at one location\n * may differ from that performed at another location.\n *\n * \\param volume A volume handle\n * \\param coords The position for which to perform the conversion.\n * \\param ncoords The length of the \\a coords array.\n * \\param voxel_value The original voxel value, to be converted to real.\n * \\param real_value_ptr A pointer to the converted real value.\n * \\ingroup mi2Cvt\n *\/\nint miconvert_voxel_to_real(mihandle_t volume,\n const misize_t coords[],\n int ncoords,\n double voxel_value,\n double *real_value_ptr);\n\n\/** Converts an N-dimensional spatial position in voxel coordinates into a\n * 3-dimensional spatial position in world coordinates.\n *\n * The returned world coordinate vector is in a standardized order, with\n * the X position first (at index 0), followed by the Y and Z coordinates.\n * The voxel coordinate vector is in the native order appropriate to the\n * file.\n *\n * \\ingroup mi2Cvt\n *\/\nint miconvert_voxel_to_world(mihandle_t volume,\n const double voxel[],\n double world[]);\n\n\/** Converts a 3-dimensional spatial position in world coordinates into a\n * N-dimensional spatial position in voxel coordinates.\n *\n * The input world coordinate vector is in a standardized order, with\n * the X position first (at index 0), followed by the Y and Z coordinates.\n * The voxel coordinate vector is in the native order appropriate to the\n * file.\n *\n * \\ingroup mi2Cvt\n *\/\nint miconvert_world_to_voxel(mihandle_t volume,\n const double world[],\n double voxel[]);\n\n\/** This function retrieves the real values of a position in the\n * MINC volume. The \"real\" value is the value at the given location\n * after scaling has been applied.\n *\n * \\param volume A volume handle\n * \\param coords The voxel position to retrieve\n * \\param ndims The number of values in the \\a coords array\n * \\param value_ptr Pointer to a double variable to hold the returned value.\n *\n * \\ingroup mi2Cvt\n *\/\nint miget_real_value(mihandle_t volume,\n const misize_t coords[],\n int ndims,\n double *value_ptr);\n\n\/** This function sets the real value of a position in the MINC\n * volume. The \"real\" value is the value at the given location\n * after scaling has been applied.\n *\n * \\param volume A volume handle\n * \\param coords The voxel position to retrieve\n * \\param ndims The number of values in the \\a coords array\n * \\param value The value to save at this location.\n *\n * \\ingroup mi2Cvt\n *\/\nint miset_real_value(mihandle_t volume,\n const misize_t coords[],\n int ndims,\n double value);\n\n\n\/** This function retrieves the voxel values of a position in the\n * MINC volume. The voxel value is the unscaled value, and corresponds\n * to the value actually stored in the file.\n *\n * \\ingroup mi2Cvt\n *\/\nint miget_voxel_value(mihandle_t volume,\n const misize_t coords[],\n int ndims,\n double *voxel_ptr);\n\n\n\/** This function sets the voxel value of a position in the MINC\n * volume. The voxel value is the unscaled value, and corresponds to the\n * value actually stored in the file.\n *\n * \\ingroup mi2Cvt\n *\/\nint miset_voxel_value(mihandle_t volume,\n const misize_t coords[],\n int ndims,\n double voxel);\n\n\/** Get the absolute minimum and maximum values of a volume.\n *\n * \\ingroup mi2Cvt\n *\/\nint miget_volume_real_range(mihandle_t volume, double real_range[2]);\n\n\/**\n * This function sets the world coordinates of the point (0,0,0) in voxel\n * coordinates. This changes the constant offset of the two coordinate\n * systems.\n *\n * \\ingroup mi2Cvt\n *\/\nint miset_world_origin(mihandle_t volume, double origin[MI2_3D]);\n\n\/* VALID functions *\/\n\/** This function gets the maximum valid value specific to the data\n * type of the \\a volume parameter.\n * \\retval MI_ERROR on failure\n * \\retval MI_NOERROR on success\n *\/\nint miget_volume_valid_max(mihandle_t volume, double *valid_max);\n\n\/** This function sets the maximum valid value specific to the data\n * type of the \\a volume parameter.\n * \\retval MI_ERROR on failure\n * \\retval MI_NOERROR on success\n *\/\nint miset_volume_valid_max(mihandle_t volume, double valid_max);\n\n\/** This function gets the minimum valid value specific to the data\n * type of the \\a volume parameter.\n * \\retval MI_ERROR on failure\n * \\retval MI_NOERROR on success\n *\/\nint miget_volume_valid_min(mihandle_t volume, double *valid_min);\n\n\/** This function sets the minimum valid value specific to the data\n * type of the \\a volume parameter.\n * \\retval MI_ERROR on failure\n * \\retval MI_NOERROR on success\n *\/\nint miset_volume_valid_min(mihandle_t volume, double valid_min);\n\n\/** This function gets the minimum and maximum valid value specific to the\n * data type of the \\a volume parameter.\n * \\retval MI_ERROR on failure\n * \\retval MI_NOERROR on success\n *\/\nint miget_volume_valid_range(mihandle_t volume, double *valid_max, double *valid_min);\n\n\/** This function sets the minimum and maximum valid value specific to the\n * data type of the \\a volume parameter.\n * \\retval MI_ERROR on failure\n * \\retval MI_NOERROR on success\n *\/\nint miset_volume_valid_range(mihandle_t volume, double valid_max, double valid_min);\n\n\/** \\defgroup mi2Rec RECORD functions *\/\n\/** This method gets the name of the record dimension\n * TODO: set record name??\n * \\ingroup mi2Rec\n *\/\nint miget_record_name(mihandle_t volume, char **name);\n\n\/** This method gets the length (i.e., number of fields in the case of\n * uniform records and number of bytes for non_uniform ones) of the\n * record.\n * \\ingroup mi2Rec\n *\/\nint miget_record_length(mihandle_t volume, int *length);\n\n\/** This method returns the field name for the given field index. Memory\n * for returned string is allocated on the heap and should be released using\n * mifree_name().\n * \\ingroup mi2Rec\n *\/\nint miget_record_field_name(mihandle_t volume, int index, char **name);\n\n\/** This method sets a field name for the volume record. The volume\n * must be of class \"MI_CLASS_UNIFORM_RECORD\". The size of record\n * type will be increased if necessary to accomodate the new field.\n * \\ingroup mi2Rec\n *\/\nint miset_record_field_name(mihandle_t volume, int index,\n const char *name);\n\n\/** \\ingroup mi2Label LABEL functions *\/\n\n\/**\n * This function associates a label name with an integer value for the given\n * volume. Functions which read and write voxel values will read\/write\n * in integer values, and must call miget_label_name() to discover the\n * descriptive text string which corresponds to the integer value.\n * \\ingroup mi2Label\n *\/\nint midefine_label(mihandle_t volume, int value, const char *name);\n\n\/**\n * For a labelled volume, this function retrieves the text name\n * associated with a given integer value.\n *\n * The name pointer returned must be freed by calling mifree_name().\n * \\ingroup mi2Label\n*\/\nint miget_label_name(mihandle_t volume, int value, char **name);\n\n\/**\n * This function is the inverse of miget_label_name(). It is called to determine\n * what integer value, if any, corresponds to the given text string.\n * \\ingroup mi2Label\n*\/\nint miget_label_value(mihandle_t volume, const char *name, int *value);\n\n\n\/**\n * This function returns the number of defined labels, if any, or zero.\n * \\ingroup mi2Label\n*\/\nint miget_number_of_defined_labels(mihandle_t volume, int *number_of_labels);\n\n\/**\n * This function returns the label value associated with an index (0,1,...)\n * \\ingroup mi2Label\n*\/\nint miget_label_value_by_index(mihandle_t volume, int idx, int *value);\n\n#ifdef __cplusplus\n}\n#endif \/* __cplusplus defined *\/\n\n\n-}\n\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Data.Minc.Raw.Base where\n\nimport Data.Minc.Utils\nimport Data.Minc.Types\n\nimport Foreign hiding (unsafePerformIO)\nimport Foreign.C\nimport System.IO.Unsafe (unsafePerformIO)\nimport Control.Monad (liftM)\n\n#include \n\n-- VOLUME FUNCTIONS\n\n-- extern int micreate_volume(const char *filename, int number_of_dimensions,\n-- midimhandle_t dimensions[],\n-- mitype_t volume_type,\n-- miclass_t volume_class,\n-- mivolumeprops_t create_props,\n-- mihandle_t *volume);\n{#fun micreate_volume{ `String', `Int',\n allocaDims- `[Ptr ()]' peekDims*,\n toCInt `MincMiType',\n toCInt `MincMiClass',\n id `Ptr ()',\n alloca- `Ptr ()' peek* } -> `Int' #}\n\n-- extern int micreate_volume_image(mihandle_t volume);\n{#fun micreate_volume_image{ id `Ptr ()' } -> `Int' #}\n\n-- FIXME How do we make a mivolumeprops_t?\n\ntoCInt :: Enum a => a -> CInt\ntoCInt = toEnum . fromEnum\n\ntoCUInt :: Enum a => a -> CUInt\ntoCUInt = toEnum . fromEnum\n\ntoCULLong :: Enum a => a -> CULLong\ntoCULLong = toEnum . fromEnum\n\n-- toCULongLong :: Enum a => a -> CULongLong\n-- toCULongLong = toEnum . fromEnum\n\n-- extern int miget_volume_dimension_count(mihandle_t volume, midimclass_t dimclass, midimattr_t attr, int *number_of_dimensions);\n{#fun miget_volume_dimension_count{ id `Ptr ()', toCInt `MincDimClass', toCUInt `MincDimAttribute', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- extern int miget_volume_voxel_count(mihandle_t volume, int *number_of_voxels);\n{#fun miget_volume_voxel_count{ id `Ptr ()', alloca- `Int' peekIntConv* } -> `Int' #}\n\n-- extern int miopen_volume(const char *filename, int mode, mihandle_t *volume);\n{#fun miopen_volume{ `String', `Int', alloca- `Ptr ()' peek* } -> `Int' #}\n\n-- extern int miclose_volume(mihandle_t volume);\n{#fun miclose_volume{ id `Ptr ()' } -> `Int' #}\n\n-- extern int miget_slice_scaling_flag(mihandle_t volume, miboolean_t *slice_scaling_flag);\n-- FIXME Might be nicer to use a Bool marshalling thing instead of a CInt (miboolean_t is just int).\n{#fun miget_slice_scaling_flag{ id `Ptr ()', alloca- `CInt' peek* } -> `Int' #}\n\n{-\nextern int miset_slice_scaling_flag(mihandle_t volume,\n\t\t\t\t miboolean_t slice_scaling_flag);\n-}\n\n\n-- extern int miget_volume_dimensions(mihandle_t volume, midimclass_t dimclass, midimattr_t attr,\n-- miorder_t order, int array_length,\n-- midimhandle_t dimensions[]);\n{#fun miget_volume_dimensions{ id `Ptr ()', toCInt `MincDimClass', toCUInt `MincDimAttribute',\n toCInt `MincDimOrder', toCInt `Int', allocaDims- `[Ptr ()]' peekDims* } -> `Int' #}\n\n-- int miget_dimension_sizes(const midimhandle_t dimensions[], misize_t array_length,\n-- misize_t sizes[]);\n{#fun miget_dimension_sizes{ withArray* `[Ptr ()]', toCULLong `Int', allocaDimSizes- `[Int]' peekDimSizes* } -> `Int' #}\n\n\n-- int miget_dimension_separations(const midimhandle_t dimensions[],\n-- mivoxel_order_t voxel_order,\n-- misize_t array_length,\n-- double separations[]);\n{#fun miget_dimension_separations{ withArray* `[Ptr ()]', toCInt `MincVoxelOrder', toCULLong `Int',\n allocaSeparations- `[CDouble]' peekSeparations* } -> `Int' #}\n\n\n-- int miget_dimension_starts(const midimhandle_t dimensions[], mivoxel_order_t voxel_order,\n-- misize_t array_length, double starts[]);\n{#fun miget_dimension_starts{ withArray* `[Ptr ()]', toCInt `MincVoxelOrder', toCULLong `Int',\n allocaStarts- `[CDouble]' peekStarts* } -> `Int' #}\n\n-- int miget_dimension_name(midimhandle_t dimension, char **name_ptr);\n{#fun miget_dimension_name{ id `Ptr ()', alloca- `CString' peek*} -> `Int' #}\n\n-- withArrayInts :: Storable a => [a] -> (Ptr a -> IO b) -> IO b\nwithArrayInts x = withArray (map toCULLong x)\n\n-- int miget_real_value_hyperslab(mihandle_t volume,\n-- mitype_t buffer_data_type,\n-- const misize_t start[],\n-- const misize_t count[],\n-- void *buffer);\n{#fun miget_real_value_hyperslab{ id `Ptr ()',\n toCInt `MincType',\n withArrayInts* `[Int]',\n withArrayInts* `[Int]',\n id `Ptr ()' } -> `Int' #}\n\n-- int miget_data_type(mihandle_t vol, mitype_t *volume_data_type);\n{#fun miget_data_type{ id `Ptr ()', alloca- `MincType' peekMincType* } -> `Int' #}\n\n-- int miget_hyperslab_size(mitype_t volume_data_type,\n-- int n_dimensions,\n-- const hsize_t count[],\n-- misize_t *size_ptr);\n{#fun miget_hyperslab_size{ toCInt `MincType',\n toCInt `Int',\n withArrayInts* `[Int]',\n alloca- `CULLong' peekIntConv* } -> `Int' #}\n\n\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"dff86d494fbfef7b5fee6c1942f8689f3da4af83","subject":"Remove spurious ',' which upset haddock","message":"Remove spurious ',' which upset haddock\n\ndarcs-hash:20060128104532-b4c10-4fc9f6552a84dd7420d8adacd8488eb3c20cc8d3.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), 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":"f10f462d9eb3604bfeb2b96f08e801762939131d","subject":"Fix Andy's compilation problem.","message":"Fix Andy's compilation problem.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"3e89e5c86e416f72c9143f61f1038f658fbc1e5b","subject":"[project @ 2004-07-29 12:14:23 by duncan_coutts]","message":"[project @ 2004-07-29 12:14:23 by duncan_coutts]\n\nmake FileChooserError an instance of GErrorClass so users can catch exceptions\nnicely using the FileChooserError enum.\n\ndarcs-hash:20040729121423-d6ff7-9a23387184a4a4550fa63a6fbec62d2616137a2f.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/abstract\/FileChooser.chs","new_file":"gtk\/abstract\/FileChooser.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to GConf -*-haskell-*-\n-- for storing and retrieving configuartion information\n--\n-- Author : Duncan Coutts\n-- Created: 24 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n--\n-- The file chooser dialog and widget is a replacement\n-- for the old \"FileSel\"ection dialog. It provides a better user\n-- interface and an improved API.\n--\n-- The FileChooser (as opposed to the dialog or widget) is the interface that\n-- the \"FileChooserDialog\" and \"FileChooserWidget\" implement, all the operations\n-- except construction are on this interface.\n--\n-- * Added in GTK+ 2.4\n--\n\nmodule FileChooser (\n FileChooserClass,\n FileChooser,\n FileChooserAction(..),\n fileChooserSetAction,\n fileChooserGetAction,\n fileChooserSetLocalOnly,\n fileChooserGetLocalOnly,\n fileChooserSetSelectMultiple,\n fileChooserGetSelectMultiple,\n fileChooserSetCurrentName,\n fileChooserGetFilename,\n fileChooserSetFilename,\n fileChooserSelectFilename,\n fileChooserUnselectFilename,\n fileChooserSelectAll,\n fileChooserUnselectAll,\n fileChooserGetFilenames,\n fileChooserSetCurrentFolder,\n fileChooserGetCurrentFolder,\n fileChooserGetURI,\n fileChooserSetURI,\n fileChooserSelectURI,\n fileChooserUnselectURI,\n fileChooserGetURIs,\n fileChooserSetCurrentFolderURI,\n fileChooserGetCurrentFolderURI,\n fileChooserSetPreviewWidget,\n fileChooserGetPreviewWidget,\n fileChooserSetPreviewWidgetActive,\n fileChooserGetPreviewWidgetActive,\n fileChooserSetUsePreviewLabel,\n fileChooserGetUsePreviewLabel,\n fileChooserGetPreviewFilename,\n fileChooserGetPreviewURI,\n fileChooserSetExtraWidget,\n fileChooserGetExtraWidget,\n fileChooserAddFilter,\n fileChooserRemoveFilter,\n fileChooserListFilters,\n fileChooserSetFilter,\n fileChooserGetFilter,\n fileChooserAddShortcutFolder,\n fileChooserRemoveShortcutFolder,\n fileChooserlistShortcutFolders,\n fileChooserAddShortcutFolderURI,\n fileChooserRemoveShortcutFolderURI,\n fileChooserListShortcutFolderURIs,\n onCurrentFolderChanged,\n afterCurrentFolderChanged,\n onFileActivated,\n afterFileActivated,\n-- onSelectionChanged,\n-- afterSelectionChanged,\n onUpdatePreview,\n afterUpdatePreview\n) where\n\nimport Monad (liftM, when)\nimport FFI\n{#import Hierarchy#}\nimport Object\t\t(makeNewObject)\nimport Signal\n{#import GList#}\nimport GError (propagateGError, GErrorDomain, GErrorClass(..))\n\n{# context lib=\"gtk\" prefix =\"gtk\" #}\n\n{# enum FileChooserAction {underscoreToCase} #}\n{# enum FileChooserError {underscoreToCase} #}\n\nfileChooserErrorDomain :: GErrorDomain\nfileChooserErrorDomain = unsafePerformIO {#call unsafe file_chooser_error_quark#}\n \ninstance GErrorClass FileChooserError where\n gerrorDomain _ = fileChooserErrorDomain\n\nfileChooserSetAction :: FileChooserClass chooser => chooser -> FileChooserAction -> IO ()\nfileChooserSetAction chooser action =\n {# call gtk_file_chooser_set_action #} (toFileChooser chooser)\n (fromIntegral $ fromEnum action)\n\nfileChooserGetAction :: FileChooserClass chooser => chooser -> IO FileChooserAction\nfileChooserGetAction chooser = liftM (toEnum . fromIntegral) $\n {# call gtk_file_chooser_get_action #} (toFileChooser chooser)\n\nfileChooserSetLocalOnly :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetLocalOnly chooser localOnly = \n {# call gtk_file_chooser_set_local_only #} (toFileChooser chooser)\n (fromBool localOnly)\n\nfileChooserGetLocalOnly :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetLocalOnly chooser = liftM toBool $\n {# call gtk_file_chooser_get_local_only #} (toFileChooser chooser)\n\nfileChooserSetSelectMultiple :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetSelectMultiple chooser selectMultiple = \n {# call gtk_file_chooser_set_select_multiple #} (toFileChooser chooser)\n (fromBool selectMultiple)\n\nfileChooserGetSelectMultiple :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetSelectMultiple chooser = liftM toBool $\n {# call gtk_file_chooser_get_select_multiple #} (toFileChooser chooser)\n\nfileChooserSetCurrentName :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserSetCurrentName chooser name =\n withCString name $ \\strPtr ->\n {# call gtk_file_chooser_set_current_name #} (toFileChooser chooser) strPtr\n\nfileChooserGetFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_set_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_select_filename #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectFilename :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectFilename chooser filename = \n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_unselect_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserSelectAll chooser = \n {# call gtk_file_chooser_select_all #} (toFileChooser chooser)\n\nfileChooserUnselectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserUnselectAll chooser = \n {# call gtk_file_chooser_unselect_all #} (toFileChooser chooser)\n\nfileChooserGetFilenames :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetFilenames chooser = do\n strList <- {# call gtk_file_chooser_get_filenames #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolder :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolder chooser foldername = liftM toBool $\n withCString foldername $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolder :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetCurrentFolder chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_uri #} (toFileChooser chooser) strPtr\n\nfileChooserSelectURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_select_uri #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectURI chooser uri = \n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_unselect_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetURIs chooser = do\n strList <- {# call gtk_file_chooser_get_uris #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolderURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolderURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolderURI :: FileChooserClass chooser => chooser -> IO String\nfileChooserGetCurrentFolderURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder_uri #} (toFileChooser chooser)\n readCString strPtr\n\nfileChooserSetPreviewWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetPreviewWidget chooser widget = \n {# call gtk_file_chooser_set_preview_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetPreviewWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetPreviewWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_preview_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserSetPreviewWidgetActive :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetPreviewWidgetActive chooser active = \n {# call gtk_file_chooser_set_preview_widget_active #} (toFileChooser chooser)\n (fromBool active)\n\nfileChooserGetPreviewWidgetActive :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetPreviewWidgetActive chooser = liftM toBool $\n {# call gtk_file_chooser_get_preview_widget_active #} (toFileChooser chooser)\n\nfileChooserSetUsePreviewLabel :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetUsePreviewLabel chooser usePreview = \n {# call gtk_file_chooser_set_use_preview_label #} (toFileChooser chooser)\n (fromBool usePreview)\n\nfileChooserGetUsePreviewLabel :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetUsePreviewLabel chooser = liftM toBool $\n {# call gtk_file_chooser_get_use_preview_label #} (toFileChooser chooser)\n\nfileChooserGetPreviewFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetPreviewURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetExtraWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetExtraWidget chooser widget = \n {# call gtk_file_chooser_set_extra_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetExtraWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetExtraWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_extra_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserAddFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserAddFilter chooser filter = \n {# call gtk_file_chooser_add_filter #} (toFileChooser chooser) filter\n\nfileChooserRemoveFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserRemoveFilter chooser filter = \n {# call gtk_file_chooser_remove_filter #} (toFileChooser chooser) filter\n\nfileChooserListFilters :: FileChooserClass chooser => chooser -> IO [FileFilter]\nfileChooserListFilters chooser = do\n filterList <- {# call gtk_file_chooser_list_filters #} (toFileChooser chooser)\n filterPtrs <- fromGSList filterList\n mapM (makeNewObject mkFileFilter . return) filterPtrs\n\nfileChooserSetFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserSetFilter chooser filter = \n {# call gtk_file_chooser_set_filter #} (toFileChooser chooser) filter\n\nfileChooserGetFilter :: FileChooserClass chooser => chooser -> IO (Maybe FileFilter)\nfileChooserGetFilter chooser = do\n ptr <- {# call gtk_file_chooser_get_filter #} (toFileChooser chooser)\n maybePeek (makeNewObject mkFileFilter . return) ptr\n\nfileChooserAddShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserlistShortcutFolders :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserlistShortcutFolders chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folders #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserAddShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder_uri #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder_uri #}\n (toFileChooser chooser) strPtr gerrorPtr\n return ()\n\nfileChooserListShortcutFolderURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserListShortcutFolderURIs chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folder_uris #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nonCurrentFolderChanged, afterCurrentFolderChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" False\nafterCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" True\n\nonFileActivated, afterFileActivated :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonFileActivated = connect_NONE__NONE \"file-activated\" False\nafterFileActivated = connect_NONE__NONE \"file-activated\" True\n\n--onSelectionChanged, afterSelectionChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\n--onSelectionChanged = connect_NONE__NONE \"selection-changed\" False\n--afterSelectionChanged = connect_NONE__NONE \"selection-changed\" True\n\nonUpdatePreview, afterUpdatePreview :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonUpdatePreview = connect_NONE__NONE \"update-preview\" False\nafterUpdatePreview = connect_NONE__NONE \"update-preview\" True\n\n\n------------------------------------------------------\n-- Utility functions that really ought to go elsewhere\n\n-- like peekCString but then frees the string using g_free\nreadCString :: CString -> IO String\nreadCString strPtr = do\n str <- peekCString strPtr\n {# call unsafe g_free #} (castPtr strPtr)\n return str\n\n-- convenience functions for GSlists of strings\nfromStringGSList :: GSList -> IO [String]\nfromStringGSList strList = do\n strPtrs <- fromGSList strList\n mapM readCString strPtrs\n\ntoStringGSList :: [String] -> IO GSList\ntoStringGSList strs = do\n strPtrs <- mapM newCString strs\n toGSList strPtrs\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to GConf -*-haskell-*-\n-- for storing and retrieving configuartion information\n--\n-- Author : Duncan Coutts\n-- Created: 24 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n--\n-- The file chooser dialog and widget is a replacement\n-- for the old \"FileSel\"ection dialog. It provides a better user\n-- interface and an improved API.\n--\n-- The FileChooser (as opposed to the dialog or widget) is the interface that\n-- the \"FileChooserDialog\" and \"FileChooserWidget\" implement, all the operations\n-- except construction are on this interface.\n--\n-- * Added in GTK+ 2.4\n--\n\nmodule FileChooser (\n FileChooserClass,\n FileChooser,\n FileChooserAction(..),\n fileChooserSetAction,\n fileChooserGetAction,\n fileChooserSetLocalOnly,\n fileChooserGetLocalOnly,\n fileChooserSetSelectMultiple,\n fileChooserGetSelectMultiple,\n fileChooserSetCurrentName,\n fileChooserGetFilename,\n fileChooserSetFilename,\n fileChooserSelectFilename,\n fileChooserUnselectFilename,\n fileChooserSelectAll,\n fileChooserUnselectAll,\n fileChooserGetFilenames,\n fileChooserSetCurrentFolder,\n fileChooserGetCurrentFolder,\n fileChooserGetURI,\n fileChooserSetURI,\n fileChooserSelectURI,\n fileChooserUnselectURI,\n fileChooserGetURIs,\n fileChooserSetCurrentFolderURI,\n fileChooserGetCurrentFolderURI,\n fileChooserSetPreviewWidget,\n fileChooserGetPreviewWidget,\n fileChooserSetPreviewWidgetActive,\n fileChooserGetPreviewWidgetActive,\n fileChooserSetUsePreviewLabel,\n fileChooserGetUsePreviewLabel,\n fileChooserGetPreviewFilename,\n fileChooserGetPreviewURI,\n fileChooserSetExtraWidget,\n fileChooserGetExtraWidget,\n fileChooserAddFilter,\n fileChooserRemoveFilter,\n fileChooserListFilters,\n fileChooserSetFilter,\n fileChooserGetFilter,\n fileChooserAddShortcutFolder,\n fileChooserRemoveShortcutFolder,\n fileChooserlistShortcutFolders,\n fileChooserAddShortcutFolderURI,\n fileChooserRemoveShortcutFolderURI,\n fileChooserListShortcutFolderURIs,\n onCurrentFolderChanged,\n afterCurrentFolderChanged,\n onFileActivated,\n afterFileActivated,\n-- onSelectionChanged,\n-- afterSelectionChanged,\n onUpdatePreview,\n afterUpdatePreview\n) where\n\nimport Monad (liftM, when)\nimport FFI\n{#import Hierarchy#}\nimport Object\t\t(makeNewObject)\nimport Signal\n{#import GList#}\nimport GError (propagateGError)\n\n{# context lib=\"gtk\" prefix =\"gtk\" #}\n\n{# enum FileChooserAction {underscoreToCase} #}\n{# enum FileChooserError {underscoreToCase} #}\n\nfileChooserSetAction :: FileChooserClass chooser => chooser -> FileChooserAction -> IO ()\nfileChooserSetAction chooser action =\n {# call gtk_file_chooser_set_action #} (toFileChooser chooser)\n (fromIntegral $ fromEnum action)\n\nfileChooserGetAction :: FileChooserClass chooser => chooser -> IO FileChooserAction\nfileChooserGetAction chooser = liftM (toEnum . fromIntegral) $\n {# call gtk_file_chooser_get_action #} (toFileChooser chooser)\n\nfileChooserSetLocalOnly :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetLocalOnly chooser localOnly = \n {# call gtk_file_chooser_set_local_only #} (toFileChooser chooser)\n (fromBool localOnly)\n\nfileChooserGetLocalOnly :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetLocalOnly chooser = liftM toBool $\n {# call gtk_file_chooser_get_local_only #} (toFileChooser chooser)\n\nfileChooserSetSelectMultiple :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetSelectMultiple chooser selectMultiple = \n {# call gtk_file_chooser_set_select_multiple #} (toFileChooser chooser)\n (fromBool selectMultiple)\n\nfileChooserGetSelectMultiple :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetSelectMultiple chooser = liftM toBool $\n {# call gtk_file_chooser_get_select_multiple #} (toFileChooser chooser)\n\nfileChooserSetCurrentName :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserSetCurrentName chooser name =\n withCString name $ \\strPtr ->\n {# call gtk_file_chooser_set_current_name #} (toFileChooser chooser) strPtr\n\nfileChooserGetFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_set_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectFilename :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectFilename chooser filename = liftM toBool $\n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_select_filename #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectFilename :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectFilename chooser filename = \n withCString filename $ \\strPtr ->\n {# call gtk_file_chooser_unselect_filename #} (toFileChooser chooser) strPtr\n\nfileChooserSelectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserSelectAll chooser = \n {# call gtk_file_chooser_select_all #} (toFileChooser chooser)\n\nfileChooserUnselectAll :: FileChooserClass chooser => chooser -> IO ()\nfileChooserUnselectAll chooser = \n {# call gtk_file_chooser_unselect_all #} (toFileChooser chooser)\n\nfileChooserGetFilenames :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetFilenames chooser = do\n strList <- {# call gtk_file_chooser_get_filenames #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolder :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolder chooser foldername = liftM toBool $\n withCString foldername $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolder :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetCurrentFolder chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_uri #} (toFileChooser chooser) strPtr\n\nfileChooserSelectURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSelectURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_select_uri #} (toFileChooser chooser) strPtr\n\nfileChooserUnselectURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserUnselectURI chooser uri = \n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_unselect_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserGetURIs chooser = do\n strList <- {# call gtk_file_chooser_get_uris #} (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserSetCurrentFolderURI :: FileChooserClass chooser => chooser -> String -> IO Bool\nfileChooserSetCurrentFolderURI chooser uri = liftM toBool $\n withCString uri $ \\strPtr ->\n {# call gtk_file_chooser_set_current_folder_uri #} (toFileChooser chooser) strPtr\n\nfileChooserGetCurrentFolderURI :: FileChooserClass chooser => chooser -> IO String\nfileChooserGetCurrentFolderURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_current_folder_uri #} (toFileChooser chooser)\n readCString strPtr\n\nfileChooserSetPreviewWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetPreviewWidget chooser widget = \n {# call gtk_file_chooser_set_preview_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetPreviewWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetPreviewWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_preview_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserSetPreviewWidgetActive :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetPreviewWidgetActive chooser active = \n {# call gtk_file_chooser_set_preview_widget_active #} (toFileChooser chooser)\n (fromBool active)\n\nfileChooserGetPreviewWidgetActive :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetPreviewWidgetActive chooser = liftM toBool $\n {# call gtk_file_chooser_get_preview_widget_active #} (toFileChooser chooser)\n\nfileChooserSetUsePreviewLabel :: FileChooserClass chooser => chooser -> Bool -> IO ()\nfileChooserSetUsePreviewLabel chooser usePreview = \n {# call gtk_file_chooser_set_use_preview_label #} (toFileChooser chooser)\n (fromBool usePreview)\n\nfileChooserGetUsePreviewLabel :: FileChooserClass chooser => chooser -> IO Bool\nfileChooserGetUsePreviewLabel chooser = liftM toBool $\n {# call gtk_file_chooser_get_use_preview_label #} (toFileChooser chooser)\n\nfileChooserGetPreviewFilename :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewFilename chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_filename #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserGetPreviewURI :: FileChooserClass chooser => chooser -> IO (Maybe String)\nfileChooserGetPreviewURI chooser = do\n strPtr <- {# call gtk_file_chooser_get_preview_uri #} (toFileChooser chooser)\n maybePeek readCString strPtr\n\nfileChooserSetExtraWidget :: (FileChooserClass chooser, WidgetClass widget) =>\n chooser -> widget -> IO ()\nfileChooserSetExtraWidget chooser widget = \n {# call gtk_file_chooser_set_extra_widget #} (toFileChooser chooser)\n (toWidget widget)\n\nfileChooserGetExtraWidget :: FileChooserClass chooser => chooser -> IO (Maybe Widget)\nfileChooserGetExtraWidget chooser = do\n ptr <- {# call gtk_file_chooser_get_extra_widget #} (toFileChooser chooser)\n maybePeek (makeNewObject mkWidget . return) ptr\n\nfileChooserAddFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserAddFilter chooser filter = \n {# call gtk_file_chooser_add_filter #} (toFileChooser chooser) filter\n\nfileChooserRemoveFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserRemoveFilter chooser filter = \n {# call gtk_file_chooser_remove_filter #} (toFileChooser chooser) filter\n\nfileChooserListFilters :: FileChooserClass chooser => chooser -> IO [FileFilter]\nfileChooserListFilters chooser = do\n filterList <- {# call gtk_file_chooser_list_filters #} (toFileChooser chooser)\n filterPtrs <- fromGSList filterList\n mapM (makeNewObject mkFileFilter . return) filterPtrs\n\nfileChooserSetFilter :: FileChooserClass chooser => chooser -> FileFilter -> IO ()\nfileChooserSetFilter chooser filter = \n {# call gtk_file_chooser_set_filter #} (toFileChooser chooser) filter\n\nfileChooserGetFilter :: FileChooserClass chooser => chooser -> IO (Maybe FileFilter)\nfileChooserGetFilter chooser = do\n ptr <- {# call gtk_file_chooser_get_filter #} (toFileChooser chooser)\n maybePeek (makeNewObject mkFileFilter . return) ptr\n\nfileChooserAddShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolder :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolder chooser foldername =\n propagateGError $ \\gerrorPtr ->\n withCString foldername $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserlistShortcutFolders :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserlistShortcutFolders chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folders #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nfileChooserAddShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserAddShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_add_shortcut_folder_uri #} (toFileChooser chooser)\n strPtr gerrorPtr\n return ()\n\nfileChooserRemoveShortcutFolderURI :: FileChooserClass chooser => chooser -> String -> IO ()\nfileChooserRemoveShortcutFolderURI chooser folderuri =\n propagateGError $ \\gerrorPtr ->\n withCString folderuri $ \\strPtr -> do\n {# call gtk_file_chooser_remove_shortcut_folder_uri #}\n (toFileChooser chooser) strPtr gerrorPtr\n return ()\n\nfileChooserListShortcutFolderURIs :: FileChooserClass chooser => chooser -> IO [String]\nfileChooserListShortcutFolderURIs chooser = do\n strList <- {# call gtk_file_chooser_list_shortcut_folder_uris #}\n (toFileChooser chooser)\n fromStringGSList strList\n\nonCurrentFolderChanged, afterCurrentFolderChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" False\nafterCurrentFolderChanged = connect_NONE__NONE \"current-folder-changed\" True\n\nonFileActivated, afterFileActivated :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonFileActivated = connect_NONE__NONE \"file-activated\" False\nafterFileActivated = connect_NONE__NONE \"file-activated\" True\n\n--onSelectionChanged, afterSelectionChanged :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\n--onSelectionChanged = connect_NONE__NONE \"selection-changed\" False\n--afterSelectionChanged = connect_NONE__NONE \"selection-changed\" True\n\nonUpdatePreview, afterUpdatePreview :: FileChooserClass c => c -> IO () -> IO (ConnectId c)\nonUpdatePreview = connect_NONE__NONE \"update-preview\" False\nafterUpdatePreview = connect_NONE__NONE \"update-preview\" True\n\n\n------------------------------------------------------\n-- Utility functions that really ought to go elsewhere\n\n-- like peekCString but then frees the string using g_free\nreadCString :: CString -> IO String\nreadCString strPtr = do\n str <- peekCString strPtr\n {# call unsafe g_free #} (castPtr strPtr)\n return str\n\n-- convenience functions for GSlists of strings\nfromStringGSList :: GSList -> IO [String]\nfromStringGSList strList = do\n strPtrs <- fromGSList strList\n mapM readCString strPtrs\n\ntoStringGSList :: [String] -> IO GSList\ntoStringGSList strs = do\n strPtrs <- mapM newCString strs\n toGSList strPtrs\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7cd2d33d709d8ab68d7980254c7588121bd7be02","subject":"[project @ 2002-06-13 23:03:12 by as49]","message":"[project @ 2002-06-13 23:03:12 by as49]\n\nReversing the argument order flipped some arguments which weren't supposed to\nmove. Jens Petersen pointed that out.\n\ndarcs-hash:20020613230312-d90cf-2236c01a5ae30920a5795baf97cc6365fe4594f4.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"5002e109a32713b85aca4df740919e802c5b3375","subject":"Add the tree view notification functions. These are needed by any custom TreeModel implementation that allows changes in the model. They are to tell any watcing views of changes in the model so the views can update themselves appropriately.","message":"Add the tree view notification functions.\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","repos":"vincenthz\/webkit","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":"1474653cee79da96fd91deb02cdaa8a333ca01dd","subject":"Error handling for image loading","message":"Error handling for image loading\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, 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\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\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","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 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0044ee762ef17404a8ff4aeb697e067456772b67","subject":"Support CL_PLATFORM_NOT_FOUND_KHR error.","message":"Support CL_PLATFORM_NOT_FOUND_KHR error.\n\nKhronos .icd extension may report error when no platform is\nfound. This patch essentially provides a friendly error message like:\n*** Exception: CL_PLATFORM_NOT_FOUND_KHR\n\nPreviously it was just an error code:\n*** Exception: CLError.toEnum: Cannot match -1001\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Types.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Types.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 DeriveDataTypeable #-}\nmodule Control.Parallel.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLMemObjectType_, CLMemInfo_, CLImageInfo_, CLMapFlags_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..), CLMapFlag(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLMapFlags_ = {#type cl_map_flags#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_PLATFORM_NOT_FOUND_KHR=CL_PLATFORM_NOT_FOUND_KHR,\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_PLATFORM_NOT_FOUND_khr', Returned when no .icd (platform drivers)\n can be properly loaded.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMapFlag {\n cL_MAP_READ=CL_MAP_READ,\n cL_MAP_WRITE=CL_MAP_WRITE\n };\n#endc\n{#enum CLMapFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes =\n\tbitmaskToFlags \n\t\t[CL_DEVICE_TYPE_CPU\n\t\t,CL_DEVICE_TYPE_GPU\n\t\t,CL_DEVICE_TYPE_ACCELERATOR\n\t\t,CL_DEVICE_TYPE_DEFAULT\n\t\t,CL_DEVICE_TYPE_ALL\n\t\t]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\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 DeriveDataTypeable #-}\nmodule Control.Parallel.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLMemObjectType_, CLMemInfo_, CLImageInfo_, CLMapFlags_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..), CLMapFlag(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLMapFlags_ = {#type cl_map_flags#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMapFlag {\n cL_MAP_READ=CL_MAP_READ,\n cL_MAP_WRITE=CL_MAP_WRITE\n };\n#endc\n{#enum CLMapFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes =\n\tbitmaskToFlags \n\t\t[CL_DEVICE_TYPE_CPU\n\t\t,CL_DEVICE_TYPE_GPU\n\t\t,CL_DEVICE_TYPE_ACCELERATOR\n\t\t,CL_DEVICE_TYPE_DEFAULT\n\t\t,CL_DEVICE_TYPE_ALL\n\t\t]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"fcf1fcdb1f971492bdeb2f6262afd26ab89b35cd","subject":"part 5: memory allocation","message":"part 5: memory allocation\n\nIgnore-this: 5718e1e645334583608043b54096137a\n\ndarcs-hash:20091219121234-dcabc-eac9fc2f5d6a4378c498641b4e058a1670f0c55e.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Marshal\/Alloc.chs","new_file":"Foreign\/CUDA\/Runtime\/Marshal\/Alloc.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Marshal.Alloc\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory allocation for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Marshal.Alloc\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 -- ** Copying\n --\n -- Basic copying between the host and device\n --\n memcpy,\n CopyDirection(..)\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable (Storable)\nimport qualified Foreign.Storable as F\nimport qualified Foreign.Marshal as F\n\nimport Foreign.CUDA.Runtime.DevicePtr\nimport Foreign.CUDA.Runtime.Error\n-- import Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\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 (DevicePtr a)\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> newDevicePtr (castPtr ptr)\n _ -> resultIfOk (rv,undefined)\n\n{# fun unsafe cudaMalloc\n { alloca'- `Ptr ()' peek'*\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C-> Haskell doesn't like qualified imports in marshaller specifications\n 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 (DevicePtr a, Int64)\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> (p,pitch)) `fmap` newDevicePtr (castPtr ptr)\n _ -> resultIfOk (rv,undefined)\n\n{# fun unsafe cudaMallocPitch\n { alloca'- `Ptr ()' peek'*\n , alloca'- `Int64' peekIntConv*\n , cIntConv `Int64'\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\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 (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 ()\nfree = finalizeDevicePtr\n\n--free :: DevicePtr a -> IO (Maybe String)\n--free p = nothingIfOk `fmap` (withDevicePtr p cudaFree)\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 ()\nmemset ptr bytes symbol =\n nothingIfOk =<< cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevPtrCast* `DevicePtr a'\n , `Int'\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n withDevPtrCast = withDevicePtr . castDevicePtr\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 ()\nmemset2D ptr (width,height) pitch symbol =\n nothingIfOk =<< cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevPtrCast* `DevicePtr a'\n , cIntConv `Int64'\n , `Int'\n , cIntConv `Int64'\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n withDevPtrCast = withDevicePtr . castDevicePtr\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 ()\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 (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 action =\n allocaBytes bytes $ \\dptr ->\n memset dptr bytes symbol >>\n action dptr\n\n\n--------------------------------------------------------------------------------\n-- Copying\n--------------------------------------------------------------------------------\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\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 ()\nmemcpy dst src bytes dir =\n nothingIfOk =<< 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-- |\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-- Auxiliary utilities\n--------------------------------------------------------------------------------\n\n--\n-- Errors\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.Runtime.Marshal.Alloc\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory allocation for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Marshal.Alloc\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 -- ** Copying\n --\n -- Basic copying between the host and device\n --\n memcpy,\n CopyDirection(..)\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable (Storable)\nimport qualified Foreign.Storable as F\nimport qualified Foreign.Marshal as F\n\nimport Foreign.CUDA.Runtime.DevicePtr\nimport Foreign.CUDA.Runtime.Error\n-- import Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\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 ()\nfree = finalizeDevicePtr\n\n--free :: DevicePtr a -> IO (Maybe String)\n--free p = nothingIfOk `fmap` (withDevicePtr p cudaFree)\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 { withDevPtrCast* `DevicePtr a' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where\n withDevPtrCast = withDevicePtr . castDevicePtr\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 { withDevPtrCast* `DevicePtr a' ,\n cIntConv `Int64' ,\n `Int' ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where\n withDevPtrCast = withDevicePtr . castDevicePtr\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 (moduleForceEither `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-- Copying\n--------------------------------------------------------------------------------\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\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-- |\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-- Auxiliary utilities\n--------------------------------------------------------------------------------\n\n--\n-- Errors\n--\nmoduleErr :: String -> String -> a\nmoduleErr fun msg = error (\"Foreign.CUDA.\" ++ fun ++ ':':' ':msg)\n\nmoduleForceEither :: Either String a -> a\nmoduleForceEither (Left s) = moduleErr \"Marshal\" s\nmoduleForceEither (Right r) = r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7e3fced964f75ae718a410d9141c31d5fa07cbf2","subject":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO","message":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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 ) 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\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\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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"3c87e2b1749965675cdf7076a31ba3b7fde73d18","subject":"All of commit.h","message":"All of 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.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\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\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\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-------------------------------------------------------------------------------\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.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\nnewtype Tree = Tree 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\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\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\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\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":"d3098bd1ab6e3aa88eccd792688b2d9fa7772e41","subject":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members","message":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult(..),\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult,\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0c22c9e691906b404b800d0418e2a6fd27876d05","subject":"Fixed binding error in CV.Transforms.distanceTransform","message":"Fixed binding error in CV.Transforms.distanceTransform\n","repos":"BeautifulDestinations\/CV,aleator\/CV,aleator\/CV,TomMD\/CV","old_file":"CV\/Transforms.chs","new_file":"CV\/Transforms.chs","new_contents":"{-#LANGUAGE CPP, 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 as I \nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\nimport qualified CV.Matrix as M\nimport CV.Matrix (Matrix,withMatPtr)\nimport Control.DeepSeq\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 cl <- I.create (getSize 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 target <- I.create (getSize 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 <- I.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 <- I.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\nperspectiveTransform' :: (CreateImage (Image c d)) => Matrix Float -> Image c d -> (Int,Int)-> Image c d\nperspectiveTransform' mat img size\n = unsafePerformIO $ do\n r <- create size\n withImage img $ \\c_img ->\n withMatPtr mat $ \\c_mat ->\n withImage r $ \\c_r -> {#call wrapWarpPerspective#} (castPtr c_img) (castPtr c_r) (castPtr c_mat)\n return r\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#c\nenum HomographyMethod {\n Default = 0,\n Ransac = CV_RANSAC,\n LMeds = CV_LMEDS\n };\n#endc\n{#enum HomographyMethod {}#}\n\ngetHomography' :: Matrix Float -> Matrix Float -> HomographyMethod -> Float -> Matrix Float\ngetHomography' srcPts dstPts method ransacThreshold = \n unsafePerformIO $ do\n hmg <- M.create (3,3) :: IO (Matrix Float)\n withMatPtr srcPts $\u00a0\\c_src ->\n withMatPtr dstPts $\u00a0\\c_dst ->\n withMatPtr hmg $\u00a0\\c_hmg -> do\n {#call cvFindHomography#} \n (castPtr c_src) \n (castPtr c_dst) \n (castPtr c_hmg)\n (fromIntegral $ fromEnum method)\n (realToFrac ransacThreshold)\n nullPtr\n return hmg\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 <- I.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 <- I.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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- I.create (w2,h2)\n blit i img (0,0)\n let (Mutable im) = i\n im `deepseq` return im\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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n CCOMP = CV_DIST_LABEL_CCOMP\n ,PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\n\n-- |Mask sizes accepted by distanceTransform\n#c\nenum MaskSize {\n M3 = 3\n ,M5 = 5\n ,MPrecise = CV_DIST_MASK_PRECISE\n};\n#endc\n{#enum MaskSize {}#}\n\n\n-- |Mask sizes accepted by distanceTransform\n-- data MaskSize = M3 |\u00a0M5\u00a0| MPrecise deriving (Eq,Ord,Enum,Show)\n\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 <- I.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#ifdef OpenCV24\n (fromIntegral . fromEnum $ CCOMP)\n#endif\n return result\n\n -- TODO: Add handling for labels\n -- TODO: Add handling for custom masks\n","old_contents":"{-#LANGUAGE CPP, 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 as I \nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\nimport qualified CV.Matrix as M\nimport CV.Matrix (Matrix,withMatPtr)\nimport Control.DeepSeq\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 cl <- I.create (getSize 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 target <- I.create (getSize 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 <- I.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 <- I.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\nperspectiveTransform' :: (CreateImage (Image c d)) => Matrix Float -> Image c d -> (Int,Int)-> Image c d\nperspectiveTransform' mat img size\n = unsafePerformIO $ do\n r <- create size\n withImage img $ \\c_img ->\n withMatPtr mat $ \\c_mat ->\n withImage r $ \\c_r -> {#call wrapWarpPerspective#} (castPtr c_img) (castPtr c_r) (castPtr c_mat)\n return r\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#c\nenum HomographyMethod {\n Default = 0,\n Ransac = CV_RANSAC,\n LMeds = CV_LMEDS\n };\n#endc\n{#enum HomographyMethod {}#}\n\ngetHomography' :: Matrix Float -> Matrix Float -> HomographyMethod -> Float -> Matrix Float\ngetHomography' srcPts dstPts method ransacThreshold = \n unsafePerformIO $ do\n hmg <- M.create (3,3) :: IO (Matrix Float)\n withMatPtr srcPts $\u00a0\\c_src ->\n withMatPtr dstPts $\u00a0\\c_dst ->\n withMatPtr hmg $\u00a0\\c_hmg -> do\n {#call cvFindHomography#} \n (castPtr c_src) \n (castPtr c_dst) \n (castPtr c_hmg)\n (fromIntegral $ fromEnum method)\n (realToFrac ransacThreshold)\n nullPtr\n return hmg\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 <- I.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 <- I.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-- | Enlargen the image so that its size is a power of two.\nminEnlarge :: Image GrayScale D32 -> Image GrayScale D32\nminEnlarge i = enlargeShadow (min (ceiling (logBase 2 (f w))) (ceiling (logBase 2 (f h)))) i\n where \n f = fromIntegral\n (w,h) = getSize i\n\n-- | Calculate an infinite gaussian pyramid of an image while keeping track of\n-- various corner cases and gotchas.\ngaussianPyramid :: Image GrayScale D32 -> [Image GrayScale D32]\ngaussianPyramid = iterate pyrDown' . minEnlarge\n where \n pyrDown' i = let (w,h) = getSize i\n in if (w`div`2) <=1 ||\u00a0(h`div`2) <= 1 then i else pyrDown i\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-- |Enlargen the image so that its size is divisible by 2^n. Fill the area\n-- outside the image with black.\nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- I.create (w2,h2)\n blit i img (0,0)\n let (Mutable im) = i\n im `deepseq` return im\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-- |\u00a0Enlargen the image so that its size is is divisible by 2^n. Replicate\n-- the border of the image.\nenlargeShadow :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlargeShadow n img = unsafePerformIO $ do\n i <- create (w2,h2)\n withImage img $\u00a0\\c_img -> \n withImage i $ \\c_i -> {#call blitShadow#} c_i c_img \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#ifdef OpenCV24\n#c\nenum LabelType {\n CCOMP = CV_DIST_LABEL_CCOMP\n ,PIXEL = CV_DIST_LABEL_PIXEL\n};\n#endc\n{#enum LabelType {}#}\n#endif\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 <- I.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#ifdef OpenCV24\n (fromIntegral . fromEnum $ CCOMP)\n#endif\n return result\n\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":"5fca453a424ca7b4a0d4cb116af835bb7f1ce390","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\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , Envelope (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n , OGR\n , OGRConduit\n , OGRSource\n , OGRSink\n , runOGR\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n\n , createLayer\n , createLayerWithDef\n\n , getLayer\n , getLayerByName\n\n , sourceLayer\n , sourceLayer_\n , conduitInsertLayer\n , conduitInsertLayer_\n , sinkInsertLayer\n , sinkInsertLayer_\n , sinkUpdateLayer\n\n , executeSQL\n\n , syncLayerToDisk\n , syncToDisk\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerExtent\n , layerFeatureDef\n\n , createFeature\n , createFeatureWithFid\n , createFeature_\n , getFeature\n , updateFeature\n , deleteFeature\n\n , registerAll\n , cleanupAll\n\n , liftOGR\n , closeLayer\n , unDataSource\n , unLayer\n , layerHasCapability\n , driverHasCapability\n , dataSourceHasCapability\n , nullLayerH\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Conduit\nimport qualified Data.Conduit.List as CL\nimport Data.Maybe (isNothing, fromMaybe)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative (Applicative, (<$>), (<*>), pure)\nimport Control.Monad (liftM, when, void, (>=>), (<=<))\nimport Control.Monad.Base (MonadBase)\nimport Control.Monad.Catch (\n MonadThrow(..)\n , MonadCatch\n , MonadMask\n , bracket\n , finally\n )\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Resource (MonadResource, ReleaseKey)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..))\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\n#endif\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable, peek)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) =\n DataSource { unDataSource :: DataSourceH }\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nnewtype OGR s l a = OGR (GDAL s a)\n\nderiving instance Functor (OGR s l)\nderiving instance Applicative (OGR s l)\nderiving instance Monad (OGR s l)\nderiving instance MonadIO (OGR s l)\nderiving instance MonadThrow (OGR s l)\nderiving instance MonadCatch (OGR s l)\nderiving instance MonadMask (OGR s l)\nderiving instance MonadBase IO (OGR s l)\nderiving instance MonadResource (OGR s l)\n\nrunOGR :: (forall l. OGR s l a )-> GDAL s a\nrunOGR (OGR a) = a\n\nliftOGR :: GDAL s a -> OGR s l a\nliftOGR = OGR\n\ntype OGRConduit s l i o = Conduit i (OGR s l) o\ntype OGRSource s l o = Source (OGR s l) o\ntype OGRSink s l i = Sink i (OGR s l)\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s l (t::AccessMode) a) = Layer (ReleaseKey, LayerH)\n\nunLayer :: Layer s l t a -> LayerH\nunLayer (Layer (_,l)) = l\n\ncloseLayer :: MonadIO m => Layer s l t a -> m ()\ncloseLayer (Layer (rk,_)) = release rk\n\ntype ROLayer s l = Layer s l ReadOnly\ntype RWLayer s l = Layer s l ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p =\n newDataSourceHandle $ withCString p $ \\p' ->\n checkGDALCall checkIt ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGROpen\"\n\n\nnewDataSourceHandle\n :: IO DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle act = liftM snd $ allocate alloc free\n where\n alloc = liftM DataSource act\n free ds\n | dsPtr \/= nullDataSourceH = {#call OGR_DS_Destroy as ^#} dsPtr\n | otherwise = return ()\n where dsPtr = unDataSource ds\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n checkGDALCall checkIt\n (withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGR_Dr_CreateDataSource\"\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: forall s l a. OGRFeatureDef a\n => RWDataSource s -> ApproxOK -> OptionList -> GDAL s (RWLayer s l a)\ncreateLayer ds = createLayerWithDef ds (featureDef (Proxy :: Proxy a))\n\n\n\ncreateLayerWithDef\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s l a)\ncreateLayerWithDef ds FeatureDef{..} approxOk options =\n liftM Layer $\n flip allocate (const (return ())) $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList options $ \\pOpts -> do\n pL <- checkGDALCall checkIt $\n {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts\n V.forM_ fdFields $ \\(n,f) -> withFieldDefnH n f $ \\pFld ->\n checkOGRError $ {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if SUPPORTS_MULTI_GEOM_FIELDS\n V.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 = unDataSource 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\ngetLayerSchema :: LayerH -> IO FeatureDefnH\ngetLayerSchema = {#call OGR_L_GetLayerDefn as ^#}\n\ncreateFeatureWithFidIO\n :: OGRFeature a => LayerH -> Maybe Fid -> a -> IO (Maybe Fid)\ncreateFeatureWithFidIO pL fid feat = do\n pFd <- getLayerSchema pL\n featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError ({#call OGR_L_CreateFeature as ^#} pL pF)\n getFid pF\n\ncreateFeatureWithFid\n :: OGRFeature a => RWLayer s l a -> Maybe Fid -> a -> GDAL s (Maybe Fid)\ncreateFeatureWithFid layer fid =\n liftIO . createFeatureWithFidIO (unLayer layer) fid\n\ncreateFeature :: OGRFeature a => RWLayer s l a -> a -> GDAL s Fid\ncreateFeature layer =\n createFeatureWithFid layer Nothing >=>\n maybe (throwBindingException UnexpectedNullFid) return\n\ncreateFeature_ :: OGRFeature a => RWLayer s l a -> a -> GDAL s ()\ncreateFeature_ layer = void . createFeatureWithFid layer Nothing\n\nupdateFeature :: OGRFeature a => RWLayer s l a -> Fid -> a -> GDAL s ()\nupdateFeature layer fid feat = liftIO $ do\n pFd <- getLayerSchema pL\n featureToHandle pFd (Just fid) feat $\n checkOGRError . {#call OGR_L_SetFeature as ^#} pL\n where pL = unLayer layer\n\ngetFeature :: OGRFeature a => Layer s l t a -> Fid -> GDAL s (Maybe a)\ngetFeature layer (Fid fid) = liftIO $ do\n when (not (pL `layerHasCapability` RandomRead)) $\n throwBindingException (UnsupportedLayerCapability RandomRead)\n fDef <- layerFeatureDefIO pL\n liftM (fmap snd) $ featureFromHandle fDef $\n {#call OGR_L_GetFeature as ^#} pL (fromIntegral fid)\n where pL = unLayer layer\n\ndeleteFeature :: Layer s l t a -> Fid -> GDAL s ()\ndeleteFeature layer (Fid fid) = liftIO $\n checkOGRError $\n {#call OGR_L_DeleteFeature as ^#} (unLayer layer) (fromIntegral fid)\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if SUPPORTS_MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\nsyncToDisk :: RWDataSource s -> GDAL s ()\nsyncToDisk =\n liftIO . checkOGRError . {#call OGR_DS_SyncToDisk as ^#} . unDataSource\n\nsyncLayerToDiskIO :: RWLayer s l a -> IO ()\nsyncLayerToDiskIO = checkOGRError . {#call OGR_L_SyncToDisk as ^#} . unLayer\n\nsyncLayerToDisk :: RWLayer s l a -> GDAL s ()\nsyncLayerToDisk = liftIO . syncLayerToDiskIO\n\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayer ix ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n {#call OGR_DS_GetLayer as ^#} (unDataSource 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\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayerByName name ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n useAsEncodedCString name $\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerName name)\n\n\nsourceLayer\n :: OGRFeature a\n => GDAL s (Layer s l t a)\n -> OGRSource s l (Maybe Fid, a)\nsourceLayer alloc = layerTransaction alloc' loop\n where\n alloc' = do\n l <- alloc\n liftIO $ {#call OGR_L_ResetReading as ^#} (unLayer l)\n fDef <- layerFeatureDef l\n return (l, fDef)\n\n loop seed = do\n next <- liftIO $\n featureFromHandle (snd seed) $\n {#call OGR_L_GetNextFeature as ^#} (unLayer (fst seed))\n case next of\n Just v -> yield v >> loop seed\n Nothing -> return ()\n\nsourceLayer_\n :: OGRFeature a => GDAL s (Layer s l t a) -> OGRSource s l a\nsourceLayer_ = (=$= (CL.map snd)) . sourceLayer\n\n\nconduitInsertLayer\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l (Maybe Fid, a) (Maybe Fid)\nconduitInsertLayer = flip conduitFromLayer createIt\n where\n createIt (l, pFd) = awaitForever $ \\(fid, feat) -> do\n fid' <- liftIO $ featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError ({#call OGR_L_CreateFeature as ^#} (unLayer l) pF)\n getFid pF\n yield fid'\n\nconduitInsertLayer_\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l a (Maybe Fid)\nconduitInsertLayer_ = (CL.map (\\i->(Nothing,i)) =$=) . conduitInsertLayer\n\nsinkInsertLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Maybe Fid, a) ()\nsinkInsertLayer = (=$= CL.sinkNull) . conduitInsertLayer\n\nsinkInsertLayer_\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l a ()\nsinkInsertLayer_ =\n ((=$= CL.sinkNull) . ((CL.map (\\i->(Nothing,i))) =$=)) . conduitInsertLayer\n\nsinkUpdateLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Fid, a) ()\nsinkUpdateLayer = flip conduitFromLayer updateIt\n where\n updateIt (l, pFd) = awaitForever $ \\(fid, feat) ->\n liftIO $ featureToHandle pFd (Just fid) feat $\n checkOGRError . {#call OGR_L_SetFeature as ^#} (unLayer l)\n\n\nlayerTransaction\n :: GDAL s (Layer s l t a, e)\n -> ((Layer s l t a, e) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nlayerTransaction alloc inside = do\n alloc' <- lift (liftOGR (unsafeGDALToIO alloc))\n (rbKey, seed) <- allocate alloc' rollback\n liftIO $ checkOGRError $\n {#call OGR_L_StartTransaction as ^#} (unLayer (fst seed))\n addCleanup (const (release rbKey))\n (inside seed >> liftIO (commit rbKey seed))\n where\n free = closeLayer . fst\n commit rbKey seed = bracket (unprotect rbKey) (const (free seed)) $ \\m -> do\n when (isNothing m) (error \"layerTransaction: this should not happen\")\n checkOGRError ({#call OGR_L_CommitTransaction as ^#} (unLayer (fst seed)))\n checkOGRError ({#call OGR_L_SyncToDisk as ^#} (unLayer (fst seed)))\n\n rollback seed =\n checkOGRError ({#call OGR_L_RollbackTransaction as ^#} (unLayer (fst seed)))\n `finally` free seed\n\n\n\nconduitFromLayer\n :: GDAL s (RWLayer s l a)\n -> ((RWLayer s l a, FeatureDefnH) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nconduitFromLayer alloc = layerTransaction alloc'\n where\n alloc' = do\n l <- alloc\n schema <- liftIO $ getLayerSchema (unLayer l)\n return (l, schema)\n\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it to the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> maybeNewSpatialRefBorrowedHandle\n ({#call unsafe OGR_L_GetSpatialRef as ^#} p)\n <*> pure True\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = unsafeUseAsCString \"SQLITE\"\nwithSQLDialect OGRDialect = unsafeUseAsCString \"OGRSQL\"\n\nexecuteSQL\n :: OGRFeature a\n => SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s l a)\nexecuteSQL dialect query mSpatialFilter ds =\n liftM Layer $ allocate execute freeIfNotNull\n where\n execute =\n checkGDALCall checkit $\n withMaybeGeometry mSpatialFilter $ \\pF ->\n useAsEncodedCString query $ \\pQ ->\n withSQLDialect dialect $ {#call OGR_DS_ExecuteSQL as ^#} pDs pQ pF\n\n freeIfNotNull pL\n | pL \/= nullLayerH = {#call unsafe OGR_DS_ReleaseResultSet as ^#} pDs pL\n | otherwise = return ()\n\n pDs = unDataSource 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\nlayerName :: Layer s l t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerExtent :: Layer s l t a -> GDAL s Envelope\nlayerExtent l = liftIO $ alloca $ \\pE -> do\n checkOGRError ({#call OGR_L_GetExtent as ^#} (unLayer l) pE 1)\n peek pE\n\nlayerFeatureDef :: Layer s l t a -> GDAL s FeatureDef\nlayerFeatureDef = liftIO . layerFeatureDefIO . unLayer\n\nlayerFeatureDefIO :: LayerH -> IO FeatureDef\nlayerFeatureDefIO pL = do\n gfd <- layerGeomFieldDef pL\n getLayerSchema pL >>= featureDefFromHandle gfd\n\n\ngetSpatialFilter :: Layer s l t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $\n {#call unsafe OGR_L_GetSpatialFilter as ^#} (unLayer l) >>= maybeCloneGeometry\n\nsetSpatialFilter :: Layer s l t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withGeometry g $ {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , Envelope (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n , OGR\n , OGRConduit\n , OGRSource\n , OGRSink\n , runOGR\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , datasourceName\n\n , createLayer\n , createLayerWithDef\n\n , getLayer\n , getLayerByName\n\n , sourceLayer\n , sourceLayer_\n , conduitInsertLayer\n , conduitInsertLayer_\n , sinkInsertLayer\n , sinkInsertLayer_\n , sinkUpdateLayer\n\n , executeSQL\n\n , syncLayerToDisk\n , syncToDisk\n\n , getSpatialFilter\n , setSpatialFilter\n\n , layerCount\n , layerName\n , layerExtent\n , layerFeatureDef\n\n , createFeature\n , createFeatureWithFid\n , createFeature_\n , getFeature\n , updateFeature\n , deleteFeature\n\n , registerAll\n , cleanupAll\n\n , liftOGR\n , closeLayer\n , unDataSource\n , unLayer\n , layerHasCapability\n , driverHasCapability\n , dataSourceHasCapability\n , nullLayerH\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Conduit\nimport qualified Data.Conduit.List as CL\nimport Data.Maybe (isNothing, fromMaybe)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Text (Text)\nimport qualified Data.Vector as V\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, when, void, (>=>), (<=<))\nimport Control.Monad.Base (MonadBase)\nimport Control.Monad.Catch (\n MonadThrow(..)\n , MonadCatch\n , MonadMask\n , bracket\n , finally\n )\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Resource (MonadResource, ReleaseKey)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..))\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\n#endif\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool)\n\nimport Foreign.Storable (Storable, peek)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH newtype#}\nderiving instance Eq DriverH\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) =\n DataSource { unDataSource :: DataSourceH }\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nnewtype OGR s l a = OGR (GDAL s a)\n\nderiving instance Functor (OGR s l)\nderiving instance Applicative (OGR s l)\nderiving instance Monad (OGR s l)\nderiving instance MonadIO (OGR s l)\nderiving instance MonadThrow (OGR s l)\nderiving instance MonadCatch (OGR s l)\nderiving instance MonadMask (OGR s l)\nderiving instance MonadBase IO (OGR s l)\nderiving instance MonadResource (OGR s l)\n\nrunOGR :: (forall l. OGR s l a )-> GDAL s a\nrunOGR (OGR a) = a\n\nliftOGR :: GDAL s a -> OGR s l a\nliftOGR = OGR\n\ntype OGRConduit s l i o = Conduit i (OGR s l) o\ntype OGRSource s l o = Source (OGR s l) o\ntype OGRSink s l i = Sink i (OGR s l)\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s l (t::AccessMode) a) = Layer (ReleaseKey, LayerH)\n\nunLayer :: Layer s l t a -> LayerH\nunLayer (Layer (_,l)) = l\n\ncloseLayer :: MonadIO m => Layer s l t a -> m ()\ncloseLayer (Layer (rk,_)) = release rk\n\ntype ROLayer s l = Layer s l ReadOnly\ntype RWLayer s l = Layer s l ReadWrite\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p =\n newDataSourceHandle $ withCString p $ \\p' ->\n checkGDALCall checkIt ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGROpen\"\n\n\nnewDataSourceHandle\n :: IO DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle act = liftM snd $ allocate alloc free\n where\n alloc = liftM DataSource act\n free ds\n | dsPtr \/= nullDataSourceH = {#call OGR_DS_Destroy as ^#} dsPtr\n | otherwise = return ()\n where dsPtr = unDataSource ds\n\ntype Driver = String\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n checkGDALCall checkIt\n (withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGR_Dr_CreateDataSource\"\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: String -> IO DriverH\ndriverByName name = withCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullDriverH\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: forall s l a. OGRFeatureDef a\n => RWDataSource s -> ApproxOK -> OptionList -> GDAL s (RWLayer s l a)\ncreateLayer ds = createLayerWithDef ds (featureDef (Proxy :: Proxy a))\n\n\n\ncreateLayerWithDef\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s l a)\ncreateLayerWithDef ds FeatureDef{..} approxOk options =\n liftM Layer $\n flip allocate (const (return ())) $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList options $ \\pOpts -> do\n pL <- checkGDALCall checkIt $\n {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts\n V.forM_ fdFields $ \\(n,f) -> withFieldDefnH n f $ \\pFld ->\n checkOGRError $ {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if SUPPORTS_MULTI_GEOM_FIELDS\n V.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 = unDataSource 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\ngetLayerSchema :: LayerH -> IO FeatureDefnH\ngetLayerSchema = {#call OGR_L_GetLayerDefn as ^#}\n\ncreateFeatureWithFidIO\n :: OGRFeature a => LayerH -> Maybe Fid -> a -> IO (Maybe Fid)\ncreateFeatureWithFidIO pL fid feat = do\n pFd <- getLayerSchema pL\n featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError ({#call OGR_L_CreateFeature as ^#} pL pF)\n getFid pF\n\ncreateFeatureWithFid\n :: OGRFeature a => RWLayer s l a -> Maybe Fid -> a -> GDAL s (Maybe Fid)\ncreateFeatureWithFid layer fid =\n liftIO . createFeatureWithFidIO (unLayer layer) fid\n\ncreateFeature :: OGRFeature a => RWLayer s l a -> a -> GDAL s Fid\ncreateFeature layer =\n createFeatureWithFid layer Nothing >=>\n maybe (throwBindingException UnexpectedNullFid) return\n\ncreateFeature_ :: OGRFeature a => RWLayer s l a -> a -> GDAL s ()\ncreateFeature_ layer = void . createFeatureWithFid layer Nothing\n\nupdateFeature :: OGRFeature a => RWLayer s l a -> Fid -> a -> GDAL s ()\nupdateFeature layer fid feat = liftIO $ do\n pFd <- getLayerSchema pL\n featureToHandle pFd (Just fid) feat $\n checkOGRError . {#call OGR_L_SetFeature as ^#} pL\n where pL = unLayer layer\n\ngetFeature :: OGRFeature a => Layer s l t a -> Fid -> GDAL s (Maybe a)\ngetFeature layer (Fid fid) = liftIO $ do\n when (not (pL `layerHasCapability` RandomRead)) $\n throwBindingException (UnsupportedLayerCapability RandomRead)\n fDef <- layerFeatureDefIO pL\n liftM (fmap snd) $ featureFromHandle fDef $\n {#call OGR_L_GetFeature as ^#} pL (fromIntegral fid)\n where pL = unLayer layer\n\ndeleteFeature :: Layer s l t a -> Fid -> GDAL s ()\ndeleteFeature layer (Fid fid) = liftIO $\n checkOGRError $\n {#call OGR_L_DeleteFeature as ^#} (unLayer layer) (fromIntegral fid)\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if SUPPORTS_MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\nsyncToDisk :: RWDataSource s -> GDAL s ()\nsyncToDisk =\n liftIO . checkOGRError . {#call OGR_DS_SyncToDisk as ^#} . unDataSource\n\nsyncLayerToDiskIO :: RWLayer s l a -> IO ()\nsyncLayerToDiskIO = checkOGRError . {#call OGR_L_SyncToDisk as ^#} . unLayer\n\nsyncLayerToDisk :: RWLayer s l a -> GDAL s ()\nsyncLayerToDisk = liftIO . syncLayerToDiskIO\n\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayer ix ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n {#call OGR_DS_GetLayer as ^#} (unDataSource 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\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayerByName name ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n useAsEncodedCString name $\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerName name)\n\n\nsourceLayer\n :: OGRFeature a\n => GDAL s (Layer s l t a)\n -> OGRSource s l (Maybe Fid, a)\nsourceLayer alloc = layerTransaction alloc' loop\n where\n alloc' = do\n l <- alloc\n liftIO $ {#call OGR_L_ResetReading as ^#} (unLayer l)\n fDef <- layerFeatureDef l\n return (l, fDef)\n\n loop seed = do\n next <- liftIO $\n featureFromHandle (snd seed) $\n {#call OGR_L_GetNextFeature as ^#} (unLayer (fst seed))\n case next of\n Just v -> yield v >> loop seed\n Nothing -> return ()\n\nsourceLayer_\n :: OGRFeature a => GDAL s (Layer s l t a) -> OGRSource s l a\nsourceLayer_ = (=$= (CL.map snd)) . sourceLayer\n\n\nconduitInsertLayer\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l (Maybe Fid, a) (Maybe Fid)\nconduitInsertLayer = flip conduitFromLayer createIt\n where\n createIt (l, pFd) = awaitForever $ \\(fid, feat) -> do\n fid' <- liftIO $ featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError ({#call OGR_L_CreateFeature as ^#} (unLayer l) pF)\n getFid pF\n yield fid'\n\nconduitInsertLayer_\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l a (Maybe Fid)\nconduitInsertLayer_ = (CL.map (\\i->(Nothing,i)) =$=) . conduitInsertLayer\n\nsinkInsertLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Maybe Fid, a) ()\nsinkInsertLayer = (=$= CL.sinkNull) . conduitInsertLayer\n\nsinkInsertLayer_\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l a ()\nsinkInsertLayer_ =\n ((=$= CL.sinkNull) . ((CL.map (\\i->(Nothing,i))) =$=)) . conduitInsertLayer\n\nsinkUpdateLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Fid, a) ()\nsinkUpdateLayer = flip conduitFromLayer updateIt\n where\n updateIt (l, pFd) = awaitForever $ \\(fid, feat) ->\n liftIO $ featureToHandle pFd (Just fid) feat $\n checkOGRError . {#call OGR_L_SetFeature as ^#} (unLayer l)\n\n\nlayerTransaction\n :: GDAL s (Layer s l t a, e)\n -> ((Layer s l t a, e) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nlayerTransaction alloc inside = do\n alloc' <- lift (liftOGR (unsafeGDALToIO alloc))\n (rbKey, seed) <- allocate alloc' rollback\n liftIO $ checkOGRError $\n {#call OGR_L_StartTransaction as ^#} (unLayer (fst seed))\n addCleanup (const (release rbKey))\n (inside seed >> liftIO (commit rbKey seed))\n where\n free = closeLayer . fst\n commit rbKey seed = bracket (unprotect rbKey) (const (free seed)) $ \\m -> do\n when (isNothing m) (error \"layerTransaction: this should not happen\")\n checkOGRError ({#call OGR_L_CommitTransaction as ^#} (unLayer (fst seed)))\n checkOGRError ({#call OGR_L_SyncToDisk as ^#} (unLayer (fst seed)))\n\n rollback seed =\n checkOGRError ({#call OGR_L_RollbackTransaction as ^#} (unLayer (fst seed)))\n `finally` free seed\n\n\n\nconduitFromLayer\n :: GDAL s (RWLayer s l a)\n -> ((RWLayer s l a, FeatureDefnH) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nconduitFromLayer alloc = layerTransaction alloc'\n where\n alloc' = do\n l <- alloc\n schema <- liftIO $ getLayerSchema (unLayer l)\n return (l, schema)\n\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it to the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> maybeNewSpatialRefBorrowedHandle\n ({#call unsafe OGR_L_GetSpatialRef as ^#} p)\n <*> pure True\n\nlayerCount :: DataSource s t -> GDAL s Int\nlayerCount = liftM fromIntegral\n . liftIO . {#call OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndatasourceName :: DataSource s t -> GDAL s String\ndatasourceName =\n liftIO . (peekCString <=< {#call unsafe OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = unsafeUseAsCString \"SQLITE\"\nwithSQLDialect OGRDialect = unsafeUseAsCString \"OGRSQL\"\n\nexecuteSQL\n :: OGRFeature a\n => SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s l a)\nexecuteSQL dialect query mSpatialFilter ds =\n liftM Layer $ allocate execute freeIfNotNull\n where\n execute =\n checkGDALCall checkit $\n withMaybeGeometry mSpatialFilter $ \\pF ->\n useAsEncodedCString query $ \\pQ ->\n withSQLDialect dialect $ {#call OGR_DS_ExecuteSQL as ^#} pDs pQ pF\n\n freeIfNotNull pL\n | pL \/= nullLayerH = {#call unsafe OGR_DS_ReleaseResultSet as ^#} pDs pL\n | otherwise = return ()\n\n pDs = unDataSource 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\nlayerName :: Layer s l t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerExtent :: Layer s l t a -> GDAL s Envelope\nlayerExtent l = liftIO $ alloca $ \\pE -> do\n checkOGRError ({#call OGR_L_GetExtent as ^#} (unLayer l) pE 1)\n peek pE\n\nlayerFeatureDef :: Layer s l t a -> GDAL s FeatureDef\nlayerFeatureDef = liftIO . layerFeatureDefIO . unLayer\n\nlayerFeatureDefIO :: LayerH -> IO FeatureDef\nlayerFeatureDefIO pL = do\n gfd <- layerGeomFieldDef pL\n getLayerSchema pL >>= featureDefFromHandle gfd\n\n\ngetSpatialFilter :: Layer s l t a -> GDAL s (Maybe Geometry)\ngetSpatialFilter l = liftIO $\n {#call unsafe OGR_L_GetSpatialFilter as ^#} (unLayer l) >>= maybeCloneGeometry\n\nsetSpatialFilter :: Layer s l t a -> Geometry -> GDAL s ()\nsetSpatialFilter l g = liftIO $\n withGeometry g $ {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3531f1cab48cc454e3529d5d88afa61cb05159d4","subject":"explicitly convert between Haskell<->C types, instead of casting pointers","message":"explicitly convert between Haskell<->C types, instead of casting pointers\n\nIgnore-this: 34c6069346640a68090d3039c57ef56e\n- seems that the tesla box didn't like cheating\n\ndarcs-hash:20100110013743-dcabc-93a7db308701bb8a7164cee63cccbae30e7eaf3f.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda","old_file":"examples\/src\/smvm\/SMVM.chs","new_file":"examples\/src\/smvm\/SMVM.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n--\n-- Module : SMVM\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Sparse-matrix dense-vector multiplication\n--\n--------------------------------------------------------------------------------\n\nmodule Main where\n\n#include \"smvm.h\"\n\n-- Friends\nimport Time\nimport C2HS\nimport RandomVector (randomList,randomListR,verifyList)\n\n-- System\nimport Numeric\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\nimport System.Random\nimport Foreign.CUDA (withDevicePtr)\nimport qualified Foreign.CUDA as CUDA\n\n--\n-- A very simple sparse-matrix \/ vector representation\n-- (confusingly, different from that in RandomVector and used elsewhere)\n--\ntype Vector e = [e]\ntype SparseVector e = [(Int,e)]\ntype SparseMatrix e = [SparseVector e]\n\n--------------------------------------------------------------------------------\n-- Reference\n--------------------------------------------------------------------------------\n\nsmvm :: (Num e, Storable e) => SparseMatrix e -> Vector e -> Vector e\nsmvm sm v = [ sum [ x * (v!!col) | (col,x) <- sv ] | sv <- sm ]\n\n--------------------------------------------------------------------------------\n-- CUDA\n--------------------------------------------------------------------------------\n\n--\n-- Sparse-matrix vector multiplication, using compressed-sparse row format.\n--\n-- Lots of boilerplate to copy data to the device. Our simple list\n-- representation has atrocious copy performance (see the `bandwidthTest'\n-- example), so don't include that in the benchmarking\n--\nsmvm_csr :: SparseMatrix Float -> Vector Float -> IO (Vector Float)\nsmvm_csr sm v =\n let matData = concatMap (map cFloatConv . snd . unzip) sm\n colIdx = concatMap (map cIntConv . fst . unzip) sm\n rowPtr = scanl (+) 0 (map (cIntConv . length) sm)\n v' = map cFloatConv v\n#ifdef __DEVICE_EMULATION__\n iters = 1\n#else\n iters = 100\n#endif\n in\n CUDA.withListArray matData $ \\d_data ->\n CUDA.withListArray rowPtr $ \\d_ptr ->\n CUDA.withListArray colIdx $ \\d_indices ->\n CUDA.withListArrayLen v' $ \\num_rows d_x ->\n CUDA.allocaArray num_rows $ \\d_y -> do\n (t,_) <- benchmark iters (smvm_csr_f d_y d_x d_data d_ptr d_indices num_rows) CUDA.sync\n putStrLn $ \"Elapsed time: \" ++ shows (fromInteger (timeIn millisecond t)\/100::Float) \" ms\"\n map cFloatConv <$> CUDA.peekListArray num_rows d_y\n\n{# fun unsafe smvm_csr_f\n { withDevicePtr* `CUDA.DevicePtr CFloat'\n , withDevicePtr* `CUDA.DevicePtr CFloat'\n , withDevicePtr* `CUDA.DevicePtr CFloat'\n , withDevicePtr* `CUDA.DevicePtr CUInt'\n , withDevicePtr* `CUDA.DevicePtr CUInt'\n , `Int' } -> `()' #}\n\n--------------------------------------------------------------------------------\n-- Main\n--------------------------------------------------------------------------------\n\nrandomSM :: (Num e, Random e, Storable e) => (Int,Int) -> IO (SparseMatrix e)\nrandomSM (h,w) = replicateM h sparseVec\n where\n sparseVec = do\n nz <- randomRIO (0,w`div`50) -- number of non-zero elements (max 2% occupancy)\n idx <- nub . sort <$> randomListR nz (0,w-1) -- remove duplicate column indices\n zip idx <$> randomList (length idx) -- (column indices don't actually need to be sorted)\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 putStrLn $ \" Compute capability: \" ++ show (CUDA.computeCapability props)\n putStrLn $ \" Total global memory: \" ++\n showFFloat (Just 2) (fromIntegral (CUDA.totalGlobalMem props) \/ (1024*1024) :: Double) \" GB\\n\"\n\n let k = 2048 -- size of the matrix\/vector\n vec <- randomList k\n mat <- randomSM (k,k)\n putStrLn $ \"Sparse-matrix size: \" ++ show k ++ \" x \" ++ show k\n putStrLn $ \"Non-zero elements: \" ++ show (sum (map length mat))\n\n let ref = smvm mat vec\n cuda <- smvm_csr mat vec\n\n putStrLn $ \"Validating: \" ++ if verifyList ref cuda then \"Ok!\" else \"INVALID!\"\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n--\n-- Module : SMVM\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Sparse-matrix dense-vector multiplication\n--\n--------------------------------------------------------------------------------\n\nmodule Main where\n\n#include \"smvm.h\"\n\n-- Friends\nimport Time\nimport C2HS\nimport RandomVector (randomList,randomListR,verifyList)\n\n-- System\nimport Numeric\nimport Data.List\nimport Control.Monad\nimport Control.Applicative\nimport System.Random\nimport qualified Foreign.CUDA as CUDA\n\n--\n-- A very simple sparse-matrix \/ vector representation\n-- (confusingly, different from that in RandomVector and used elsewhere)\n--\ntype Vector e = [e]\ntype SparseVector e = [(Int,e)]\ntype SparseMatrix e = [SparseVector e]\n\n--------------------------------------------------------------------------------\n-- Reference\n--------------------------------------------------------------------------------\n\nsmvm :: (Num e, Storable e) => SparseMatrix e -> Vector e -> Vector e\nsmvm sm v = [ sum [ x * (v!!col) | (col,x) <- sv ] | sv <- sm ]\n\n--------------------------------------------------------------------------------\n-- CUDA\n--------------------------------------------------------------------------------\n\n--\n-- Sparse-matrix vector multiplication, using compressed-sparse row format.\n--\n-- Lots of boilerplate to copy data to the device. Our simple list\n-- representation has atrocious copy performance (see the `bandwidthTest'\n-- example), so don't include that in the benchmarking\n--\nsmvm_csr :: SparseMatrix Float -> Vector Float -> IO (Vector Float)\nsmvm_csr sm v =\n let matData = concatMap (snd . unzip) sm\n colIdx = concatMap (fst . unzip) sm\n rowPtr = scanl (+) 0 (map length sm)\n iters = 100\n in\n CUDA.withListArray matData $ \\d_data ->\n CUDA.withListArray rowPtr $ \\d_ptr ->\n CUDA.withListArray colIdx $ \\d_indices ->\n CUDA.withListArrayLen v $ \\num_rows d_x ->\n CUDA.allocaArray num_rows $ \\d_y -> do\n (t,_) <- benchmark iters (smvm_csr_f d_y d_x d_data d_ptr d_indices num_rows) CUDA.sync\n putStrLn $ \"Elapsed time: \" ++ shows (fromInteger (timeIn millisecond t)\/100::Float) \" ms\"\n CUDA.peekListArray num_rows d_y\n\n{# fun unsafe smvm_csr_f\n { withDP* `CUDA.DevicePtr Float'\n , withDP* `CUDA.DevicePtr Float'\n , withDP* `CUDA.DevicePtr Float'\n , withDP* `CUDA.DevicePtr Int'\n , withDP* `CUDA.DevicePtr Int'\n , `Int' } -> `()' #}\n where\n withDP dp a = CUDA.withDevicePtr dp $ \\p -> a (castPtr p)\n\n--------------------------------------------------------------------------------\n-- Main\n--------------------------------------------------------------------------------\n\nrandomSM :: (Num e, Random e, Storable e) => (Int,Int) -> IO (SparseMatrix e)\nrandomSM (h,w) = replicateM h sparseVec\n where\n sparseVec = do\n nz <- randomRIO (0,w`div`50) -- number of non-zero elements (max 2% occupancy)\n idx <- nub . sort <$> randomListR nz (0,w-1) -- remove duplicate column indices\n zip idx <$> randomList (length idx) -- (column indices don't actually need to be sorted)\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 putStrLn $ \" Compute capability: \" ++ show (CUDA.computeCapability props)\n putStrLn $ \" Total global memory: \" ++\n showFFloat (Just 2) (fromIntegral (CUDA.totalGlobalMem props) \/ (1024*1024) :: Double) \" GB\\n\"\n\n let k = 2048 -- size of the matrix\/vector\n vec <- randomList k\n mat <- randomSM (k,k)\n putStrLn $ \"Sparse-matrix size: \" ++ show k ++ \" x \" ++ show k\n putStrLn $ \"Non-zero elements: \" ++ show (sum (map length mat))\n\n let ref = smvm mat vec\n cuda <- smvm_csr mat vec\n\n putStrLn $ \"Validating: \" ++ if verifyList ref cuda then \"Ok!\" else \"INVALID!\"\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e82034cbecd68868075192b996f8bb0ca2b75776","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\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer","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":"368768a1dea356a14e176e25fc9bb24053fcc517","subject":"GetPixel for mutable images","message":"GetPixel for mutable images\n","repos":"aleator\/CV,BeautifulDestinations\/CV,aleator\/CV,TomMD\/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, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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":"bf9e79b2e485977c00ebd29ec608c47e72814948","subject":"Fix bug in initialMetadata.","message":"Fix bug in initialMetadata.\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 (readIORef . initialMDRef)\n case status of\n Just md -> return md\n Nothing ->\n branchOnStatus\n (joinClientRWOp clientWaitForInitialMetadata)\n (joinClientRWOp clientWaitForInitialMetadata)\n (\\code msg -> lift (throwE (StatusError code msg)))\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\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","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"} {"commit":"e5df71088877b86e6feb2234870a399be7993502","subject":"TODOs","message":"TODOs\n","repos":"mwotton\/Hubris-Haskell,mwotton\/Hubris-Haskell,mwotton\/Hubris-Haskell","old_file":"lib\/RubyMap.chs","new_file":"lib\/RubyMap.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n-- {-# LANGUAGE TypeSynonymInstances #-}\n\n{- TODO\n\nRip the array trnaslation stuff out to a utility function. same with hashes.\n\ninstall as package. This is a bit iffy for GHC\/JHC compatibility - if we commit to\nCabal, that leaves JHC out in the cold.\n\nperhaps need cabal file for ghc and equivalent for jhc.\n\n-}\n\n\nmodule RubyMap where\n#include \"rshim.h\"\n#include \n\n-- import Control.Applicative\n-- import Control.Monad\nimport Data.Word\n-- import Foreign.Ptr\nimport Foreign.C.Types\t\nimport Foreign.C.String\n-- import Foreign.Storable\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- import Foreign.Marshal.Array\n\n{# context lib=\"rshim\" #}\n\n{# enum RubyType {} deriving (Eq, Show) #} -- maybe Ord?\n#if RUBY_VERSION_CODE <= 187\ndata RubyConsts = RUBY_Qfalse \n | RUBY_Qtrue \n | RUBY_Qnil \n | RUBY_Qundef \n\ninstance Enum RubyConsts where\n fromEnum RUBY_Qfalse = 0\n fromEnum RUBY_Qtrue = 2\n fromEnum RUBY_Qnil = 4\n fromEnum RUBY_Qundef = 6\n\n toEnum 0 = RUBY_Qfalse\n toEnum 2 = RUBY_Qtrue\n toEnum 4 = RUBY_Qnil\n toEnum 6 = RUBY_Qundef\n#else\n{# enum ruby_special_consts as RubyConsts {} deriving (Eq,Show) #}\n#endif\ntype Value = CULong -- FIXME, we'd prefer to import the type VALUE directly\nforeign import ccall unsafe \"ruby.h rb_str2cstr\" rb_str2cstr :: Value -> CInt -> CString\nforeign import ccall unsafe \"ruby.h rb_str_new2\" rb_str_new2 :: CString -> Value\nforeign import ccall unsafe \"ruby.h rb_ary_new2\" rb_ary_new2 :: CLong -> IO Value\nforeign import ccall unsafe \"ruby.h rb_ary_push\" rb_ary_push :: Value -> Value -> IO ()\nforeign import ccall unsafe \"ruby.h rb_float_new\" rb_float_new :: Double -> Value\nforeign import ccall unsafe \"ruby.h rb_big2str\" rb_big2str :: Value -> Int -> Value\nforeign import ccall unsafe \"ruby.h rb_str_to_inum\" rb_str_to_inum :: Value -> Int -> Int -> Value\n\n-- we're being a bit filthy here - the interface is all macros, so we're digging in to find what it actually is\nforeign import ccall unsafe \"rshim.h rb_ary_len\" rb_ary_len :: Value -> CUInt\nforeign import ccall unsafe \"rshim.h rtype\" rtype :: Value -> Int\nforeign import ccall unsafe \"rshim.h int2fix\" int2fix :: Int -> Value\nforeign import ccall unsafe \"rshim.h fix2int\" fix2int :: Value -> Int\nforeign import ccall unsafe \"rshim.h num2dbl\" num2dbl :: Value -> Double -- technically CDoubles, but jhc promises they're the same\n\n-- this line crashes jhc\nforeign import ccall unsafe \"intern.h rb_ary_entry\" rb_ary_entry :: Value -> CLong -> IO Value\n\nforeign import ccall safe \"ruby.h rb_raise\" rb_raise :: Value -> CString -> IO ()\nforeign import ccall unsafe \"ruby.h rb_eval_string\" rb_eval_string :: CString -> Value\n\n\n\n\ndata RValue = T_NIL \n | T_FLOAT Double\n | T_STRING String\n\n -- List is non-ideal. Switch to uvector? Array? There's always going\n -- to be an extraction step to pull the RValues out.\n | T_ARRAY [RValue]\n | T_FIXNUM Int \n | T_HASH Int -- definitely FIXME - native ruby hashes, or going to transliterate into Data.Map?\n | T_BIGNUM Integer \n\n -- technically, these are mapping over the types True and False,\n -- I'm going to treat them as values, though.\n | T_TRUE \n | T_FALSE \n\n | T_SYMBOL Word -- interned string\n\n-- These are the other basic Ruby structures that we're not handling yet.\n-- | T_REGEXP \n-- | T_FILE\n-- | T_STRUCT \n-- | T_DATA \n-- | T_OBJECT \n-- | T_CLASS \n-- | T_MODULE \n\ntoRuby :: RValue -> Value\ntoRuby r = case r of\n T_FLOAT d -> rb_float_new d\n -- need to take the address of the cstr, just cast it to a value\n -- sadly no bytestrings yet - unpack it to a list. yeah it's ugly.\n T_STRING str -> rb_str_new2 $ unsafePerformIO $ newCAString str\n T_FIXNUM i -> int2fix i\n\n -- so this is just bizarre - there's no boolean type. True and False have their own types\n -- as well as their own values.\n T_TRUE -> fromIntegral $ fromEnum RUBY_Qtrue\n T_FALSE -> fromIntegral $ fromEnum RUBY_Qfalse\n T_NIL -> fromIntegral $ fromEnum RUBY_Qnil\n T_ARRAY l -> unsafePerformIO $ do\n ary <- rb_ary_new2 $ fromIntegral $ length l\n mapM_ (rb_ary_push ary . toRuby) l\n return ary\n T_BIGNUM b -> rb_str_to_inum (rb_str_new2 $ unsafePerformIO $ newCAString $ show b) 10 1\n _ -> error \"sorry, haven't implemented that yet.\"\n\nfromRuby :: Value -> RValue\nfromRuby v = case target of\n RT_NIL -> T_NIL\n RT_FIXNUM -> T_FIXNUM $ fix2int v\n RT_STRING -> T_STRING $ unsafePerformIO $ peekCString $ rb_str2cstr v 0\n RT_FLOAT -> T_FLOAT $ num2dbl v\n RT_BIGNUM -> T_BIGNUM $ read $ unsafePerformIO $ peekCString $ rb_str2cstr (rb_big2str v 10) 0\n RT_TRUE -> T_TRUE\n RT_FALSE -> T_FALSE\n RT_ARRAY -> T_ARRAY $ map fromRuby $ unsafePerformIO $ mapM (rb_ary_entry v . fromIntegral) [0..(rb_ary_len v) - 1]\n\n _ -> error (show target)\n where target :: RubyType\n target = toEnum $ rtype v\n\n-- utility stuff\n\nthrowException :: String -> IO Value\nthrowException s = do he <- newCAString \"HaskellError\"\n err <- newCAString s\n rb_raise (rb_eval_string he) err\n error \"shouldn't ever get here\"","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n-- {-# LANGUAGE TypeSynonymInstances #-}\n\nmodule RubyMap where\n#include \"rshim.h\"\n#include \n\n-- import Control.Applicative\n-- import Control.Monad\nimport Data.Word\n-- import Foreign.Ptr\nimport Foreign.C.Types\t\nimport Foreign.C.String\n-- import Foreign.Storable\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- import Foreign.Marshal.Array\n\n{# context lib=\"rshim\" #}\n\n{# enum RubyType {} deriving (Eq, Show) #} -- maybe Ord?\n#if RUBY_VERSION_CODE <= 187\ndata RubyConsts = RUBY_Qfalse \n | RUBY_Qtrue \n | RUBY_Qnil \n | RUBY_Qundef \n\ninstance Enum RubyConsts where\n fromEnum RUBY_Qfalse = 0\n fromEnum RUBY_Qtrue = 2\n fromEnum RUBY_Qnil = 4\n fromEnum RUBY_Qundef = 6\n\n toEnum 0 = RUBY_Qfalse\n toEnum 2 = RUBY_Qtrue\n toEnum 4 = RUBY_Qnil\n toEnum 6 = RUBY_Qundef\n#else\n{# enum ruby_special_consts as RubyConsts {} deriving (Eq,Show) #}\n#endif\ntype Value = CULong -- FIXME, we'd prefer to import the type VALUE directly\nforeign import ccall unsafe \"ruby.h rb_str2cstr\" rb_str2cstr :: Value -> CInt -> CString\nforeign import ccall unsafe \"ruby.h rb_str_new2\" rb_str_new2 :: CString -> Value\nforeign import ccall unsafe \"ruby.h rb_ary_new2\" rb_ary_new2 :: CLong -> IO Value\nforeign import ccall unsafe \"ruby.h rb_ary_push\" rb_ary_push :: Value -> Value -> IO ()\nforeign import ccall unsafe \"ruby.h rb_float_new\" rb_float_new :: Double -> Value\nforeign import ccall unsafe \"ruby.h rb_big2str\" rb_big2str :: Value -> Int -> Value\nforeign import ccall unsafe \"ruby.h rb_str_to_inum\" rb_str_to_inum :: Value -> Int -> Int -> Value\n\n-- we're being a bit filthy here - the interface is all macros, so we're digging in to find what it actually is\nforeign import ccall unsafe \"rshim.h rb_ary_len\" rb_ary_len :: Value -> CUInt\nforeign import ccall unsafe \"rshim.h rtype\" rtype :: Value -> Int\nforeign import ccall unsafe \"rshim.h int2fix\" int2fix :: Int -> Value\nforeign import ccall unsafe \"rshim.h fix2int\" fix2int :: Value -> Int\nforeign import ccall unsafe \"rshim.h num2dbl\" num2dbl :: Value -> Double -- technically CDoubles, but jhc promises they're the same\n\n-- this line crashes jhc\nforeign import ccall unsafe \"intern.h rb_ary_entry\" rb_ary_entry :: Value -> CLong -> IO Value\n\nforeign import ccall safe \"ruby.h rb_raise\" rb_raise :: Value -> CString -> IO ()\nforeign import ccall unsafe \"ruby.h rb_eval_string\" rb_eval_string :: CString -> Value\n\n\n\n\ndata RValue = T_NIL \n | T_FLOAT Double\n | T_STRING String\n\n -- List is non-ideal. Switch to uvector? Array? There's always going\n -- to be an extraction step to pull the RValues out.\n | T_ARRAY [RValue]\n | T_FIXNUM Int \n | T_HASH Int -- definitely FIXME - native ruby hashes, or going to transliterate into Data.Map?\n | T_BIGNUM Integer \n\n -- technically, these are mapping over the types True and False,\n -- I'm going to treat them as values, though.\n | T_TRUE \n | T_FALSE \n\n | T_SYMBOL Word -- interned string\n\n-- These are the other basic Ruby structures that we're not handling yet.\n-- | T_REGEXP \n-- | T_FILE\n-- | T_STRUCT \n-- | T_DATA \n-- | T_OBJECT \n-- | T_CLASS \n-- | T_MODULE \n\ntoRuby :: RValue -> Value\ntoRuby r = case r of\n T_FLOAT d -> rb_float_new d\n -- need to take the address of the cstr, just cast it to a value\n -- sadly no bytestrings yet - unpack it to a list. yeah it's ugly.\n T_STRING str -> rb_str_new2 $ unsafePerformIO $ newCAString str\n T_FIXNUM i -> int2fix i\n\n -- so this is just bizarre - there's no boolean type. True and False have their own types\n -- as well as their own values.\n T_TRUE -> fromIntegral $ fromEnum RUBY_Qtrue\n T_FALSE -> fromIntegral $ fromEnum RUBY_Qfalse\n T_NIL -> fromIntegral $ fromEnum RUBY_Qnil\n T_ARRAY l -> unsafePerformIO $ do\n ary <- rb_ary_new2 $ fromIntegral $ length l\n mapM_ (rb_ary_push ary . toRuby) l\n return ary\n T_BIGNUM b -> rb_str_to_inum (rb_str_new2 $ unsafePerformIO $ newCAString $ show b) 10 1\n _ -> error \"sorry, haven't implemented that yet.\"\n\nfromRuby :: Value -> RValue\nfromRuby v = case target of\n RT_NIL -> T_NIL\n RT_FIXNUM -> T_FIXNUM $ fix2int v\n RT_STRING -> T_STRING $ unsafePerformIO $ peekCString $ rb_str2cstr v 0\n RT_FLOAT -> T_FLOAT $ num2dbl v\n RT_BIGNUM -> T_BIGNUM $ read $ unsafePerformIO $ peekCString $ rb_str2cstr (rb_big2str v 10) 0\n RT_TRUE -> T_TRUE\n RT_FALSE -> T_FALSE\n RT_ARRAY -> T_ARRAY $ map fromRuby $ unsafePerformIO $ mapM (rb_ary_entry v . fromIntegral) [0..(rb_ary_len v) - 1]\n\n _ -> error (show target)\n where target :: RubyType\n target = toEnum $ rtype v\n\n-- utility stuff\n\nthrowException :: String -> IO Value\nthrowException s = do he <- newCAString \"HaskellError\"\n err <- newCAString s\n rb_raise (rb_eval_string he) err\n error \"shouldn't ever get here\"","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"2dc09233043a2403c94afe3fa85aee4715f3f77a","subject":"Fix for safeGetPixel","message":"Fix for safeGetPixel\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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\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-- |\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\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 = 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.\nblit :: MutableImage GrayScale D32 -> Image GrayScale D32 -> (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 :: (CreateImage (MutableImage 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) = 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":"203f50b75ab8732c624863718e5290c2eee40dff","subject":"Removed datatypecontexts","message":"Removed datatypecontexts\n","repos":"aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV","old_file":"CV\/Histogram.chs","new_file":"CV\/Histogram.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\n\nhistogram imageBins accumulate mask = unsafePerformIO $\n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds\n withPtrList (map imageFPTR images) $ \\ptrs ->\n case mask of\n Just m -> do\n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where\n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface,DatatypeContexts#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\n\nhistogram imageBins accumulate mask = unsafePerformIO $\n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds\n withPtrList (map imageFPTR images) $ \\ptrs ->\n case mask of\n Just m -> do\n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where\n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0de45dec710e93748be4cefc54becea5a0776759","subject":"Add all of the debug info accessors","message":"Add all of the debug info accessors\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.Dwarf\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\ndata CMeta\n{#pointer *CMeta as MetaPtr -> CMeta #}\n\ncMetaTag :: MetaPtr -> IO MetaTag\ncMetaTag v = toEnum . fromIntegral <$> {#get CMeta->tag #} v\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 Int\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\ncMetaGlobalValue :: MetaPtr -> IO ValuePtr\ncMetaGlobalValue = {#get CMeta->u.metaGlobalInfo.global#}\ncMetaLocationLine :: MetaPtr -> IO Int\ncMetaLocationLine p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.lineNumber#} p\ncMetaLocationColumn :: MetaPtr -> IO Int\ncMetaLocationColumn p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.columnNumber#} p\ncMetaLocationScope :: MetaPtr -> IO MetaPtr\ncMetaLocationScope = {#get CMeta->u.metaLocationInfo.scope#}\ncMetaLocationOriginalLocation :: MetaPtr -> IO MetaPtr\ncMetaLocationOriginalLocation = {#get CMeta->u.metaLocationInfo.origLocation#}\ncMetaLocationFilename :: MetaPtr -> KnotMonad ByteString\ncMetaLocationFilename = shareString {#get CMeta->u.metaLocationInfo.filename#}\ncMetaLocationDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaLocationDirectory = shareString {#get CMeta->u.metaLocationInfo.directory#}\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#}\ncMetaTemplateTypeFilename :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateTypeFilename = shareString {#get CMeta->u.metaTemplateTypeInfo.filename#}\ncMetaTemplateTypeDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateTypeDirectory = shareString {#get CMeta->u.metaTemplateTypeInfo.directory#}\ncMetaTemplateTypeLine :: MetaPtr -> IO Int\ncMetaTemplateTypeLine p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.lineNumber#} p\ncMetaTemplateTypeColumn :: MetaPtr -> IO Int\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\ncMetaTemplateValueFilename :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateValueFilename = shareString {#get CMeta->u.metaTemplateValueInfo.filename#}\ncMetaTemplateValueDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateValueDirectory = shareString {#get CMeta->u.metaTemplateValueInfo.directory#}\ncMetaTemplateValueLine :: MetaPtr -> IO Int\ncMetaTemplateValueLine p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.lineNumber#} p\ncMetaTemplateValueColumn :: MetaPtr -> IO Int\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 Int\ncMetaVariableLine p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.lineNumber#} p\ncMetaVariableArgNumber :: MetaPtr -> IO Int\ncMetaVariableArgNumber p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.argNumber#} p\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 =\n peekArray p {#get CMeta->u.metaVariableInfo.addrElements#} {#get CMeta->u.metaVariableInfo.numAddrElements#}\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 Int\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 Int\ncMetaLexicalBlockLine p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.lineNumber#} p\ncMetaLexicalBlockColumn :: MetaPtr -> IO Int\ncMetaLexicalBlockColumn p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.columnNumber#} p\ncMetaLexicalBlockDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaLexicalBlockDirectory = shareString {#get CMeta->u.metaLexicalBlockInfo.directory#}\ncMetaLexicalBlockFilename :: MetaPtr -> KnotMonad ByteString\ncMetaLexicalBlockFilename = shareString {#get CMeta->u.metaLexicalBlockInfo.filename#}\ncMetaNamespaceContext :: MetaPtr -> IO MetaPtr\ncMetaNamespaceContext = {#get CMeta->u.metaNamespaceInfo.context#}\ncMetaNamespaceName :: MetaPtr -> KnotMonad ByteString\ncMetaNamespaceName = shareString {#get CMeta->u.metaNamespaceInfo.name#}\ncMetaNamespaceDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaNamespaceDirectory = shareString {#get CMeta->u.metaNamespaceInfo.directory#}\ncMetaNamespaceCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaNamespaceCompileUnit = {#get CMeta->u.metaNamespaceInfo.compileUnit#}\ncMetaNamespaceLine :: MetaPtr -> IO Int\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 Int\ncMetaSubprogramLine p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.lineNumber#} p\ncMetaSubprogramType :: MetaPtr -> IO MetaPtr\ncMetaSubprogramType = {#get CMeta->u.metaSubprogramInfo.type#}\ncMetaSubprogramReturnTypeName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramReturnTypeName = shareString {#get CMeta->u.metaSubprogramInfo.returnTypeName#}\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 MetaPtr\ncMetaSubprogramContainingType = {#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\ncMetaSubprogramFilename :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramFilename = shareString {#get CMeta->u.metaSubprogramInfo.filename#}\ncMetaSubprogramDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramDirectory = shareString {#get CMeta->u.metaSubprogramInfo.directory#}\ncMetaTypeContext :: MetaPtr -> IO MetaPtr\ncMetaTypeContext = {#get CMeta->u.metaTypeInfo.context#}\ncMetaTypeName :: MetaPtr -> KnotMonad ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\ncMetaTypeCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaTypeCompileUnit = {#get CMeta->u.metaTypeInfo.compileUnit#}\ncMetaTypeFile :: MetaPtr -> IO MetaPtr\ncMetaTypeFile = {#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 :: MetaPtr -> KnotMonad ByteString\ncMetaTypeDirectory = shareString {#get CMeta->u.metaTypeInfo.directory#}\ncMetaTypeFilename :: MetaPtr -> KnotMonad ByteString\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 MetaPtr\ncMetaTypeDerivedFrom = {#get CMeta->u.metaTypeInfo.typeDerivedFrom#}\ncMetaTypeOriginalTypeSize :: MetaPtr -> IO Int64\ncMetaTypeOriginalTypeSize p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.originalTypeSize#} p\ncMetaTypeCompositeComponents :: MetaPtr -> IO MetaPtr\ncMetaTypeCompositeComponents = {#get CMeta->u.metaTypeInfo.typeArray#}\ncMetaTypeRuntimeLanguage :: MetaPtr -> IO Int32\ncMetaTypeRuntimeLanguage p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.runTimeLang#} p\ncMetaTypeContainingType :: MetaPtr -> IO MetaPtr\ncMetaTypeContainingType = {#get CMeta->u.metaTypeInfo.containingType#}\ncMetaTypeTemplateParams :: MetaPtr -> IO MetaPtr\ncMetaTypeTemplateParams = {#get CMeta->u.metaTypeInfo.templateParams#}\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\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 , typeIdSrc :: 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 -> KnotState\nemptyState r1 r2 =\n KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\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\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 res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref)\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 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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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","old_contents":"{-# 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\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\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 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\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\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' } -> `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 , typeIdSrc :: IORef Int\n , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n }\nemptyState :: IORef Int -> IORef Int -> KnotState\nemptyState r1 r2 = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\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\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 _ bitcodefile = do\n m <- marshalLLVM bitcodefile\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 res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref)\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 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\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 tt <- translateType finalState typePtr\n\n uid <- nextId\n\n resetLocalIdCounter\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\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\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 = Nothing\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"249f686a4b06265a69ebf0c7cf194c158e212a10","subject":"Add missing functions to Fl_Table.","message":"Add missing functions to Fl_Table.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Table.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Fl_Table.chs","new_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.FLTK.LowLevel.Fl_Table\n (\n TableFuncs(..),\n defaultTableFuncs,\n tableNew,\n tableDestroy,\n -- * Inherited from Fl_Widget\n tableHandle,\n tableHandleSuper,\n tableParent,\n tableSetParent,\n tableType_,\n tableSetType,\n tableDrawLabel,\n tableX,\n tableY,\n tableW,\n tableH,\n tableSetAlign,\n tableAlign,\n tableBox,\n tableSetBox,\n tableColor,\n tableSetColor,\n tableSetColorWithBgSel,\n tableSelectionColor,\n tableSetSelectionColor,\n tableLabel,\n tableCopyLabel,\n tableSetLabel,\n tableLabeltype,\n tableSetLabeltype,\n tableLabelcolor,\n tableSetLabelcolor,\n tableLabelfont,\n tableSetLabelfont,\n tableLabelsize,\n tableSetLabelsize,\n tableImage,\n tableSetImage,\n tableDeimage,\n tableSetDeimage,\n tableTooltip,\n tableCopyTooltip,\n tableSetTooltip,\n tableWhen,\n tableSetWhen,\n tableVisible,\n tableVisibleR,\n tableShow,\n tableHide,\n tableSetVisible,\n tableClearVisible,\n tableActive,\n tableActiveR,\n tableActivate,\n tableDeactivate,\n tableOutput,\n tableSetOutput,\n tableClearOutput,\n tableTakesevents,\n tableSetChanged,\n tableClearChanged,\n tableTakeFocus,\n tableSetVisibleFocus,\n tableClearVisibleFocus,\n tableModifyVisibleFocus,\n tableVisibleFocus,\n tableContains,\n tableInside,\n tableRedraw,\n tableRedrawLabel,\n tableDamage,\n tableClearDamageWithBitmask,\n tableClearDamage,\n tableDamageWithText,\n tableDamageInsideWidget,\n tableMeasureLabel,\n tableWindow,\n tableTopWindow,\n tableTopWindowOffset,\n tableResize,\n tableResizeSuper,\n tableSetCallback,\n tableBegin,\n tableEnd,\n tableFind,\n tableAdd,\n tableInsert,\n tableRemoveIndex,\n tableRemoveWidget,\n tableClear,\n tableClearSuper,\n tableSetResizable,\n tableResizable,\n tableAddResizable,\n tableInitSizes,\n tableChildren,\n tableSetClipChildren,\n tableClipChildren,\n tableFocus,\n tableDdfdesignKludge,\n tableInsertWithBefore,\n tableArray,\n tableChild,\n -- * Fl_Table specific\n tableSetTableBox,\n tableTableBox,\n tableSetRowsSuper,\n tableSetRows,\n tableRows,\n tableSetColsSuper,\n tableSetCols,\n tableCols,\n tableSetVisibleCells,\n tableIsInteractiveResize,\n tableRowResize,\n tableSetRowResize,\n tableColResize,\n tableSetColResize,\n tableColResizeMin,\n tableSetColResizeMin,\n tableRowResizeMin,\n tableSetRowResizeMin,\n tableRowHeader,\n tableSetRowHeader,\n tableColHeader,\n tableSetColHeader,\n tableSetColHeaderHeight,\n tableColHeaderHeight,\n tableSetRowHeaderWidth,\n tableRowHeaderWidth,\n tableSetRowHeaderColor,\n tableRowHeaderColor,\n tableSetColHeaderColor,\n tableColHeaderColor,\n tableSetRowHeight,\n tableRowHeight,\n tableSetColWidth,\n tableColWidth,\n tableSetRowHeightAll,\n tableSetColWidthAll,\n tableSetRowPosition,\n tableSetColPosition,\n tableRowPosition,\n tableColPosition,\n tableSetTopRow,\n tableTopRow,\n tableIsSelected,\n tableGetSelection,\n tableSetSelection,\n tableMoveCursor,\n tableDraw,\n tableDrawSuper,\n tableInsertWithWidget,\n tableCallbackRow,\n tableCallbackCol,\n tableCallbackContext,\n tableDoCallback,\n tableFindCell,\n tableAsWindow,\n tableAsWindowSuper,\n tableAsGroup,\n tableAsGroupSuper,\n tableAsGlWindow,\n tableAsGlWindowSuper\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_TableC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Group\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\ndata TableFuncs a =\n TableFuncs\n {\n tableDrawOverride :: Maybe (WidgetCallback a)\n ,tableHandleOverride :: Maybe (WidgetEventHandler a)\n ,tableResizeOverride :: Maybe (RectangleF a)\n ,tableShowOverride :: Maybe (WidgetCallback a)\n ,tableHideOverride :: Maybe (WidgetCallback a)\n ,tableAsWindowOverride :: Maybe (GetWindowF a)\n ,tableAsGlWindowOverride :: Maybe (GetGlWindowF a)\n ,tableAsGroupOverride :: Maybe (GetGroupF a)\n ,tableDrawCellOverride :: Maybe (TableDrawCellF a)\n ,tableClearOverride :: Maybe (WidgetCallback a)\n ,tableSetRowsOverride :: Maybe (TableSetIntF a)\n ,tableSetColsOverride :: Maybe (TableSetIntF a)\n }\n\ntableFunctionStruct :: (TableFuncs a) -> IO (Ptr ())\ntableFunctionStruct funcs = do\n p <- mallocBytes {#sizeof fl_Table_Virtual_Funcs #}\n toCallbackPrim `orNullFunPtr` (tableDrawOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->draw#} p\n toEventHandlerPrim `orNullFunPtr` (tableHandleOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->handle#} p\n toRectangleFPrim `orNullFunPtr` (tableResizeOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->resize#} p\n toCallbackPrim `orNullFunPtr` (tableShowOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->show#} p\n toCallbackPrim `orNullFunPtr` (tableHideOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->hide#} p\n toGetWindowFPrim `orNullFunPtr` (tableAsWindowOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->as_window#} p\n toGetGlWindowFPrim `orNullFunPtr` (tableAsGlWindowOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->as_gl_window#} p\n toGetGroupFPrim `orNullFunPtr` (tableAsGroupOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->as_group#} p\n toTableDrawCellPrim `orNullFunPtr` (tableDrawCellOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->draw_cell#} p\n toCallbackPrim `orNullFunPtr` (tableClearOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->clear#} p\n toTableSetIntFPrim `orNullFunPtr` (tableSetRowsOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->set_rows#} p \n toTableSetIntFPrim `orNullFunPtr` (tableSetColsOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->set_cols#} p\n return p\ndefaultTableFuncs :: TableFuncs a\ndefaultTableFuncs = TableFuncs Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing\n{# fun Fl_Table_New as tableNew' { `Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_Table_New_WithLabel as tableNewWithLabel' { `Int',`Int',`Int',`Int',`String', id `Ptr ()'} -> `Ptr ()' id #}\ntableNew :: Rectangle -> Maybe String -> TableFuncs a -> IO (Table ())\ntableNew rectangle label' funcs' =\n do \n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n ptr <- tableFunctionStruct funcs'\n case label' of\n (Just l') -> tableNewWithLabel' x_pos y_pos width height l' (castPtr ptr) >>= toObject\n Nothing -> tableNew' x_pos y_pos width height (castPtr ptr) >>= toObject\n\n{# fun Fl_Table_Destroy as tableDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ntableDestroy :: Table a -> IO ()\ntableDestroy table = withObject table $ \\tablePtr -> tableDestroy' tablePtr\ntableParent :: Table a -> IO (Group ())\ntableParent = groupParent\ntableSetParent :: Table a -> Group b -> IO ()\ntableSetParent = groupSetParent\ntableType_ :: Table a -> IO (Word8)\ntableType_ = groupType_\ntableSetType :: Table a -> Word8 -> IO (())\ntableSetType = groupSetType\ntableDrawLabel :: Table a -> Maybe (Rectangle,AlignType)-> IO (())\ntableDrawLabel = groupDrawLabel\ntableX :: Table a -> IO (Int)\ntableX = groupX\ntableY :: Table a -> IO (Int)\ntableY = groupY\ntableW :: Table a -> IO (Int)\ntableW = groupW\ntableH :: Table a -> IO (Int)\ntableH = groupH\ntableSetAlign :: Table a -> AlignType -> IO (())\ntableSetAlign = groupSetAlign\ntableAlign :: Table a -> IO (AlignType)\ntableAlign = groupAlign\ntableBox :: Table a -> IO (Boxtype)\ntableBox = groupBox\ntableSetBox :: Table a -> Boxtype -> IO (())\ntableSetBox = groupSetBox\ntableColor :: Table a -> IO (Color)\ntableColor = groupColor\ntableSetColor :: Table a -> Color -> IO (())\ntableSetColor = groupSetColor\ntableSetColorWithBgSel :: Table a -> Color -> Color -> IO (())\ntableSetColorWithBgSel = groupSetColorWithBgSel\ntableSelectionColor :: Table a -> IO (Color)\ntableSelectionColor = groupSelectionColor\ntableSetSelectionColor :: Table a -> Color -> IO (())\ntableSetSelectionColor = groupSetSelectionColor\ntableLabel :: Table a -> IO (String)\ntableLabel = groupLabel\ntableCopyLabel :: Table a -> String -> IO (())\ntableCopyLabel = groupCopyLabel\ntableSetLabel :: Table a -> String -> IO (())\ntableSetLabel = groupSetLabel\ntableLabeltype :: Table a -> IO (Labeltype)\ntableLabeltype = groupLabeltype\ntableSetLabeltype :: Table a -> Labeltype -> IO (())\ntableSetLabeltype = groupSetLabeltype\ntableLabelcolor :: Table a -> IO (Color)\ntableLabelcolor = groupLabelcolor\ntableSetLabelcolor :: Table a -> Color -> IO (())\ntableSetLabelcolor = groupSetLabelcolor\ntableLabelfont :: Table a -> IO (Font)\ntableLabelfont = groupLabelfont\ntableSetLabelfont :: Table a -> Font -> IO (())\ntableSetLabelfont = groupSetLabelfont\ntableLabelsize :: Table a -> IO (FontSize)\ntableLabelsize = groupLabelsize\ntableSetLabelsize :: Table a -> FontSize -> IO (())\ntableSetLabelsize = groupSetLabelsize\ntableImage :: Table a -> IO (Image ())\ntableImage = groupImage\ntableSetImage :: Table a -> Image b -> IO (())\ntableSetImage = groupSetImage\ntableDeimage :: Table a -> IO (Image ())\ntableDeimage = groupDeimage\ntableSetDeimage :: Table a -> Image b -> IO (())\ntableSetDeimage = groupSetDeimage\ntableTooltip :: Table a -> IO (String)\ntableTooltip = groupTooltip\ntableCopyTooltip :: Table a -> String -> IO (())\ntableCopyTooltip = groupCopyTooltip\ntableSetTooltip :: Table a -> String -> IO (())\ntableSetTooltip = groupSetTooltip\ntableWhen :: Table a -> IO (When)\ntableWhen = groupWhen\ntableSetWhen :: Table a -> Word8 -> IO (())\ntableSetWhen = groupSetWhen\ntableVisible :: Table a -> IO (Int)\ntableVisible = groupVisible\ntableVisibleR :: Table a -> IO (Int)\ntableVisibleR = groupVisibleR\ntableShow :: Table a -> IO (())\ntableShow = groupShow\ntableHide :: Table a -> IO (())\ntableHide = groupHide\ntableSetVisible :: Table a -> IO (())\ntableSetVisible = groupSetVisible\ntableClearVisible :: Table a -> IO (())\ntableClearVisible = groupClearVisible\ntableActive :: Table a -> IO (Int)\ntableActive = groupActive\ntableActiveR :: Table a -> IO (Int)\ntableActiveR = groupActiveR\ntableActivate :: Table a -> IO (())\ntableActivate = groupActivate\ntableDeactivate :: Table a -> IO (())\ntableDeactivate = groupDeactivate\ntableOutput :: Table a -> IO (Int)\ntableOutput = groupOutput\ntableSetOutput :: Table a -> IO (())\ntableSetOutput = groupSetOutput\ntableClearOutput :: Table a -> IO (())\ntableClearOutput = groupClearOutput\ntableTakesevents :: Table a -> IO (Int)\ntableTakesevents = groupTakesevents\ntableSetChanged :: Table a -> IO (())\ntableSetChanged = groupSetChanged\ntableClearChanged :: Table a -> IO (())\ntableClearChanged = groupClearChanged\ntableTakeFocus :: Table a -> IO (Int)\ntableTakeFocus = groupTakeFocus\ntableSetVisibleFocus :: Table a -> IO (())\ntableSetVisibleFocus = groupSetVisibleFocus\ntableClearVisibleFocus :: Table a -> IO (())\ntableClearVisibleFocus = groupClearVisibleFocus\ntableModifyVisibleFocus :: Table a -> Int -> IO (())\ntableModifyVisibleFocus = groupModifyVisibleFocus\ntableVisibleFocus :: Table a -> IO (Int)\ntableVisibleFocus = groupVisibleFocus\ntableContains :: Table a -> Group b -> IO (Int)\ntableContains = groupContains\ntableInside :: Table a -> Group b -> IO (Int)\ntableInside = groupInside\ntableRedraw :: Table a -> IO (())\ntableRedraw = groupRedraw\ntableRedrawLabel :: Table a -> IO (())\ntableRedrawLabel = groupRedrawLabel\ntableDamage :: Table a -> IO (Word8)\ntableDamage = groupDamage\ntableClearDamageWithBitmask :: Table a -> Word8 -> IO (())\ntableClearDamageWithBitmask = groupClearDamageWithBitmask\ntableClearDamage :: Table a -> IO (())\ntableClearDamage = groupClearDamage\ntableDamageWithText :: Table a -> Word8 -> IO (())\ntableDamageWithText = groupDamageWithText\ntableDamageInsideWidget :: Table a -> Word8 -> Rectangle -> IO (())\ntableDamageInsideWidget = groupDamageInsideWidget\ntableMeasureLabel :: Table a -> IO (Size)\ntableMeasureLabel = groupMeasureLabel\ntableWindow :: Table a -> IO (Window ())\ntableWindow = groupWindow\ntableTopWindow :: Table a -> IO (Window ())\ntableTopWindow = groupTopWindow\ntableTopWindowOffset :: Table a -> IO (Position)\ntableTopWindowOffset = groupTopWindowOffset\ntableSetCallback :: Table a -> (Group b -> IO ()) -> IO (())\ntableSetCallback = groupSetCallback\ntableRemoveIndex :: Table a -> Int -> IO (())\ntableRemoveIndex = groupRemoveIndex\ntableRemoveWidget :: Table b -> Widget a -> IO (())\ntableRemoveWidget = groupRemoveWidget\ntableSetResizable :: Table b -> Widget a -> IO (())\ntableSetResizable = groupSetResizable\ntableResizable :: Table a -> IO (Widget ())\ntableResizable = groupResizable\ntableAddResizable :: Table b -> Widget a -> IO (())\ntableAddResizable = groupAddResizable\ntableSetClipChildren :: Table a -> Int -> IO (())\ntableSetClipChildren = groupSetClipChildren\ntableClipChildren :: Table a -> IO (Int)\ntableClipChildren = groupClipChildren\ntableFocus :: Group b -> Widget a -> IO (())\ntableFocus = groupFocus\ntableDdfdesignKludge :: Table a -> IO (Widget ())\ntableDdfdesignKludge = groupDdfdesignKludge\ntableInsertWithBefore :: Group b -> Widget a -> Widget c -> IO (())\ntableInsertWithBefore = groupInsertWithBefore\n{# fun unsafe Fl_Table_set_table_box as setTableBox' { id `Ptr ()',cFromEnum `Boxtype' } -> `()' #}\ntableSetTableBox :: Table a -> Boxtype -> IO ()\ntableSetTableBox table val = withObject table $ \\tablePtr -> setTableBox' tablePtr val\n{# fun unsafe Fl_Table_table_box as tableBox' { id `Ptr ()' } -> `Boxtype' cToEnum #}\ntableTableBox :: Table a -> IO (Boxtype)\ntableTableBox table = withObject table $ \\tablePtr -> tableBox' tablePtr\n{# fun unsafe Fl_Table_set_rows as setRows' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRows :: Table a -> Int -> IO ()\ntableSetRows table val = withObject table $ \\tablePtr -> setRows' tablePtr val\n{# fun unsafe Fl_Table_rows as rows' { id `Ptr ()' } -> `Int' #}\ntableRows :: Table a -> IO (Int)\ntableRows table = withObject table $ \\tablePtr -> rows' tablePtr\n{# fun unsafe Fl_Table_set_cols as setCols' { id `Ptr ()',`Int' } -> `()' #}\ntableSetCols :: Table a -> Int -> IO ()\ntableSetCols table val = withObject table $ \\tablePtr -> setCols' tablePtr val\n{# fun unsafe Fl_Table_cols as cols' { id `Ptr ()' } -> `Int' #}\ntableCols :: Table a -> IO (Int)\ntableCols table = withObject table $ \\tablePtr -> cols' tablePtr\n{# fun unsafe Fl_Table_set_visible_cells as setVisibleCells' { id `Ptr ()',id `Ptr CInt',id `Ptr CInt',id `Ptr CInt',id `Ptr CInt' } -> `()' #}\ntableSetVisibleCells :: Table a -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()\ntableSetVisibleCells table r1 r2 c1 c2 = withObject table $ \\tablePtr -> setVisibleCells' tablePtr r1 r2 c1 c2\n{# fun unsafe Fl_Table_is_interactive_resize as isInteractiveResize' { id `Ptr ()' } -> `Int' #}\ntableIsInteractiveResize :: Table a -> IO (Int)\ntableIsInteractiveResize table = withObject table $ \\tablePtr -> isInteractiveResize' tablePtr\n{# fun unsafe Fl_Table_row_resize as rowResize' { id `Ptr ()' } -> `Int' #}\ntableRowResize :: Table a -> IO (Int)\ntableRowResize table = withObject table $ \\tablePtr -> rowResize' tablePtr\n{# fun unsafe Fl_Table_set_row_resize as setRowResize' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowResize :: Table a -> Int -> IO ()\ntableSetRowResize table flag = withObject table $ \\tablePtr -> setRowResize' tablePtr flag\n{# fun unsafe Fl_Table_col_resize as colResize' { id `Ptr ()' } -> `Int' #}\ntableColResize :: Table a -> IO (Int)\ntableColResize table = withObject table $ \\tablePtr -> colResize' tablePtr\n{# fun unsafe Fl_Table_set_col_resize as setColResize' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColResize :: Table a -> Int -> IO ()\ntableSetColResize table flag = withObject table $ \\tablePtr -> setColResize' tablePtr flag\n{# fun unsafe Fl_Table_col_resize_min as colResizeMin' { id `Ptr ()' } -> `Int' #}\ntableColResizeMin :: Table a -> IO (Int)\ntableColResizeMin table = withObject table $ \\tablePtr -> colResizeMin' tablePtr\n{# fun unsafe Fl_Table_set_col_resize_min as setColResizeMin' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColResizeMin :: Table a -> Int -> IO ()\ntableSetColResizeMin table val = withObject table $ \\tablePtr -> setColResizeMin' tablePtr val\n{# fun unsafe Fl_Table_row_resize_min as rowResizeMin' { id `Ptr ()' } -> `Int' #}\ntableRowResizeMin :: Table a -> IO (Int)\ntableRowResizeMin table = withObject table $ \\tablePtr -> rowResizeMin' tablePtr\n{# fun unsafe Fl_Table_set_row_resize_min as setRowResizeMin' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowResizeMin :: Table a -> Int -> IO ()\ntableSetRowResizeMin table val = withObject table $ \\tablePtr -> setRowResizeMin' tablePtr val\n{# fun unsafe Fl_Table_row_header as rowHeader' { id `Ptr ()' } -> `Int' #}\ntableRowHeader :: Table a -> IO (Int)\ntableRowHeader table = withObject table $ \\tablePtr -> rowHeader' tablePtr\n{# fun unsafe Fl_Table_set_row_header as setRowHeader' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowHeader :: Table a -> Int -> IO ()\ntableSetRowHeader table flag = withObject table $ \\tablePtr -> setRowHeader' tablePtr flag\n{# fun unsafe Fl_Table_col_header as colHeader' { id `Ptr ()' } -> `Int' #}\ntableColHeader :: Table a -> IO (Int)\ntableColHeader table = withObject table $ \\tablePtr -> colHeader' tablePtr\n{# fun unsafe Fl_Table_set_col_header as setColHeader' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColHeader :: Table a -> Int -> IO ()\ntableSetColHeader table flag = withObject table $ \\tablePtr -> setColHeader' tablePtr flag\n{# fun unsafe Fl_Table_set_col_header_height as setColHeaderHeight' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColHeaderHeight :: Table a -> Int -> IO ()\ntableSetColHeaderHeight table height = withObject table $ \\tablePtr -> setColHeaderHeight' tablePtr height\n{# fun unsafe Fl_Table_col_header_height as colHeaderHeight' { id `Ptr ()' } -> `Int' #}\ntableColHeaderHeight :: Table a -> IO (Int)\ntableColHeaderHeight table = withObject table $ \\tablePtr -> colHeaderHeight' tablePtr\n{# fun unsafe Fl_Table_set_row_header_width as setRowHeaderWidth' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowHeaderWidth :: Table a -> Int -> IO ()\ntableSetRowHeaderWidth table width = withObject table $ \\tablePtr -> setRowHeaderWidth' tablePtr width\n{# fun unsafe Fl_Table_row_header_width as rowHeaderWidth' { id `Ptr ()' } -> `Int' #}\ntableRowHeaderWidth :: Table a -> IO (Int)\ntableRowHeaderWidth table = withObject table $ \\tablePtr -> rowHeaderWidth' tablePtr\n{# fun unsafe Fl_Table_set_row_header_color as setRowHeaderColor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ntableSetRowHeaderColor :: Table a -> Color -> IO ()\ntableSetRowHeaderColor table val = withObject table $ \\tablePtr -> setRowHeaderColor' tablePtr val\n{# fun unsafe Fl_Table_row_header_color as rowHeaderColor' { id `Ptr ()' } -> `Color' cToColor #}\ntableRowHeaderColor :: Table a -> IO (Color)\ntableRowHeaderColor table = withObject table $ \\tablePtr -> rowHeaderColor' tablePtr\n{# fun unsafe Fl_Table_set_col_header_color as setColHeaderColor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ntableSetColHeaderColor :: Table a -> Color -> IO ()\ntableSetColHeaderColor table val = withObject table $ \\tablePtr -> setColHeaderColor' tablePtr val\n{# fun unsafe Fl_Table_col_header_color as colHeaderColor' { id `Ptr ()' } -> `Color' cToColor #}\ntableColHeaderColor :: Table a -> IO (Color)\ntableColHeaderColor table = withObject table $ \\tablePtr -> colHeaderColor' tablePtr\n{# fun unsafe Fl_Table_set_row_height as setRowHeight' { id `Ptr ()',`Int',`Int' } -> `()' #}\ntableSetRowHeight :: Table a -> Int -> Int -> IO ()\ntableSetRowHeight table row height = withObject table $ \\tablePtr -> setRowHeight' tablePtr row height\n{# fun unsafe Fl_Table_row_height as rowHeight' { id `Ptr ()',`Int' } -> `Int' #}\ntableRowHeight :: Table a -> Int -> IO (Int)\ntableRowHeight table row = withObject table $ \\tablePtr -> rowHeight' tablePtr row\n{# fun unsafe Fl_Table_set_col_width as setColWidth' { id `Ptr ()',`Int',`Int' } -> `()' #}\ntableSetColWidth :: Table a -> Int -> Int -> IO ()\ntableSetColWidth table col width = withObject table $ \\tablePtr -> setColWidth' tablePtr col width\n{# fun unsafe Fl_Table_col_width as colWidth' { id `Ptr ()',`Int' } -> `Int' #}\ntableColWidth :: Table a -> Int -> IO (Int)\ntableColWidth table col = withObject table $ \\tablePtr -> colWidth' tablePtr col\n{# fun unsafe Fl_Table_set_row_height_all as setRowHeightAll' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowHeightAll :: Table a -> Int -> IO ()\ntableSetRowHeightAll table height = withObject table $ \\tablePtr -> setRowHeightAll' tablePtr height\n{# fun unsafe Fl_Table_set_col_width_all as setColWidthAll' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColWidthAll :: Table a -> Int -> IO ()\ntableSetColWidthAll table width = withObject table $ \\tablePtr -> setColWidthAll' tablePtr width\n{# fun unsafe Fl_Table_set_row_position as setRowPosition' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowPosition :: Table a -> Int -> IO ()\ntableSetRowPosition table row = withObject table $ \\tablePtr -> setRowPosition' tablePtr row\n{# fun unsafe Fl_Table_set_col_position as setColPosition' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColPosition :: Table a -> Int -> IO ()\ntableSetColPosition table col = withObject table $ \\tablePtr -> setColPosition' tablePtr col\n{# fun unsafe Fl_Table_row_position as rowPosition' { id `Ptr ()' } -> `Int' #}\ntableRowPosition :: Table a -> IO (Int)\ntableRowPosition table = withObject table $ \\tablePtr -> rowPosition' tablePtr\n{# fun unsafe Fl_Table_col_position as colPosition' { id `Ptr ()' } -> `Int' #}\ntableColPosition :: Table a -> IO (Int)\ntableColPosition table = withObject table $ \\tablePtr -> colPosition' tablePtr\n{# fun unsafe Fl_Table_set_top_row as setTopRow' { id `Ptr ()',`Int' } -> `()' #}\ntableSetTopRow :: Table a -> Int -> IO ()\ntableSetTopRow table row = withObject table $ \\tablePtr -> setTopRow' tablePtr row\n{# fun unsafe Fl_Table_top_row as topRow' { id `Ptr ()' } -> `Int' #}\ntableTopRow :: Table a -> IO (Int)\ntableTopRow table = withObject table $ \\tablePtr -> topRow' tablePtr\n{# fun unsafe Fl_Table_is_selected as isSelected' { id `Ptr ()',`Int',`Int' } -> `Int' #}\ntableIsSelected :: Table a -> Int -> Int -> IO (Int)\ntableIsSelected table r c = withObject table $ \\tablePtr -> isSelected' tablePtr r c\n{# fun unsafe Fl_Table_get_selection as getSelection' { id `Ptr ()',alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' #}\ntableGetSelection :: Table a -> IO (Position, Position)\ntableGetSelection table = \n withObject table $ \\tablePtr -> \n getSelection' tablePtr >>= \\(rt, cl, rb, cr) -> \n return $ (Position (X rt) (Y cl), Position (X rb) (Y cr))\n{# fun unsafe Fl_Table_set_selection as setSelection' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ntableSetSelection :: Table a -> Int -> Int -> Int -> Int -> IO ()\ntableSetSelection table row_top col_left row_bot col_right = withObject table $ \\tablePtr -> setSelection' tablePtr row_top col_left row_bot col_right\n{# fun unsafe Fl_Table_move_cursor as moveCursor' { id `Ptr ()',`Int',`Int' } -> `Int' #}\ntableMoveCursor :: Table a -> Int -> Int -> IO (Int)\ntableMoveCursor table r c = withObject table $ \\tablePtr -> moveCursor' tablePtr r c\n{# fun unsafe Fl_Table_init_sizes as initSizes' { id `Ptr ()' } -> `()' #}\ntableInitSizes :: Table a -> IO ()\ntableInitSizes table = withObject table $ \\tablePtr -> initSizes' tablePtr\n{# fun unsafe Fl_Table_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ntableAdd :: Table a -> Widget a -> IO ()\ntableAdd table wgt = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> add' tablePtr wgtPtr\n{# fun unsafe Fl_Table_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' #}\ntableInsert :: Table a -> Widget a -> Int -> IO ()\ntableInsert table wgt n = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> insert' tablePtr wgtPtr n\n{# fun unsafe Fl_Table_insert_with_widget as insertWithWidget' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' #}\ntableInsertWithWidget :: Table a -> Widget b -> Widget c -> IO ()\ntableInsertWithWidget table wgt w2 = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> withObject w2 $ \\w2Ptr -> insertWithWidget' tablePtr wgtPtr w2Ptr\n{# fun unsafe Fl_Table_begin as begin' { id `Ptr ()' } -> `()' #}\ntableBegin :: Table a -> IO ()\ntableBegin table = withObject table $ \\tablePtr -> begin' tablePtr\n{# fun unsafe Fl_Table_end as end' { id `Ptr ()' } -> `()' #}\ntableEnd :: Table a -> IO ()\ntableEnd table = withObject table $ \\tablePtr -> end' tablePtr\n{# fun unsafe Fl_Table_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id #}\ntableArray :: Table a -> IO [Widget ()]\ntableArray table = withObject table $ \\tablePtr -> do\n childArrayPtr <- array' tablePtr\n numChildren <- tableChildren table\n arrayToObjects childArrayPtr numChildren\n{# fun unsafe Fl_Table_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ntableChild :: Table a -> Int -> IO (Widget ())\ntableChild table n = withObject table $ \\tablePtr -> child' tablePtr n >>= toObject\n{# fun unsafe Fl_Table_children as children' { id `Ptr ()' } -> `Int' #}\ntableChildren :: Table a -> IO (Int)\ntableChildren table = withObject table $ \\tablePtr -> children' tablePtr\n{# fun unsafe Fl_Table_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ntableFind :: Table a -> Widget a -> IO (Int)\ntableFind table wgt = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> find' tablePtr wgtPtr\n{# fun unsafe Fl_Table_callback_row as callbackRow' { id `Ptr ()' } -> `Int' #}\ntableCallbackRow :: Table a -> IO (Int)\ntableCallbackRow table = withObject table $ \\tablePtr -> callbackRow' tablePtr\n{# fun unsafe Fl_Table_callback_col as callbackCol' { id `Ptr ()' } -> `Int' #}\ntableCallbackCol :: Table a -> IO (Int)\ntableCallbackCol table = withObject table $ \\tablePtr -> callbackCol' tablePtr\n{# fun unsafe Fl_Table_callback_context as callbackContext' { id `Ptr ()' } -> `TableContext' cToEnum #}\ntableCallbackContext :: Table a -> IO (TableContext)\ntableCallbackContext table = withObject table $ \\tablePtr -> callbackContext' tablePtr\n{# fun unsafe Fl_Table_do_callback as doCallback' { id `Ptr ()',cFromEnum `TableContext',`Int',`Int' } -> `()' #}\ntableDoCallback :: Table a -> TableContext -> Int -> Int -> IO ()\ntableDoCallback table tablecontext row col = withObject table $ \\tablePtr -> doCallback' tablePtr tablecontext row col\n{# fun unsafe Fl_Table_find_cell as findCell' { id `Ptr ()',cFromEnum `TableContext',`Int',`Int',alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv* } -> `CInt' id #}\ntableFindCell :: Table a -> TableContext -> Int -> Int -> IO (Maybe Rectangle)\ntableFindCell table context r c = \n withObject table $ \\tablePtr -> \n findCell' tablePtr context r c >>= \\(result, x_pos', y_pos', width', height') -> \n if (cToBool result)\n then return $ Just $ toRectangle (x_pos', y_pos', width', height')\n else return $ Nothing\n{# fun unsafe Fl_Table_draw_super as drawSuper' { id `Ptr ()' } -> `()' #}\ntableDrawSuper :: Table a -> IO ()\ntableDrawSuper table = withObject table $ \\tablePtr -> drawSuper' tablePtr\n{# fun unsafe Fl_Table_draw as draw' { id `Ptr ()' } -> `()' #}\ntableDraw :: Table a -> IO ()\ntableDraw table = withObject table $ \\tablePtr -> draw' tablePtr \n{# fun unsafe Fl_Table_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\ntableHandleSuper :: Table a -> Int -> IO (Int)\ntableHandleSuper table event = withObject table $ \\tablePtr -> handleSuper' tablePtr event \n{# fun unsafe Fl_Table_handle as handle' { id `Ptr ()',`Int' } -> `Int' #}\ntableHandle :: Table a -> Int -> IO (Int)\ntableHandle table event = withObject table $ \\tablePtr -> handle' tablePtr event \n{# fun unsafe Fl_Table_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ntableResizeSuper :: Table a -> Rectangle -> IO ()\ntableResizeSuper table rectangle = let (x_pos', y_pos', width', height') = fromRectangle rectangle in withObject table $ \\tablePtr -> resizeSuper' tablePtr x_pos' y_pos' width' height' \n{# fun unsafe Fl_Table_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ntableResize :: Table a -> Rectangle -> IO ()\ntableResize table rectangle = let (x_pos', y_pos', width', height') = fromRectangle rectangle in withObject table $ \\tablePtr -> resize' tablePtr x_pos' y_pos' width' height' \n{# fun unsafe Fl_Table_clear_super as clearSuper' { id `Ptr ()' } -> `()' #}\ntableClearSuper :: Table a -> IO ()\ntableClearSuper table = withObject table $ \\tablePtr -> clearSuper' tablePtr \n{# fun unsafe Fl_Table_clear as clear' { id `Ptr ()' } -> `()' #}\ntableClear :: Table a -> IO ()\ntableClear table = withObject table $ \\tablePtr -> clear' tablePtr \n{# fun unsafe Fl_Table_as_window_super as asWindowSuper' { id `Ptr ()' } -> `Ptr ()' id #}\ntableAsWindowSuper :: Table a -> IO (Window ())\ntableAsWindowSuper table = withObject table $ \\tablePtr -> asWindowSuper' tablePtr >>= toObject \n{# fun unsafe Fl_Table_as_window as asWindow' { id `Ptr ()' } -> `Ptr ()' id #}\ntableAsWindow :: Table a -> IO (Window ())\ntableAsWindow table = withObject table $ \\tablePtr -> asWindow' tablePtr >>= toObject \n{# fun unsafe Fl_Table_as_group_super as asGroupSuper' { id `Ptr ()' } -> `Ptr ()' id #}\ntableAsGroupSuper :: Table a -> IO (Group ())\ntableAsGroupSuper table = withObject table $ \\tablePtr -> asGroupSuper' tablePtr >>= toObject \n{# fun unsafe Fl_Table_as_group as asGroup' { id `Ptr ()' } -> `Ptr ()' id #}\ntableAsGroup :: Table a -> IO (Group ())\ntableAsGroup table = withObject table $ \\tablePtr -> asGroup' tablePtr >>= toObject \n{# fun unsafe Fl_Table_as_gl_window_super as asGlWindowSuper' { id `Ptr ()' } -> `Ptr ()' id #}\ntableAsGlWindowSuper :: Table a -> IO (GlWindow ())\ntableAsGlWindowSuper table = withObject table $ \\tablePtr -> asGlWindowSuper' tablePtr >>= toObject \n{# fun unsafe Fl_Table_as_gl_window as asGlWindow' { id `Ptr ()' } -> `Ptr ()' id #}\ntableAsGlWindow :: Table a -> IO (GlWindow ())\ntableAsGlWindow table = withObject table $ \\tablePtr -> asGlWindow' tablePtr >>= toObject \n{# fun unsafe Fl_Table_set_rows_super as setRowsSuper' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowsSuper :: Table a -> Int -> IO ()\ntableSetRowsSuper table val = withObject table $ \\tablePtr -> setRowsSuper' tablePtr val \n{# fun unsafe Fl_Table_set_cols_super as setColsSuper' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColsSuper :: Table a -> Int -> IO ()\ntableSetColsSuper table val = withObject table $ \\tablePtr -> setColsSuper' tablePtr val \n \n","old_contents":"{-# LANGUAGE CPP #-}\nmodule Graphics.UI.FLTK.LowLevel.Fl_Table\n (\n TableFuncs(..),\n defaultTableFuncs,\n tableNew,\n tableDestroy,\n -- * Inherited from Fl_Widget\n tableHandle,\n tableParent,\n tableSetParent,\n tableType_,\n tableSetType,\n tableDrawLabel,\n tableX,\n tableY,\n tableW,\n tableH,\n tableSetAlign,\n tableAlign,\n tableBox,\n tableSetBox,\n tableColor,\n tableSetColor,\n tableSetColorWithBgSel,\n tableSelectionColor,\n tableSetSelectionColor,\n tableLabel,\n tableCopyLabel,\n tableSetLabel,\n tableLabeltype,\n tableSetLabeltype,\n tableLabelcolor,\n tableSetLabelcolor,\n tableLabelfont,\n tableSetLabelfont,\n tableLabelsize,\n tableSetLabelsize,\n tableImage,\n tableSetImage,\n tableDeimage,\n tableSetDeimage,\n tableTooltip,\n tableCopyTooltip,\n tableSetTooltip,\n tableWhen,\n tableSetWhen,\n tableVisible,\n tableVisibleR,\n tableShow,\n tableHide,\n tableSetVisible,\n tableClearVisible,\n tableActive,\n tableActiveR,\n tableActivate,\n tableDeactivate,\n tableOutput,\n tableSetOutput,\n tableClearOutput,\n tableTakesevents,\n tableSetChanged,\n tableClearChanged,\n tableTakeFocus,\n tableSetVisibleFocus,\n tableClearVisibleFocus,\n tableModifyVisibleFocus,\n tableVisibleFocus,\n tableContains,\n tableInside,\n tableRedraw,\n tableRedrawLabel,\n tableDamage,\n tableClearDamageWithBitmask,\n tableClearDamage,\n tableDamageWithText,\n tableDamageInsideWidget,\n tableMeasureLabel,\n tableWindow,\n tableTopWindow,\n tableTopWindowOffset,\n tableAsGroup,\n tableAsGlWindow,\n tableResize,\n tableSetCallback,\n tableBegin,\n tableEnd,\n tableFind,\n tableAdd,\n tableInsert,\n tableRemoveIndex,\n tableRemoveWidget,\n tableClear,\n tableSetResizable,\n tableResizable,\n tableAddResizable,\n tableInitSizes,\n tableChildren,\n tableSetClipChildren,\n tableClipChildren,\n tableFocus,\n tableDdfdesignKludge,\n tableInsertWithBefore,\n tableArray,\n tableChild,\n -- * Fl_Table specific\n tableSetTableBox,\n tableTableBox,\n tableSetRowsSuper,\n tableSetRows,\n tableRows,\n tableSetColsSuper,\n tableSetCols,\n tableCols,\n tableSetVisibleCells,\n tableIsInteractiveResize,\n tableRowResize,\n tableSetRowResize,\n tableColResize,\n tableSetColResize,\n tableColResizeMin,\n tableSetColResizeMin,\n tableRowResizeMin,\n tableSetRowResizeMin,\n tableRowHeader,\n tableSetRowHeader,\n tableColHeader,\n tableSetColHeader,\n tableSetColHeaderHeight,\n tableColHeaderHeight,\n tableSetRowHeaderWidth,\n tableRowHeaderWidth,\n tableSetRowHeaderColor,\n tableRowHeaderColor,\n tableSetColHeaderColor,\n tableColHeaderColor,\n tableSetRowHeight,\n tableRowHeight,\n tableSetColWidth,\n tableColWidth,\n tableSetRowHeightAll,\n tableSetColWidthAll,\n tableSetRowPosition,\n tableSetColPosition,\n tableRowPosition,\n tableColPosition,\n tableSetTopRow,\n tableTopRow,\n tableIsSelected,\n tableGetSelection,\n tableSetSelection,\n tableMoveCursor,\n tableDraw,\n tableInsertWithWidget,\n tableCallbackRow,\n tableCallbackCol,\n tableCallbackContext,\n tableDoCallback,\n tableFindCell\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_TableC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign.C.Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Group\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\ndata TableFuncs a =\n TableFuncs\n {\n tableDrawOverride :: Maybe (WidgetCallback a)\n ,tableHandleOverride :: Maybe (WidgetEventHandler a)\n ,tableResizeOverride :: Maybe (RectangleF a)\n ,tableShowOverride :: Maybe (WidgetCallback a)\n ,tableHideOverride :: Maybe (WidgetCallback a)\n ,tableAsWindowOverride :: Maybe (GetWindowF a)\n ,tableAsGlWindowOverride :: Maybe (GetGlWindowF a)\n ,tableAsGroupOverride :: Maybe (GetGroupF a)\n ,tableDrawCellOverride :: Maybe (TableDrawCellF a)\n ,tableClearOverride :: Maybe (WidgetCallback a)\n ,tableSetRowsOverride :: Maybe (TableSetIntF a)\n ,tableSetColsOverride :: Maybe (TableSetIntF a)\n }\n\ntableFunctionStruct :: (TableFuncs a) -> IO (Ptr ())\ntableFunctionStruct funcs = do\n p <- mallocBytes {#sizeof fl_Table_Virtual_Funcs #}\n toCallbackPrim `orNullFunPtr` (tableDrawOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->draw#} p\n toEventHandlerPrim `orNullFunPtr` (tableHandleOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->handle#} p\n toRectangleFPrim `orNullFunPtr` (tableResizeOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->resize#} p\n toCallbackPrim `orNullFunPtr` (tableShowOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->show#} p\n toCallbackPrim `orNullFunPtr` (tableHideOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->hide#} p\n toGetWindowFPrim `orNullFunPtr` (tableAsWindowOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->as_window#} p\n toGetGlWindowFPrim `orNullFunPtr` (tableAsGlWindowOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->as_gl_window#} p\n toGetGroupFPrim `orNullFunPtr` (tableAsGroupOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->as_group#} p\n toTableDrawCellPrim `orNullFunPtr` (tableDrawCellOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->draw_cell#} p\n toCallbackPrim `orNullFunPtr` (tableClearOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->clear#} p\n toTableSetIntFPrim `orNullFunPtr` (tableSetRowsOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->set_rows#} p \n toTableSetIntFPrim `orNullFunPtr` (tableSetColsOverride funcs) >>=\n {#set fl_Table_Virtual_Funcs->set_cols#} p\n return p\ndefaultTableFuncs :: TableFuncs a\ndefaultTableFuncs = TableFuncs Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing\n{# fun Fl_Table_New as tableNew' { `Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_Table_New_WithLabel as tableNewWithLabel' { `Int',`Int',`Int',`Int',`String', id `Ptr ()'} -> `Ptr ()' id #}\ntableNew :: Rectangle -> Maybe String -> TableFuncs a -> IO (Table ())\ntableNew rectangle label' funcs' =\n do \n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n ptr <- tableFunctionStruct funcs'\n case label' of\n (Just l') -> tableNewWithLabel' x_pos y_pos width height l' (castPtr ptr) >>= toObject\n Nothing -> tableNew' x_pos y_pos width height (castPtr ptr) >>= toObject\n\n{# fun Fl_Table_Destroy as tableDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ntableDestroy :: Table a -> IO ()\ntableDestroy table = withObject table $ \\tablePtr -> tableDestroy' tablePtr\ntableHandle :: Table a -> Event -> IO Int\ntableHandle = groupHandle\ntableParent :: Table a -> IO (Group ())\ntableParent = groupParent\ntableSetParent :: Table a -> Group b -> IO ()\ntableSetParent = groupSetParent\ntableType_ :: Table a -> IO (Word8)\ntableType_ = groupType_\ntableSetType :: Table a -> Word8 -> IO (())\ntableSetType = groupSetType\ntableDrawLabel :: Table a -> Maybe (Rectangle,AlignType)-> IO (())\ntableDrawLabel = groupDrawLabel\ntableX :: Table a -> IO (Int)\ntableX = groupX\ntableY :: Table a -> IO (Int)\ntableY = groupY\ntableW :: Table a -> IO (Int)\ntableW = groupW\ntableH :: Table a -> IO (Int)\ntableH = groupH\ntableSetAlign :: Table a -> AlignType -> IO (())\ntableSetAlign = groupSetAlign\ntableAlign :: Table a -> IO (AlignType)\ntableAlign = groupAlign\ntableBox :: Table a -> IO (Boxtype)\ntableBox = groupBox\ntableSetBox :: Table a -> Boxtype -> IO (())\ntableSetBox = groupSetBox\ntableColor :: Table a -> IO (Color)\ntableColor = groupColor\ntableSetColor :: Table a -> Color -> IO (())\ntableSetColor = groupSetColor\ntableSetColorWithBgSel :: Table a -> Color -> Color -> IO (())\ntableSetColorWithBgSel = groupSetColorWithBgSel\ntableSelectionColor :: Table a -> IO (Color)\ntableSelectionColor = groupSelectionColor\ntableSetSelectionColor :: Table a -> Color -> IO (())\ntableSetSelectionColor = groupSetSelectionColor\ntableLabel :: Table a -> IO (String)\ntableLabel = groupLabel\ntableCopyLabel :: Table a -> String -> IO (())\ntableCopyLabel = groupCopyLabel\ntableSetLabel :: Table a -> String -> IO (())\ntableSetLabel = groupSetLabel\ntableLabeltype :: Table a -> IO (Labeltype)\ntableLabeltype = groupLabeltype\ntableSetLabeltype :: Table a -> Labeltype -> IO (())\ntableSetLabeltype = groupSetLabeltype\ntableLabelcolor :: Table a -> IO (Color)\ntableLabelcolor = groupLabelcolor\ntableSetLabelcolor :: Table a -> Color -> IO (())\ntableSetLabelcolor = groupSetLabelcolor\ntableLabelfont :: Table a -> IO (Font)\ntableLabelfont = groupLabelfont\ntableSetLabelfont :: Table a -> Font -> IO (())\ntableSetLabelfont = groupSetLabelfont\ntableLabelsize :: Table a -> IO (FontSize)\ntableLabelsize = groupLabelsize\ntableSetLabelsize :: Table a -> FontSize -> IO (())\ntableSetLabelsize = groupSetLabelsize\ntableImage :: Table a -> IO (Image ())\ntableImage = groupImage\ntableSetImage :: Table a -> Image b -> IO (())\ntableSetImage = groupSetImage\ntableDeimage :: Table a -> IO (Image ())\ntableDeimage = groupDeimage\ntableSetDeimage :: Table a -> Image b -> IO (())\ntableSetDeimage = groupSetDeimage\ntableTooltip :: Table a -> IO (String)\ntableTooltip = groupTooltip\ntableCopyTooltip :: Table a -> String -> IO (())\ntableCopyTooltip = groupCopyTooltip\ntableSetTooltip :: Table a -> String -> IO (())\ntableSetTooltip = groupSetTooltip\ntableWhen :: Table a -> IO (When)\ntableWhen = groupWhen\ntableSetWhen :: Table a -> Word8 -> IO (())\ntableSetWhen = groupSetWhen\ntableVisible :: Table a -> IO (Int)\ntableVisible = groupVisible\ntableVisibleR :: Table a -> IO (Int)\ntableVisibleR = groupVisibleR\ntableShow :: Table a -> IO (())\ntableShow = groupShow\ntableHide :: Table a -> IO (())\ntableHide = groupHide\ntableSetVisible :: Table a -> IO (())\ntableSetVisible = groupSetVisible\ntableClearVisible :: Table a -> IO (())\ntableClearVisible = groupClearVisible\ntableActive :: Table a -> IO (Int)\ntableActive = groupActive\ntableActiveR :: Table a -> IO (Int)\ntableActiveR = groupActiveR\ntableActivate :: Table a -> IO (())\ntableActivate = groupActivate\ntableDeactivate :: Table a -> IO (())\ntableDeactivate = groupDeactivate\ntableOutput :: Table a -> IO (Int)\ntableOutput = groupOutput\ntableSetOutput :: Table a -> IO (())\ntableSetOutput = groupSetOutput\ntableClearOutput :: Table a -> IO (())\ntableClearOutput = groupClearOutput\ntableTakesevents :: Table a -> IO (Int)\ntableTakesevents = groupTakesevents\ntableSetChanged :: Table a -> IO (())\ntableSetChanged = groupSetChanged\ntableClearChanged :: Table a -> IO (())\ntableClearChanged = groupClearChanged\ntableTakeFocus :: Table a -> IO (Int)\ntableTakeFocus = groupTakeFocus\ntableSetVisibleFocus :: Table a -> IO (())\ntableSetVisibleFocus = groupSetVisibleFocus\ntableClearVisibleFocus :: Table a -> IO (())\ntableClearVisibleFocus = groupClearVisibleFocus\ntableModifyVisibleFocus :: Table a -> Int -> IO (())\ntableModifyVisibleFocus = groupModifyVisibleFocus\ntableVisibleFocus :: Table a -> IO (Int)\ntableVisibleFocus = groupVisibleFocus\ntableContains :: Table a -> Group b -> IO (Int)\ntableContains = groupContains\ntableInside :: Table a -> Group b -> IO (Int)\ntableInside = groupInside\ntableRedraw :: Table a -> IO (())\ntableRedraw = groupRedraw\ntableRedrawLabel :: Table a -> IO (())\ntableRedrawLabel = groupRedrawLabel\ntableDamage :: Table a -> IO (Word8)\ntableDamage = groupDamage\ntableClearDamageWithBitmask :: Table a -> Word8 -> IO (())\ntableClearDamageWithBitmask = groupClearDamageWithBitmask\ntableClearDamage :: Table a -> IO (())\ntableClearDamage = groupClearDamage\ntableDamageWithText :: Table a -> Word8 -> IO (())\ntableDamageWithText = groupDamageWithText\ntableDamageInsideWidget :: Table a -> Word8 -> Rectangle -> IO (())\ntableDamageInsideWidget = groupDamageInsideWidget\ntableMeasureLabel :: Table a -> IO (Size)\ntableMeasureLabel = groupMeasureLabel\ntableWindow :: Table a -> IO (Window ())\ntableWindow = groupWindow\ntableTopWindow :: Table a -> IO (Window ())\ntableTopWindow = groupTopWindow\ntableTopWindowOffset :: Table a -> IO (Position)\ntableTopWindowOffset = groupTopWindowOffset\ntableAsGroup :: Table a -> IO (Group ())\ntableAsGroup = groupAsGroup\ntableAsGlWindow :: Table a -> IO (GlWindow ())\ntableAsGlWindow = groupAsGlWindow\ntableResize :: Table a -> Rectangle -> IO (())\ntableResize = groupResize\ntableSetCallback :: Table a -> (Group b -> IO ()) -> IO (())\ntableSetCallback = groupSetCallback\ntableRemoveIndex :: Table a -> Int -> IO (())\ntableRemoveIndex = groupRemoveIndex\ntableRemoveWidget :: Table b -> Widget a -> IO (())\ntableRemoveWidget = groupRemoveWidget\ntableClear :: Table a -> IO (())\ntableClear = groupClear\ntableSetResizable :: Table b -> Widget a -> IO (())\ntableSetResizable = groupSetResizable\ntableResizable :: Table a -> IO (Widget ())\ntableResizable = groupResizable\ntableAddResizable :: Table b -> Widget a -> IO (())\ntableAddResizable = groupAddResizable\ntableSetClipChildren :: Table a -> Int -> IO (())\ntableSetClipChildren = groupSetClipChildren\ntableClipChildren :: Table a -> IO (Int)\ntableClipChildren = groupClipChildren\ntableFocus :: Group b -> Widget a -> IO (())\ntableFocus = groupFocus\ntableDdfdesignKludge :: Table a -> IO (Widget ())\ntableDdfdesignKludge = groupDdfdesignKludge\ntableInsertWithBefore :: Group b -> Widget a -> Widget c -> IO (())\ntableInsertWithBefore = groupInsertWithBefore\n{# fun unsafe Fl_Table_set_table_box as setTableBox' { id `Ptr ()',cFromEnum `Boxtype' } -> `()' #}\ntableSetTableBox :: Table a -> Boxtype -> IO ()\ntableSetTableBox table val = withObject table $ \\tablePtr -> setTableBox' tablePtr val\n{# fun unsafe Fl_Table_table_box as tableBox' { id `Ptr ()' } -> `Boxtype' cToEnum #}\ntableTableBox :: Table a -> IO (Boxtype)\ntableTableBox table = withObject table $ \\tablePtr -> tableBox' tablePtr\n{# fun unsafe Fl_Table_set_rows_super as setRowsSuper' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowsSuper :: Table a -> Int -> IO ()\ntableSetRowsSuper table val = withObject table $ \\tablePtr -> setRowsSuper' tablePtr val\n{# fun unsafe Fl_Table_set_rows as setRows' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRows :: Table a -> Int -> IO ()\ntableSetRows table val = withObject table $ \\tablePtr -> setRows' tablePtr val\n{# fun unsafe Fl_Table_rows as rows' { id `Ptr ()' } -> `Int' #}\ntableRows :: Table a -> IO (Int)\ntableRows table = withObject table $ \\tablePtr -> rows' tablePtr\n{# fun unsafe Fl_Table_set_cols_super as setColsSuper' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColsSuper :: Table a -> Int -> IO ()\ntableSetColsSuper table val = withObject table $ \\tablePtr -> setColsSuper' tablePtr val\n{# fun unsafe Fl_Table_set_cols as setCols' { id `Ptr ()',`Int' } -> `()' #}\ntableSetCols :: Table a -> Int -> IO ()\ntableSetCols table val = withObject table $ \\tablePtr -> setCols' tablePtr val\n{# fun unsafe Fl_Table_cols as cols' { id `Ptr ()' } -> `Int' #}\ntableCols :: Table a -> IO (Int)\ntableCols table = withObject table $ \\tablePtr -> cols' tablePtr\n{# fun unsafe Fl_Table_set_visible_cells as setVisibleCells' { id `Ptr ()',id `Ptr CInt',id `Ptr CInt',id `Ptr CInt',id `Ptr CInt' } -> `()' #}\ntableSetVisibleCells :: Table a -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()\ntableSetVisibleCells table r1 r2 c1 c2 = withObject table $ \\tablePtr -> setVisibleCells' tablePtr r1 r2 c1 c2\n{# fun unsafe Fl_Table_is_interactive_resize as isInteractiveResize' { id `Ptr ()' } -> `Int' #}\ntableIsInteractiveResize :: Table a -> IO (Int)\ntableIsInteractiveResize table = withObject table $ \\tablePtr -> isInteractiveResize' tablePtr\n{# fun unsafe Fl_Table_row_resize as rowResize' { id `Ptr ()' } -> `Int' #}\ntableRowResize :: Table a -> IO (Int)\ntableRowResize table = withObject table $ \\tablePtr -> rowResize' tablePtr\n{# fun unsafe Fl_Table_set_row_resize as setRowResize' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowResize :: Table a -> Int -> IO ()\ntableSetRowResize table flag = withObject table $ \\tablePtr -> setRowResize' tablePtr flag\n{# fun unsafe Fl_Table_col_resize as colResize' { id `Ptr ()' } -> `Int' #}\ntableColResize :: Table a -> IO (Int)\ntableColResize table = withObject table $ \\tablePtr -> colResize' tablePtr\n{# fun unsafe Fl_Table_set_col_resize as setColResize' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColResize :: Table a -> Int -> IO ()\ntableSetColResize table flag = withObject table $ \\tablePtr -> setColResize' tablePtr flag\n{# fun unsafe Fl_Table_col_resize_min as colResizeMin' { id `Ptr ()' } -> `Int' #}\ntableColResizeMin :: Table a -> IO (Int)\ntableColResizeMin table = withObject table $ \\tablePtr -> colResizeMin' tablePtr\n{# fun unsafe Fl_Table_set_col_resize_min as setColResizeMin' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColResizeMin :: Table a -> Int -> IO ()\ntableSetColResizeMin table val = withObject table $ \\tablePtr -> setColResizeMin' tablePtr val\n{# fun unsafe Fl_Table_row_resize_min as rowResizeMin' { id `Ptr ()' } -> `Int' #}\ntableRowResizeMin :: Table a -> IO (Int)\ntableRowResizeMin table = withObject table $ \\tablePtr -> rowResizeMin' tablePtr\n{# fun unsafe Fl_Table_set_row_resize_min as setRowResizeMin' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowResizeMin :: Table a -> Int -> IO ()\ntableSetRowResizeMin table val = withObject table $ \\tablePtr -> setRowResizeMin' tablePtr val\n{# fun unsafe Fl_Table_row_header as rowHeader' { id `Ptr ()' } -> `Int' #}\ntableRowHeader :: Table a -> IO (Int)\ntableRowHeader table = withObject table $ \\tablePtr -> rowHeader' tablePtr\n{# fun unsafe Fl_Table_set_row_header as setRowHeader' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowHeader :: Table a -> Int -> IO ()\ntableSetRowHeader table flag = withObject table $ \\tablePtr -> setRowHeader' tablePtr flag\n{# fun unsafe Fl_Table_col_header as colHeader' { id `Ptr ()' } -> `Int' #}\ntableColHeader :: Table a -> IO (Int)\ntableColHeader table = withObject table $ \\tablePtr -> colHeader' tablePtr\n{# fun unsafe Fl_Table_set_col_header as setColHeader' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColHeader :: Table a -> Int -> IO ()\ntableSetColHeader table flag = withObject table $ \\tablePtr -> setColHeader' tablePtr flag\n{# fun unsafe Fl_Table_set_col_header_height as setColHeaderHeight' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColHeaderHeight :: Table a -> Int -> IO ()\ntableSetColHeaderHeight table height = withObject table $ \\tablePtr -> setColHeaderHeight' tablePtr height\n{# fun unsafe Fl_Table_col_header_height as colHeaderHeight' { id `Ptr ()' } -> `Int' #}\ntableColHeaderHeight :: Table a -> IO (Int)\ntableColHeaderHeight table = withObject table $ \\tablePtr -> colHeaderHeight' tablePtr\n{# fun unsafe Fl_Table_set_row_header_width as setRowHeaderWidth' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowHeaderWidth :: Table a -> Int -> IO ()\ntableSetRowHeaderWidth table width = withObject table $ \\tablePtr -> setRowHeaderWidth' tablePtr width\n{# fun unsafe Fl_Table_row_header_width as rowHeaderWidth' { id `Ptr ()' } -> `Int' #}\ntableRowHeaderWidth :: Table a -> IO (Int)\ntableRowHeaderWidth table = withObject table $ \\tablePtr -> rowHeaderWidth' tablePtr\n{# fun unsafe Fl_Table_set_row_header_color as setRowHeaderColor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ntableSetRowHeaderColor :: Table a -> Color -> IO ()\ntableSetRowHeaderColor table val = withObject table $ \\tablePtr -> setRowHeaderColor' tablePtr val\n{# fun unsafe Fl_Table_row_header_color as rowHeaderColor' { id `Ptr ()' } -> `Color' cToColor #}\ntableRowHeaderColor :: Table a -> IO (Color)\ntableRowHeaderColor table = withObject table $ \\tablePtr -> rowHeaderColor' tablePtr\n{# fun unsafe Fl_Table_set_col_header_color as setColHeaderColor' { id `Ptr ()',cFromColor `Color' } -> `()' #}\ntableSetColHeaderColor :: Table a -> Color -> IO ()\ntableSetColHeaderColor table val = withObject table $ \\tablePtr -> setColHeaderColor' tablePtr val\n{# fun unsafe Fl_Table_col_header_color as colHeaderColor' { id `Ptr ()' } -> `Color' cToColor #}\ntableColHeaderColor :: Table a -> IO (Color)\ntableColHeaderColor table = withObject table $ \\tablePtr -> colHeaderColor' tablePtr\n{# fun unsafe Fl_Table_set_row_height as setRowHeight' { id `Ptr ()',`Int',`Int' } -> `()' #}\ntableSetRowHeight :: Table a -> Int -> Int -> IO ()\ntableSetRowHeight table row height = withObject table $ \\tablePtr -> setRowHeight' tablePtr row height\n{# fun unsafe Fl_Table_row_height as rowHeight' { id `Ptr ()',`Int' } -> `Int' #}\ntableRowHeight :: Table a -> Int -> IO (Int)\ntableRowHeight table row = withObject table $ \\tablePtr -> rowHeight' tablePtr row\n{# fun unsafe Fl_Table_set_col_width as setColWidth' { id `Ptr ()',`Int',`Int' } -> `()' #}\ntableSetColWidth :: Table a -> Int -> Int -> IO ()\ntableSetColWidth table col width = withObject table $ \\tablePtr -> setColWidth' tablePtr col width\n{# fun unsafe Fl_Table_col_width as colWidth' { id `Ptr ()',`Int' } -> `Int' #}\ntableColWidth :: Table a -> Int -> IO (Int)\ntableColWidth table col = withObject table $ \\tablePtr -> colWidth' tablePtr col\n{# fun unsafe Fl_Table_set_row_height_all as setRowHeightAll' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowHeightAll :: Table a -> Int -> IO ()\ntableSetRowHeightAll table height = withObject table $ \\tablePtr -> setRowHeightAll' tablePtr height\n{# fun unsafe Fl_Table_set_col_width_all as setColWidthAll' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColWidthAll :: Table a -> Int -> IO ()\ntableSetColWidthAll table width = withObject table $ \\tablePtr -> setColWidthAll' tablePtr width\n{# fun unsafe Fl_Table_set_row_position as setRowPosition' { id `Ptr ()',`Int' } -> `()' #}\ntableSetRowPosition :: Table a -> Int -> IO ()\ntableSetRowPosition table row = withObject table $ \\tablePtr -> setRowPosition' tablePtr row\n{# fun unsafe Fl_Table_set_col_position as setColPosition' { id `Ptr ()',`Int' } -> `()' #}\ntableSetColPosition :: Table a -> Int -> IO ()\ntableSetColPosition table col = withObject table $ \\tablePtr -> setColPosition' tablePtr col\n{# fun unsafe Fl_Table_row_position as rowPosition' { id `Ptr ()' } -> `Int' #}\ntableRowPosition :: Table a -> IO (Int)\ntableRowPosition table = withObject table $ \\tablePtr -> rowPosition' tablePtr\n{# fun unsafe Fl_Table_col_position as colPosition' { id `Ptr ()' } -> `Int' #}\ntableColPosition :: Table a -> IO (Int)\ntableColPosition table = withObject table $ \\tablePtr -> colPosition' tablePtr\n{# fun unsafe Fl_Table_set_top_row as setTopRow' { id `Ptr ()',`Int' } -> `()' #}\ntableSetTopRow :: Table a -> Int -> IO ()\ntableSetTopRow table row = withObject table $ \\tablePtr -> setTopRow' tablePtr row\n{# fun unsafe Fl_Table_top_row as topRow' { id `Ptr ()' } -> `Int' #}\ntableTopRow :: Table a -> IO (Int)\ntableTopRow table = withObject table $ \\tablePtr -> topRow' tablePtr\n{# fun unsafe Fl_Table_is_selected as isSelected' { id `Ptr ()',`Int',`Int' } -> `Int' #}\ntableIsSelected :: Table a -> Int -> Int -> IO (Int)\ntableIsSelected table r c = withObject table $ \\tablePtr -> isSelected' tablePtr r c\n{# fun unsafe Fl_Table_get_selection as getSelection' { id `Ptr ()',alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' #}\ntableGetSelection :: Table a -> IO (Position, Position)\ntableGetSelection table = \n withObject table $ \\tablePtr -> \n getSelection' tablePtr >>= \\(rt, cl, rb, cr) -> \n return $ (Position (X rt) (Y cl), Position (X rb) (Y cr))\n{# fun unsafe Fl_Table_set_selection as setSelection' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' #}\ntableSetSelection :: Table a -> Int -> Int -> Int -> Int -> IO ()\ntableSetSelection table row_top col_left row_bot col_right = withObject table $ \\tablePtr -> setSelection' tablePtr row_top col_left row_bot col_right\n{# fun unsafe Fl_Table_move_cursor as moveCursor' { id `Ptr ()',`Int',`Int' } -> `Int' #}\ntableMoveCursor :: Table a -> Int -> Int -> IO (Int)\ntableMoveCursor table r c = withObject table $ \\tablePtr -> moveCursor' tablePtr r c\n{# fun unsafe Fl_Table_draw as draw' { id `Ptr ()' } -> `()' #}\ntableDraw :: Table a -> IO ()\ntableDraw table = withObject table $ \\tablePtr -> draw' tablePtr\n{# fun unsafe Fl_Table_init_sizes as initSizes' { id `Ptr ()' } -> `()' #}\ntableInitSizes :: Table a -> IO ()\ntableInitSizes table = withObject table $ \\tablePtr -> initSizes' tablePtr\n{# fun unsafe Fl_Table_add as add' { id `Ptr ()',id `Ptr ()' } -> `()' #}\ntableAdd :: Table a -> Widget a -> IO ()\ntableAdd table wgt = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> add' tablePtr wgtPtr\n{# fun unsafe Fl_Table_insert as insert' { id `Ptr ()',id `Ptr ()',`Int' } -> `()' #}\ntableInsert :: Table a -> Widget a -> Int -> IO ()\ntableInsert table wgt n = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> insert' tablePtr wgtPtr n\n{# fun unsafe Fl_Table_insert_with_widget as insertWithWidget' { id `Ptr ()',id `Ptr ()',id `Ptr ()' } -> `()' #}\ntableInsertWithWidget :: Table a -> Widget b -> Widget c -> IO ()\ntableInsertWithWidget table wgt w2 = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> withObject w2 $ \\w2Ptr -> insertWithWidget' tablePtr wgtPtr w2Ptr\n{# fun unsafe Fl_Table_begin as begin' { id `Ptr ()' } -> `()' #}\ntableBegin :: Table a -> IO ()\ntableBegin table = withObject table $ \\tablePtr -> begin' tablePtr\n{# fun unsafe Fl_Table_end as end' { id `Ptr ()' } -> `()' #}\ntableEnd :: Table a -> IO ()\ntableEnd table = withObject table $ \\tablePtr -> end' tablePtr\n{# fun unsafe Fl_Table_array as array' { id `Ptr ()' } -> `Ptr (Ptr ())' id #}\ntableArray :: Table a -> IO [Widget ()]\ntableArray table = withObject table $ \\tablePtr -> do\n childArrayPtr <- array' tablePtr\n numChildren <- tableChildren table\n arrayToObjects childArrayPtr numChildren\n{# fun unsafe Fl_Table_child as child' { id `Ptr ()',`Int' } -> `Ptr ()' id #}\ntableChild :: Table a -> Int -> IO (Widget ())\ntableChild table n = withObject table $ \\tablePtr -> child' tablePtr n >>= toObject\n{# fun unsafe Fl_Table_children as children' { id `Ptr ()' } -> `Int' #}\ntableChildren :: Table a -> IO (Int)\ntableChildren table = withObject table $ \\tablePtr -> children' tablePtr\n{# fun unsafe Fl_Table_find as find' { id `Ptr ()',id `Ptr ()' } -> `Int' #}\ntableFind :: Table a -> Widget a -> IO (Int)\ntableFind table wgt = withObject table $ \\tablePtr -> withObject wgt $ \\wgtPtr -> find' tablePtr wgtPtr\n{# fun unsafe Fl_Table_callback_row as callbackRow' { id `Ptr ()' } -> `Int' #}\ntableCallbackRow :: Table a -> IO (Int)\ntableCallbackRow table = withObject table $ \\tablePtr -> callbackRow' tablePtr\n{# fun unsafe Fl_Table_callback_col as callbackCol' { id `Ptr ()' } -> `Int' #}\ntableCallbackCol :: Table a -> IO (Int)\ntableCallbackCol table = withObject table $ \\tablePtr -> callbackCol' tablePtr\n{# fun unsafe Fl_Table_callback_context as callbackContext' { id `Ptr ()' } -> `TableContext' cToEnum #}\ntableCallbackContext :: Table a -> IO (TableContext)\ntableCallbackContext table = withObject table $ \\tablePtr -> callbackContext' tablePtr\n{# fun unsafe Fl_Table_do_callback as doCallback' { id `Ptr ()',cFromEnum `TableContext',`Int',`Int' } -> `()' #}\ntableDoCallback :: Table a -> TableContext -> Int -> Int -> IO ()\ntableDoCallback table tablecontext row col = withObject table $ \\tablePtr -> doCallback' tablePtr tablecontext row col\n{# fun unsafe Fl_Table_find_cell as findCell' { id `Ptr ()',cFromEnum `TableContext',`Int',`Int',alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv*,alloca- `Int' peekIntConv* } -> `CInt' id #}\ntableFindCell :: Table a -> TableContext -> Int -> Int -> IO (Maybe Rectangle)\ntableFindCell table context r c = \n withObject table $ \\tablePtr -> \n findCell' tablePtr context r c >>= \\(result, x_pos', y_pos', width', height') -> \n if (cToBool result)\n then return $ Just $ toRectangle (x_pos', y_pos', width', height')\n else return $ Nothing\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"8e18b82b0181356ef708e46cb9bdb0f0e5e7e533","subject":"Associate a type with the device ptr","message":"Associate a type with the device ptr\n\nIgnore-this: aea4b82116966ba594aa509fcb90fcc8\n\ndarcs-hash:20090721235227-115f9-7ff63e2895912b799e6e5d1f3f706daab39be3e1.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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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\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\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-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr a -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\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 -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = 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 = 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\nnewDevicePtr :: Ptr () -> IO (DevicePtr ())\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 ()))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr ptr\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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 (),Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr 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\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 (),Int64))\nmalloc3D = moduleErr \"malloc3D\" \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr () -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr ()' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr () -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr ()' ,\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 () -- ^ 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-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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":"ac80d47d402f053c68293961cb44bff562d169bb","subject":"remove debugging code","message":"remove debugging code\n","repos":"Philonous\/pontarius-gpg","old_file":"src\/Bindings.chs","new_file":"src\/Bindings.chs","new_contents":"-- | Bindings to GPGMe\n--\n-- partial bindings to gpgme\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE OverloadedStrings #-}\n\n#include \n#include \n\nmodule Bindings where\n\nimport Control.Applicative ((<$>), (<*>))\nimport qualified Control.Exception as Ex\nimport Data.Bits\nimport qualified Data.ByteString as BS\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Unsafe as BS\nimport Data.Data\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.Foreign as Text\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport System.Posix.IO\nimport System.Posix.Types\n\nfromEnum' :: (Enum a, Num b) => a -> b\nfromEnum' = fromIntegral . fromEnum\n\ntoEnum' :: (Enum c, Integral a) => a -> c\ntoEnum' = toEnum . fromIntegral\n\nfromFlags :: (Enum a, Num b, Data.Bits.Bits b) => [a] -> b\nfromFlags = foldr (.|.) 0 . map fromEnum'\n\ntoFlags :: (Data.Bits.Bits a, Eq a, Num a, Enum b, Bounded b) =>\n a\n -> [b]\ntoFlags x = filter (\\y -> let y' = fromEnum' y in x .&. y' \/= 0)\n [minBound..maxBound]\n\n{#context lib = \"gpgme\" prefix = \"gpgme\" #}\n\n{#pointer gpgme_ctx_t as Ctx foreign newtype#}\n\ninstance Show Ctx where\n show _ = \"\"\n\n{#enum gpgme_err_code_t as ErrorCode {underscoreToCase}\n with prefix = \"GPG\"\n deriving (Show) #}\n\n{#enum gpgme_err_source_t as ErrorSource {underscoreToCase}\n with prefix = \"GPG\"\n\n deriving (Show) #}\n\ndata Error = Error { errCode :: ErrorCode\n , errSource :: ErrorSource\n , errorString :: Text.Text\n } deriving (Show, Typeable )\n\nnoError :: Error\nnoError = Error ErrNoError ErrSourceUnknown \"\"\n\ninstance Ex.Exception Error\n\nthrowError :: CUInt -> IO ()\nthrowError e' = do\n mbe <- toError e'\n case mbe of\n Nothing -> return ()\n Just e -> Ex.throwIO e\n\n#c\ngpgme_err_code_t gpgme_err_code_uninlined (gpgme_error_t err);\ngpgme_err_source_t gpgme_err_source_uninlined (gpgme_error_t err);\n#endc\n\ntoError :: CUInt -> IO (Maybe Error)\ntoError err = case err of\n 0 -> return Nothing\n _ -> Just <$>\n (allocaBytes 256 $ \\buff -> do -- We hope that any error message will\n -- be less than 256 bytes long\n _ <- {#call strerror_r#} err buff 256\n Error <$> (toEnum . fromIntegral\n <$> {# call err_code_uninlined #} err)\n <*> (toEnum . fromIntegral\n <$> {# call err_source_uninlined #} err)\n <*> (Text.pack <$> peekCString buff))\n\ncheckVersion :: Maybe Text -> IO (Maybe Text)\ncheckVersion Nothing = Just . Text.pack <$>\n (peekCString =<< {#call check_version#} nullPtr)\ncheckVersion (Just txt) = withCString (Text.unpack txt) $ \\buf -> do\n _ <- {#call check_version#} buf\n return Nothing\n\n\n{#enum gpgme_protocol_t as Protocol {underscoreToCase} deriving (Show, Eq)#}\n-- gpgme_engine_check_version (gpgme_protocol_t protocol)\n\nforeign import ccall unsafe \"&gpgme_release\"\n releaseCtx :: FunPtr (Ptr Ctx -> IO ())\n\nmkContext :: Ptr (Ptr Ctx) -> IO Ctx\nmkContext p = do\n if p == nullPtr\n then Ex.throw (Ex.AssertionFailed \"nullPtr\")\n else fmap Ctx $ newForeignPtr releaseCtx . castPtr =<< peek p\n\n\n-- withCtx :: Ctx -> (Ptr Ctx -> IO t) -> IO t\n-- withCtx x f = withForeignPtr (fromCtx x) f\n\n{#fun new as ctxNew'\n {alloca- `Ctx' mkContext*}\n -> `()' throwError*- #}\n\n-- | Check that version constraint is satisfied and create a new context\nctxNew :: Maybe Text -> IO Ctx\nctxNew minVersion = do\n _ <- checkVersion minVersion\n ctxNew'\n\n\n{#enum validity_t as Validity {underscoreToCase} deriving (Show) #}\n{#enum attr_t as Attr {underscoreToCase} deriving (Show) #}\n\n------------------------------------\n-- Keys\n------------------------------------\n\n{#pointer gpgme_key_t as Key foreign newtype #}\n\nwithKeysArray :: [Key] -> (Ptr (Ptr Key) -> IO b) -> IO b\nwithKeysArray ks' f = withKeys ks' $ \\ksPtrs -> withArray0 nullPtr ksPtrs f\n where\n withKeys [] g = g []\n withKeys (k:ks) g = withKey k $ \\kPtr -> withKeys ks (g . (kPtr:))\n\nforeign import ccall \"gpgme.h &gpgme_key_unref\"\n unrefPtr :: FunPtr (Ptr Key -> IO ())\n\ngetKeys :: Ctx\n -> Bool -- ^ Only keys with secret\n -> IO [Key]\ngetKeys ctx secretOnly = withCtx ctx $ \\ctxPtr -> do\n _ <- {#call gpgme_op_keylist_start #} ctxPtr nullPtr (fromEnum' secretOnly)\n alloca $ takeKeys ctxPtr\n where\n takeKeys ctxPtr (buf :: Ptr (Ptr Key)) = do\n err <- toError =<< {#call gpgme_op_keylist_next#} ctxPtr buf\n case err of\n Nothing -> do\n keyPtr <- peek buf\n key <- newForeignPtr unrefPtr keyPtr\n (Key key :) <$> takeKeys ctxPtr buf\n Just e -> case errCode e of\n ErrEof -> return []\n _ -> error \"takeKeys\"\n\nreserved :: (Ptr a -> t) -> t\nreserved f = f nullPtr\n\nreserved0 :: Num a => (a -> t) -> t\nreserved0 f = f 0\n\n{#fun key_get_string_attr as ^\n { withKey* `Key'\n , fromEnum' `Attr'\n , reserved- `Ptr()'\n , `Int'\n } -> `Maybe BS.ByteString' toMaybeText* #}\n\n-------------------------------\n-- Data Buffers\n-------------------------------\n\nnewtype DataBuffer = DataBuffer {fromDataBuffer :: Ptr ()}\nmkDataBuffer :: Ptr (Ptr ()) -> IO DataBuffer\nmkDataBuffer = fmap DataBuffer . peek\n\nwithDataBuffer :: DataBuffer -> (Ptr () -> t) -> t\nwithDataBuffer (DataBuffer buf) f = f buf\n\ntoMaybeText :: Ptr CChar -> IO (Maybe BS.ByteString)\ntoMaybeText ptr = maybePeek BS.packCString ptr\n\nwithMaybeText :: Maybe Text -> (Ptr CChar -> IO a) -> IO a\nwithMaybeText Nothing = ($ nullPtr)\nwithMaybeText (Just txt) = withCString (Text.unpack txt)\n\n\n\n{#fun data_new as ^\n { alloca- `DataBuffer' mkDataBuffer* }\n -> `()' throwError*- #}\n\npeekInt :: (Storable a, Num b, Integral a) => Ptr a -> IO b\npeekInt = fmap fromIntegral . peek\n\n{#fun data_release_and_get_mem as ^\n { fromDataBuffer `DataBuffer'\n , alloca- `Int' peekInt*\n } -> `Ptr ()' castPtr #}\n\ngetDataBufferBytes :: DataBuffer -> IO BS.ByteString\ngetDataBufferBytes db = do\n (dt, len) <- dataReleaseAndGetMem db\n res <- if dt == nullPtr then return BS.empty\n else do\n bs <- BS.packCStringLen (castPtr dt, len)\n {#call free#} dt\n return bs\n return res\n\n{# fun gpgme_op_export_keys as opExportKeys\n { withCtx* `Ctx'\n , withKeysArray* `[Key]'\n , reserved0- `CUInt'\n , fromDataBuffer `DataBuffer'\n } -> `Error' throwError*- #}\n\ndata ImportStatus = ImportStatus { isFprint :: BS.ByteString\n , isResult :: Maybe Error\n , isStatus :: Int -- TODO: convert to flags\n } deriving (Show)\n\nimportKeyBuffer :: Ctx -> DataBuffer -> IO [ImportStatus]\nimportKeyBuffer ctx keyBuffer = withCtx ctx $ \\ctxPtr ->\n withDataBuffer keyBuffer $ \\keyPtr -> do\n throwError =<< {#call op_import#} ctxPtr keyPtr\n result <- {#call op_import_result #} ctxPtr\n walkImports =<< {#get import_result_t.imports#} result\n where\n walkImports p = if p == nullPtr\n then return []\n else do\n is <- ImportStatus <$> (BS.packCString\n =<< {#get import_status_t.fpr #} p)\n <*> (toError =<< {#get import_status_t.result #} p)\n <*> (fromIntegral <$> {#get import_status_t.status #} p)\n (is:) <$> (walkImports =<< {#get import_status_t.next #} p)\n\n\nimportKeys :: Ctx -> ByteString -> IO [ImportStatus]\nimportKeys ctx bs = withBSData bs $ importKeyBuffer ctx\n\nexportKeys :: Ctx -> [Key] -> IO BS.ByteString\nexportKeys ctx keys = withBSBuffer $ opExportKeys ctx keys\n\nunsafeUseAsCStringLen' :: Num t =>\n BS.ByteString\n -> ((Ptr CChar, t) -> IO a)\n -> IO a\nunsafeUseAsCStringLen' bs f =\n BS.unsafeUseAsCStringLen bs $ \\(bs', l) -> f (bs', fromIntegral l)\n\n{# fun data_new_from_mem as ^\n { alloca- `DataBuffer' mkDataBuffer*\n , unsafeUseAsCStringLen' * `BS.ByteString'&\n , fromEnum' `Bool'\n } -> `Error' throwError*- #}\n\n{# fun data_release as ^\n { withDataBuffer* `DataBuffer'} -> `()' #}\n\n{# fun set_armor as ^\n { withCtx* `Ctx'\n , fromEnum' `Bool'\n } -> `()' #}\n\nwithBSData :: BS.ByteString -> (DataBuffer -> IO c) -> IO c\nwithBSData bs =\n Ex.bracket (dataNewFromMem bs True)\n dataRelease\n\nwithBSBuffer :: (DataBuffer -> IO a) -> IO BS.ByteString\nwithBSBuffer f =\n Ex.bracketOnError dataNew\n dataRelease\n $ \\db -> do\n _ <- f db\n getDataBufferBytes db\n\n\n-----------------------------------\n-- Signing\n-----------------------------------\n\n{#fun signers_clear as ^\n {withCtx* `Ctx'} -> `()'#}\n\n{#fun signers_add as ^\n { withCtx* `Ctx'\n , withKey* `Key'\n } -> `()' throwError* #}\n\n{# enum sig_mode_t as SigMode {underscoreToCase}\n with prefix = \"GPGME\"\n deriving (Show) #}\n\n{#fun op_sign as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer'\n , withDataBuffer* `DataBuffer'\n , fromEnum' `SigMode'\n } -> `()' throwError*- #}\n-- exportKey\n\n-- | Sign a text using a private signing key from the GPG keychain\nsign :: Ctx\n -> BS.ByteString -- ^ Text to sign\n -> Key -- ^ Signing key to use\n -> SigMode -- ^ Signing mode\n -> IO BS.ByteString\nsign ctx plain key mode = withBSData plain $ \\plainData ->\n withBSBuffer $ \\outData -> (do\n signersClear ctx\n signersAdd ctx key\n opSign ctx plainData outData mode)\n `Ex.finally` signersClear ctx\n\n{# enum sigsum_t as SigSummary {underscoreToCase} deriving (Bounded, Show)#}\n{# enum sig_stat_t as SigStat {underscoreToCase} deriving (Bounded, Show)#}\n\n{#fun op_verify as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer' -- sig\n , withDataBuffer* `DataBuffer' -- signed-text\n , withDataBuffer* `DataBuffer' -- plain\n } -> `()' throwError*- #}\n\n\ndata VerifyResult = VerifyResult { summary :: [SigSummary]\n , fingerprint :: ByteString\n , status :: SigStat\n , timestamp :: Integer\n , expTimestamp :: Integer\n , wrongKeyUsage :: Bool\n , pkaTrust :: Int\n , chainModel :: Bool\n , validity :: Validity\n , validityReason :: ErrorCode\n } deriving Show\n\npeekVerifyResults :: Ptr () -> IO [VerifyResult]\npeekVerifyResults ptr | ptr == nullPtr = return []\n | otherwise = do\n summary <- toFlags <$> {#get gpgme_signature_t->summary#} ptr\n fingerprint <- BS.packCString =<<{# get gpgme_signature_t->fpr#} ptr\n status' <- gpgme_err_code_uninlined =<< {#get gpgme_signature_t->status#} ptr\n let status = case toEnum' status' of\n ErrNoError -> SigStatGood\n ErrBadSignature -> SigStatBad\n ErrNoPubkey -> SigStatNokey\n ErrNoData -> SigStatNosig\n ErrSigExpired -> SigStatGoodExp\n ErrKeyExpired -> SigStatGoodExpkey\n _ -> SigStatError\n timestamp <- fromIntegral <$> {#get gpgme_signature_t->timestamp#} ptr\n expTimestamp <- fromIntegral <$> {#get gpgme_signature_t->exp_timestamp#} ptr\n wrongKeyUsage <- toEnum' <$> {#get gpgme_signature_t->wrong_key_usage#} ptr\n pkaTrust <- fromIntegral <$> {#get gpgme_signature_t->pka_trust#} ptr\n chainModel <- toEnum' <$> {#get gpgme_signature_t->chain_model #} ptr\n validity <- toEnum' <$> {#get gpgme_signature_t->validity #} ptr\n validityReason <- toEnum' <$> {#get gpgme_signature_t->validity_reason#} ptr\n let res = VerifyResult { summary = summary\n , fingerprint = fingerprint\n , status = status\n , timestamp = timestamp\n , expTimestamp = expTimestamp\n , wrongKeyUsage = wrongKeyUsage\n , pkaTrust = pkaTrust\n , chainModel = chainModel\n , validity = validity\n , validityReason = validityReason\n }\n next <- {#get gpgme_signature_t->next #} ptr\n nextResult <- peekVerifyResults next\n return (res : nextResult)\n\nverifyResult :: Ctx -> IO [VerifyResult]\nverifyResult ctx = withCtx ctx $ \\ctxPtr -> do\n res <- {# call gpgme_op_verify_result #} ctxPtr\n peekVerifyResults =<< {#get verify_result_t->signatures#} res\n\n-- | Verify a signature created in 'SigModeDetach' mode\nverifyDetach :: Ctx\n -> BS.ByteString -- ^ The source text that the signature pertains to\n -> BS.ByteString -- ^ The signature\n -> IO [VerifyResult]\nverifyDetach ctx signedText sig = withBSData signedText $ \\stData ->\n withBSData sig $ \\sigData -> do\n opVerify ctx sigData stData (DataBuffer nullPtr)\n verifyResult ctx\n\n-- | Verify a signature created in 'SigModeNormal' or 'SigModeClear' mode\nverify :: Ctx\n -> BS.ByteString -- ^ Text and attached Signature\n -> IO ([VerifyResult], BS.ByteString) -- ^ result and extracted plain text\nverify ctx sig = withBSData sig $ \\sigData -> do\n plain <- withBSBuffer $ \\plainData ->\n opVerify ctx sigData (DataBuffer nullPtr) plainData\n res <- verifyResult ctx\n return (res, plain)\n\n--------------------------------\n-- Passphrases\n--------------------------------\n\n-- gpgme_error_t (*gpgme_passphrase_cb_t)(void *hook, const char *uid_hint, const char *passphrase_info, int prev_was_bad, int fd)\n\ntype PassphraseCallback = Ptr () -- ^ Hook\n -> Ptr CChar -- ^ Uid Hint\n -> Ptr CChar -- ^ passphrase info\n -> CInt -- ^ Was Bad?\n -> CInt -- ^ fd\n -> IO CUInt\n\nforeign import ccall \"wrapper\"\n mkPasswordCallback :: PassphraseCallback -> IO (FunPtr PassphraseCallback)\n\nsetPassphraseCallback :: Ctx\n -> (String -> String -> Bool -> IO String)\n -> IO ()\nsetPassphraseCallback ctx f = do\n let cbFun _ uidHint pInfo bad fd = do\n uidHintString <- peekCString uidHint\n pInfoString <- peekCString pInfo\n out <- f uidHintString pInfoString (bad == 0)\n _ <- fdWrite (Fd fd) (filter (\/= '\\n') out ++ \"\\n\" )\n return 0\n cb <- mkPasswordCallback cbFun\n withCtx ctx $ \\ctxPtr -> {# call set_passphrase_cb #} ctxPtr cb nullPtr\n\ndata Engine = Engine { engineProtocol :: Protocol\n , engineFilename :: Maybe String\n , engineHomeDir :: Maybe String\n , engineVersion :: Maybe String\n , engineReqVersion :: Maybe String\n } deriving (Show)\n\ngetEngines :: Ctx -> IO [Engine]\ngetEngines ctx = withCtx ctx $ \\ctxPtr -> do\n goEngines =<< {#call ctx_get_engine_info #} ctxPtr\n where\n goEngines this = if this == nullPtr\n then return []\n else do\n engine <- Engine <$> (toEnum' <$> {# get engine_info_t.protocol#} this)\n <*> (peekCSM =<< {#get engine_info_t.file_name#} this)\n <*> (peekCSM =<< {#get engine_info_t.home_dir#} this)\n <*> (peekCSM =<< {#get engine_info_t.version#} this)\n <*> (peekCSM =<< {#get engine_info_t.req_version#} this)\n next <- {# get gpgme_engine_info_t.next #} this\n (engine:) <$> goEngines next\n peekCSM cString = if cString == nullPtr\n then return Nothing\n else Just <$> peekCString cString\n\nsetEngine :: Ctx -> Engine -> IO ()\nsetEngine ctx eng = withCtx ctx $ \\ctxPtr->\n withMBCString (engineFilename eng) $ \\fNamePtr ->\n withMBCString (engineHomeDir eng) $ \\hDirPtr ->\n throwError =<< {#call ctx_set_engine_info #} ctxPtr\n (fromEnum' $ engineProtocol eng)\n fNamePtr\n hDirPtr\n where\n withMBCString Nothing f = f nullPtr\n withMBCString (Just str) f = withCString str f\n\n{# enum pinentry_mode_t as PinentryMode {underscoreToCase} #}\n\n{# fun set_pinentry_mode as ^\n { withCtx* `Ctx'\n , fromEnum' `PinentryMode'\n } -> `()' throwError*- #}\n\n-------------------------------------------\n-- Key Creation ---------------------------\n-------------------------------------------\ndata GenKeyResult = GenKeyResult { genKeyhasPrimary :: Bool\n , genKeyhasSubKey :: Bool\n , genKeyFingerprint :: Maybe BS.ByteString\n } deriving (Show)\n\ngenKey :: Ctx -> String -> IO GenKeyResult\ngenKey ctx params = withCtx ctx $ \\ctxPtr ->\n withCString params $ \\paramsPtr -> do\n throwError =<< {#call gpgme_op_genkey#} ctxPtr paramsPtr nullPtr nullPtr\n res <- {#call gpgme_op_genkey_result#} ctxPtr\n prim <- toEnum' <$> {#get gpgme_genkey_result_t.primary#} res\n sub <- toEnum' <$> {#get gpgme_genkey_result_t.sub#} res\n fprint <- maybePeek BS.packCString =<< {#get gpgme_genkey_result_t.fpr#} res\n return $ GenKeyResult prim sub fprint\n\n------------------------------------------\n-- Key Deletion --------------------------\n------------------------------------------\n\n{# fun gpgme_op_delete as deleteKey\n { withCtx* `Ctx'\n , withKey* `Key'\n , fromEnum' `Bool'\n } -> `()' throwError*- #}\n\n------------------------------------------\n-- Key Editing ---------------------------\n------------------------------------------\n\n-- gpgme_error_t (*gpgme_edit_cb_t) (void *handle, gpgme_status_code_t status, const char *args, int fd)\n\n{# enum gpgme_status_code_t as StatusCode {underscoreToCase} deriving (Show, Read, Eq, Data, Typeable, Bounded) #}\n\ntype EditCallback' = Ptr () -> CInt -> CString -> CInt -> IO CUInt\ntype EditCallback = StatusCode -> Text -> Fd -> IO Error\n\nforeign import ccall \"wrapper\"\n mkEditCallback :: EditCallback' -> IO (FunPtr EditCallback')\n\n#c\ngpgme_error_t gpgme_err_make_uninlined ( gpgme_err_source_t err_source\n , gpgme_err_code_t err_code);\n#endc\n\n{# fun gpgme_err_make_uninlined as mkError\n { fromEnum' `ErrorSource'\n , fromEnum' `ErrorCode'\n }\n -> `CUInt' id #}\n\neditKey :: Ctx -> Key -> EditCallback -> IO ByteString\neditKey ctx key callback = do\n let callback' _ scInt cStr fdInt = do\n str <- if (cStr == nullPtr) then return \"\" else peekCString cStr\n err <- callback (toEnum $ fromIntegral scInt) (Text.pack str)\n (Fd fdInt)\n mkError (errSource err) (errCode err)\n Ex.bracket (mkEditCallback callback') freeHaskellFunPtr\n $ \\cb ->\n withCtx ctx $ \\ctxPtr ->\n withKey key $ \\keyPtr ->\n withBSBuffer $ \\buffer ->\n withDataBuffer buffer $ \\bufferPtr ->\n throwError =<< {#call gpgme_op_edit#} ctxPtr keyPtr cb nullPtr bufferPtr\n\n-----------------------------------------\n-- Process ------------------------------\n-----------------------------------------\n\n{# fun kill as ^\n { fromIntegral `CPid'\n , fromIntegral `Int'\n } -> `Int' fromIntegral #}\n","old_contents":"-- | Bindings to GPGMe\n--\n-- partial bindings to gpgme\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE OverloadedStrings #-}\n\n#include \n#include \n\nmodule Bindings where\n\nimport Control.Applicative ((<$>), (<*>))\nimport qualified Control.Exception as Ex\nimport Data.Bits\nimport qualified Data.ByteString as BS\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString.Unsafe as BS\nimport Data.Data\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport qualified Data.Text.Foreign as Text\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport System.Posix.IO\nimport System.Posix.Types\n\nfromEnum' :: (Enum a, Num b) => a -> b\nfromEnum' = fromIntegral . fromEnum\n\ntoEnum' :: (Enum c, Integral a) => a -> c\ntoEnum' = toEnum . fromIntegral\n\nfromFlags :: (Enum a, Num b, Data.Bits.Bits b) => [a] -> b\nfromFlags = foldr (.|.) 0 . map fromEnum'\n\ntoFlags :: (Data.Bits.Bits a, Eq a, Num a, Enum b, Bounded b) =>\n a\n -> [b]\ntoFlags x = filter (\\y -> let y' = fromEnum' y in x .&. y' \/= 0)\n [minBound..maxBound]\n\n{#context lib = \"gpgme\" prefix = \"gpgme\" #}\n\n{#pointer gpgme_ctx_t as Ctx foreign newtype#}\n\ninstance Show Ctx where\n show _ = \"\"\n\n{#enum gpgme_err_code_t as ErrorCode {underscoreToCase}\n with prefix = \"GPG\"\n deriving (Show) #}\n\n{#enum gpgme_err_source_t as ErrorSource {underscoreToCase}\n with prefix = \"GPG\"\n\n deriving (Show) #}\n\ndata Error = Error { errCode :: ErrorCode\n , errSource :: ErrorSource\n , errorString :: Text.Text\n } deriving (Show, Typeable )\n\nnoError :: Error\nnoError = Error ErrNoError ErrSourceUnknown \"\"\n\ninstance Ex.Exception Error\n\nthrowError :: CUInt -> IO ()\nthrowError e' = do\n mbe <- toError e'\n case mbe of\n Nothing -> return ()\n Just e -> Ex.throwIO e\n\n#c\ngpgme_err_code_t gpgme_err_code_uninlined (gpgme_error_t err);\ngpgme_err_source_t gpgme_err_source_uninlined (gpgme_error_t err);\n#endc\n\ntoError :: CUInt -> IO (Maybe Error)\ntoError err = case err of\n 0 -> return Nothing\n _ -> Just <$>\n (allocaBytes 256 $ \\buff -> do -- We hope that any error message will\n -- be less than 256 bytes long\n _ <- {#call strerror_r#} err buff 256\n Error <$> (toEnum . fromIntegral\n <$> {# call err_code_uninlined #} err)\n <*> (toEnum . fromIntegral\n <$> {# call err_source_uninlined #} err)\n <*> (Text.pack <$> peekCString buff))\n\ncheckVersion :: Maybe Text -> IO (Maybe Text)\ncheckVersion Nothing = Just . Text.pack <$>\n (peekCString =<< {#call check_version#} nullPtr)\ncheckVersion (Just txt) = withCString (Text.unpack txt) $ \\buf -> do\n _ <- {#call check_version#} buf\n return Nothing\n\n\n{#enum gpgme_protocol_t as Protocol {underscoreToCase} deriving (Show, Eq)#}\n-- gpgme_engine_check_version (gpgme_protocol_t protocol)\n\nforeign import ccall unsafe \"&gpgme_release\"\n releaseCtx :: FunPtr (Ptr Ctx -> IO ())\n\nmkContext :: Ptr (Ptr Ctx) -> IO Ctx\nmkContext p = do\n if p == nullPtr\n then Ex.throw (Ex.AssertionFailed \"nullPtr\")\n else fmap Ctx $ newForeignPtr releaseCtx . castPtr =<< peek p\n\n\n-- withCtx :: Ctx -> (Ptr Ctx -> IO t) -> IO t\n-- withCtx x f = withForeignPtr (fromCtx x) f\n\n{#fun new as ctxNew'\n {alloca- `Ctx' mkContext*}\n -> `()' throwError*- #}\n\n-- | Check that version constraint is satisfied and create a new context\nctxNew :: Maybe Text -> IO Ctx\nctxNew minVersion = do\n _ <- checkVersion minVersion\n ctxNew'\n\n\n{#enum validity_t as Validity {underscoreToCase} deriving (Show) #}\n{#enum attr_t as Attr {underscoreToCase} deriving (Show) #}\n\n------------------------------------\n-- Keys\n------------------------------------\n\n{#pointer gpgme_key_t as Key foreign newtype #}\n\nwithKeysArray :: [Key] -> (Ptr (Ptr Key) -> IO b) -> IO b\nwithKeysArray ks' f = withKeys ks' $ \\ksPtrs -> withArray0 nullPtr ksPtrs f\n where\n withKeys [] g = g []\n withKeys (k:ks) g = withKey k $ \\kPtr -> withKeys ks (g . (kPtr:))\n\nforeign import ccall \"gpgme.h &gpgme_key_unref\"\n unrefPtr :: FunPtr (Ptr Key -> IO ())\n\ngetKeys :: Ctx\n -> Bool -- ^ Only keys with secret\n -> IO [Key]\ngetKeys ctx secretOnly = withCtx ctx $ \\ctxPtr -> do\n _ <- {#call gpgme_op_keylist_start #} ctxPtr nullPtr (fromEnum' secretOnly)\n alloca $ takeKeys ctxPtr\n where\n takeKeys ctxPtr (buf :: Ptr (Ptr Key)) = do\n err <- toError =<< {#call gpgme_op_keylist_next#} ctxPtr buf\n case err of\n Nothing -> do\n keyPtr <- peek buf\n key <- newForeignPtr unrefPtr keyPtr\n (Key key :) <$> takeKeys ctxPtr buf\n Just e -> case errCode e of\n ErrEof -> return []\n _ -> error \"takeKeys\"\n\nreserved :: (Ptr a -> t) -> t\nreserved f = f nullPtr\n\nreserved0 :: Num a => (a -> t) -> t\nreserved0 f = f 0\n\n{#fun key_get_string_attr as ^\n { withKey* `Key'\n , fromEnum' `Attr'\n , reserved- `Ptr()'\n , `Int'\n } -> `Maybe BS.ByteString' toMaybeText* #}\n\n-------------------------------\n-- Data Buffers\n-------------------------------\n\nnewtype DataBuffer = DataBuffer {fromDataBuffer :: Ptr ()}\nmkDataBuffer :: Ptr (Ptr ()) -> IO DataBuffer\nmkDataBuffer = fmap DataBuffer . peek\n\nwithDataBuffer :: DataBuffer -> (Ptr () -> t) -> t\nwithDataBuffer (DataBuffer buf) f = f buf\n\ntoMaybeText :: Ptr CChar -> IO (Maybe BS.ByteString)\ntoMaybeText ptr = maybePeek BS.packCString ptr\n\nwithMaybeText :: Maybe Text -> (Ptr CChar -> IO a) -> IO a\nwithMaybeText Nothing = ($ nullPtr)\nwithMaybeText (Just txt) = withCString (Text.unpack txt)\n\n\n\n{#fun data_new as ^\n { alloca- `DataBuffer' mkDataBuffer* }\n -> `()' throwError*- #}\n\npeekInt :: (Storable a, Num b, Integral a) => Ptr a -> IO b\npeekInt = fmap fromIntegral . peek\n\n{#fun data_release_and_get_mem as ^\n { fromDataBuffer `DataBuffer'\n , alloca- `Int' peekInt*\n } -> `Ptr ()' castPtr #}\n\ngetDataBufferBytes :: DataBuffer -> IO BS.ByteString\ngetDataBufferBytes db = do\n (dt, len) <- dataReleaseAndGetMem db\n res <- if dt == nullPtr then return BS.empty\n else do\n bs <- BS.packCStringLen (castPtr dt, len)\n {#call free#} dt\n return bs\n return res\n\n{# fun gpgme_op_export_keys as opExportKeys\n { withCtx* `Ctx'\n , withKeysArray* `[Key]'\n , reserved0- `CUInt'\n , fromDataBuffer `DataBuffer'\n } -> `Error' throwError*- #}\n\ndata ImportStatus = ImportStatus { isFprint :: BS.ByteString\n , isResult :: Maybe Error\n , isStatus :: Int -- TODO: convert to flags\n } deriving (Show)\n\nimportKeyBuffer :: Ctx -> DataBuffer -> IO [ImportStatus]\nimportKeyBuffer ctx keyBuffer = withCtx ctx $ \\ctxPtr ->\n withDataBuffer keyBuffer $ \\keyPtr -> do\n throwError =<< {#call op_import#} ctxPtr keyPtr\n result <- {#call op_import_result #} ctxPtr\n walkImports =<< {#get import_result_t.imports#} result\n where\n walkImports p = if p == nullPtr\n then return []\n else do\n is <- ImportStatus <$> (BS.packCString\n =<< {#get import_status_t.fpr #} p)\n <*> (toError =<< {#get import_status_t.result #} p)\n <*> (fromIntegral <$> {#get import_status_t.status #} p)\n (is:) <$> (walkImports =<< {#get import_status_t.next #} p)\n\n\nimportKeys :: Ctx -> ByteString -> IO [ImportStatus]\nimportKeys ctx bs = withBSData bs $ importKeyBuffer ctx\n\nexportKeys :: Ctx -> [Key] -> IO BS.ByteString\nexportKeys ctx keys = withBSBuffer $ opExportKeys ctx keys\n\nunsafeUseAsCStringLen' :: Num t =>\n BS.ByteString\n -> ((Ptr CChar, t) -> IO a)\n -> IO a\nunsafeUseAsCStringLen' bs f =\n BS.unsafeUseAsCStringLen bs $ \\(bs', l) -> f (bs', fromIntegral l)\n\n{# fun data_new_from_mem as ^\n { alloca- `DataBuffer' mkDataBuffer*\n , unsafeUseAsCStringLen' * `BS.ByteString'&\n , fromEnum' `Bool'\n } -> `Error' throwError*- #}\n\n{# fun data_release as ^\n { withDataBuffer* `DataBuffer'} -> `()' #}\n\n{# fun set_armor as ^\n { withCtx* `Ctx'\n , fromEnum' `Bool'\n } -> `()' #}\n\nwithBSData :: BS.ByteString -> (DataBuffer -> IO c) -> IO c\nwithBSData bs =\n Ex.bracket (dataNewFromMem bs True)\n dataRelease\n\nwithBSBuffer :: (DataBuffer -> IO a) -> IO BS.ByteString\nwithBSBuffer f =\n Ex.bracketOnError dataNew\n dataRelease\n $ \\db -> do\n _ <- f db\n getDataBufferBytes db\n\n\n-----------------------------------\n-- Signing\n-----------------------------------\n\n{#fun signers_clear as ^\n {withCtx* `Ctx'} -> `()'#}\n\n{#fun signers_add as ^\n { withCtx* `Ctx'\n , withKey* `Key'\n } -> `()' throwError* #}\n\n{# enum sig_mode_t as SigMode {underscoreToCase}\n with prefix = \"GPGME\"\n deriving (Show) #}\n\n{#fun op_sign as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer'\n , withDataBuffer* `DataBuffer'\n , fromEnum' `SigMode'\n } -> `()' throwError*- #}\n-- exportKey\n\n-- | Sign a text using a private signing key from the GPG keychain\nsign :: Ctx\n -> BS.ByteString -- ^ Text to sign\n -> Key -- ^ Signing key to use\n -> SigMode -- ^ Signing mode\n -> IO BS.ByteString\nsign ctx plain key mode = withBSData plain $ \\plainData ->\n withBSBuffer $ \\outData -> (do\n signersClear ctx\n signersAdd ctx key\n opSign ctx plainData outData mode)\n `Ex.finally` signersClear ctx\n\n{# enum sigsum_t as SigSummary {underscoreToCase} deriving (Bounded, Show)#}\n{# enum sig_stat_t as SigStat {underscoreToCase} deriving (Bounded, Show)#}\n\n{#fun op_verify as ^\n { withCtx* `Ctx'\n , withDataBuffer* `DataBuffer' -- sig\n , withDataBuffer* `DataBuffer' -- signed-text\n , withDataBuffer* `DataBuffer' -- plain\n } -> `()' throwError*- #}\n\n\ndata VerifyResult = VerifyResult { summary :: [SigSummary]\n , fingerprint :: ByteString\n , status :: SigStat\n , timestamp :: Integer\n , expTimestamp :: Integer\n , wrongKeyUsage :: Bool\n , pkaTrust :: Int\n , chainModel :: Bool\n , validity :: Validity\n , validityReason :: ErrorCode\n } deriving Show\n\npeekVerifyResults :: Ptr () -> IO [VerifyResult]\npeekVerifyResults ptr | ptr == nullPtr = return []\n | otherwise = do\n summary <- toFlags <$> {#get gpgme_signature_t->summary#} ptr\n fingerprint <- BS.packCString =<<{# get gpgme_signature_t->fpr#} ptr\n status' <- gpgme_err_code_uninlined =<< {#get gpgme_signature_t->status#} ptr\n let status = case toEnum' status' of\n ErrNoError -> SigStatGood\n ErrBadSignature -> SigStatBad\n ErrNoPubkey -> SigStatNokey\n ErrNoData -> SigStatNosig\n ErrSigExpired -> SigStatGoodExp\n ErrKeyExpired -> SigStatGoodExpkey\n _ -> SigStatError\n timestamp <- fromIntegral <$> {#get gpgme_signature_t->timestamp#} ptr\n expTimestamp <- fromIntegral <$> {#get gpgme_signature_t->exp_timestamp#} ptr\n wrongKeyUsage <- toEnum' <$> {#get gpgme_signature_t->wrong_key_usage#} ptr\n pkaTrust <- fromIntegral <$> {#get gpgme_signature_t->pka_trust#} ptr\n chainModel <- toEnum' <$> {#get gpgme_signature_t->chain_model #} ptr\n validity <- toEnum' <$> {#get gpgme_signature_t->validity #} ptr\n validityReason <- toEnum' <$> {#get gpgme_signature_t->validity_reason#} ptr\n let res = VerifyResult { summary = summary\n , fingerprint = fingerprint\n , status = status\n , timestamp = timestamp\n , expTimestamp = expTimestamp\n , wrongKeyUsage = wrongKeyUsage\n , pkaTrust = pkaTrust\n , chainModel = chainModel\n , validity = validity\n , validityReason = validityReason\n }\n next <- {#get gpgme_signature_t->next #} ptr\n nextResult <- peekVerifyResults next\n return (res : nextResult)\n\nverifyResult :: Ctx -> IO [VerifyResult]\nverifyResult ctx = withCtx ctx $ \\ctxPtr -> do\n res <- {# call gpgme_op_verify_result #} ctxPtr\n peekVerifyResults =<< {#get verify_result_t->signatures#} res\n\n-- | Verify a signature created in 'SigModeDetach' mode\nverifyDetach :: Ctx\n -> BS.ByteString -- ^ The source text that the signature pertains to\n -> BS.ByteString -- ^ The signature\n -> IO [VerifyResult]\nverifyDetach ctx signedText sig = withBSData signedText $ \\stData ->\n withBSData sig $ \\sigData -> do\n opVerify ctx sigData stData (DataBuffer nullPtr)\n verifyResult ctx\n\n-- | Verify a signature created in 'SigModeNormal' or 'SigModeClear' mode\nverify :: Ctx\n -> BS.ByteString -- ^ Text and attached Signature\n -> IO ([VerifyResult], BS.ByteString) -- ^ result and extracted plain text\nverify ctx sig = withBSData sig $ \\sigData -> do\n plain <- withBSBuffer $ \\plainData ->\n opVerify ctx sigData (DataBuffer nullPtr) plainData\n res <- verifyResult ctx\n return (res, plain)\n\n--------------------------------\n-- Passphrases\n--------------------------------\n\n-- gpgme_error_t (*gpgme_passphrase_cb_t)(void *hook, const char *uid_hint, const char *passphrase_info, int prev_was_bad, int fd)\n\ntype PassphraseCallback = Ptr () -- ^ Hook\n -> Ptr CChar -- ^ Uid Hint\n -> Ptr CChar -- ^ passphrase info\n -> CInt -- ^ Was Bad?\n -> CInt -- ^ fd\n -> IO CUInt\n\nforeign import ccall \"wrapper\"\n mkPasswordCallback :: PassphraseCallback -> IO (FunPtr PassphraseCallback)\n\nsetPassphraseCallback :: Ctx\n -> (String -> String -> Bool -> IO String)\n -> IO ()\nsetPassphraseCallback ctx f = do\n let cbFun _ uidHint pInfo bad fd = do\n uidHintString <- peekCString uidHint\n pInfoString <- peekCString pInfo\n out <- f uidHintString pInfoString (bad == 0)\n _ <- fdWrite (Fd fd) (filter (\/= '\\n') out ++ \"\\n\" )\n return 0\n cb <- mkPasswordCallback cbFun\n withCtx ctx $ \\ctxPtr -> {# call set_passphrase_cb #} ctxPtr cb nullPtr\n\ndata Engine = Engine { engineProtocol :: Protocol\n , engineFilename :: Maybe String\n , engineHomeDir :: Maybe String\n , engineVersion :: Maybe String\n , engineReqVersion :: Maybe String\n } deriving (Show)\n\ngetEngines :: Ctx -> IO [Engine]\ngetEngines ctx = withCtx ctx $ \\ctxPtr -> do\n goEngines =<< {#call ctx_get_engine_info #} ctxPtr\n where\n goEngines this = if this == nullPtr\n then return []\n else do\n engine <- Engine <$> (toEnum' <$> {# get engine_info_t.protocol#} this)\n <*> (peekCSM =<< {#get engine_info_t.file_name#} this)\n <*> (peekCSM =<< {#get engine_info_t.home_dir#} this)\n <*> (peekCSM =<< {#get engine_info_t.version#} this)\n <*> (peekCSM =<< {#get engine_info_t.req_version#} this)\n next <- {# get gpgme_engine_info_t.next #} this\n (engine:) <$> goEngines next\n peekCSM cString = if cString == nullPtr\n then return Nothing\n else Just <$> peekCString cString\n\nsetEngine :: Ctx -> Engine -> IO ()\nsetEngine ctx eng = withCtx ctx $ \\ctxPtr->\n withMBCString (engineFilename eng) $ \\fNamePtr ->\n withMBCString (engineHomeDir eng) $ \\hDirPtr ->\n throwError =<< {#call ctx_set_engine_info #} ctxPtr\n (fromEnum' $ engineProtocol eng)\n fNamePtr\n hDirPtr\n where\n withMBCString Nothing f = f nullPtr\n withMBCString (Just str) f = withCString str f\n\n{# enum pinentry_mode_t as PinentryMode {underscoreToCase} #}\n\n{# fun set_pinentry_mode as ^\n { withCtx* `Ctx'\n , fromEnum' `PinentryMode'\n } -> `()' throwError*- #}\n\n-------------------------------------------\n-- Key Creation ---------------------------\n-------------------------------------------\ndata GenKeyResult = GenKeyResult { genKeyhasPrimary :: Bool\n , genKeyhasSubKey :: Bool\n , genKeyFingerprint :: Maybe BS.ByteString\n } deriving (Show)\n\ngenKey :: Ctx -> String -> IO GenKeyResult\ngenKey ctx params = withCtx ctx $ \\ctxPtr ->\n withCString params $ \\paramsPtr -> do\n putStrLn \"starting key genearion\"\n throwError =<< {#call gpgme_op_genkey#} ctxPtr paramsPtr nullPtr nullPtr\n putStrLn \"retrieving result\"\n res <- {#call gpgme_op_genkey_result#} ctxPtr\n putStrLn \"Extracting result data\"\n prim <- toEnum' <$> {#get gpgme_genkey_result_t.primary#} res\n sub <- toEnum' <$> {#get gpgme_genkey_result_t.sub#} res\n fprint <- maybePeek BS.packCString =<< {#get gpgme_genkey_result_t.fpr#} res\n return $ GenKeyResult prim sub fprint\n\n------------------------------------------\n-- Key Deletion --------------------------\n------------------------------------------\n\n{# fun gpgme_op_delete as deleteKey\n { withCtx* `Ctx'\n , withKey* `Key'\n , fromEnum' `Bool'\n } -> `()' throwError*- #}\n\n------------------------------------------\n-- Key Editing ---------------------------\n------------------------------------------\n\n-- gpgme_error_t (*gpgme_edit_cb_t) (void *handle, gpgme_status_code_t status, const char *args, int fd)\n\n{# enum gpgme_status_code_t as StatusCode {underscoreToCase} deriving (Show, Read, Eq, Data, Typeable, Bounded) #}\n\ntype EditCallback' = Ptr () -> CInt -> CString -> CInt -> IO CUInt\ntype EditCallback = StatusCode -> Text -> Fd -> IO Error\n\nforeign import ccall \"wrapper\"\n mkEditCallback :: EditCallback' -> IO (FunPtr EditCallback')\n\n#c\ngpgme_error_t gpgme_err_make_uninlined ( gpgme_err_source_t err_source\n , gpgme_err_code_t err_code);\n#endc\n\n{# fun gpgme_err_make_uninlined as mkError\n { fromEnum' `ErrorSource'\n , fromEnum' `ErrorCode'\n }\n -> `CUInt' id #}\n\neditKey :: Ctx -> Key -> EditCallback -> IO ByteString\neditKey ctx key callback = do\n let callback' _ scInt cStr fdInt = do\n str <- if (cStr == nullPtr) then return \"\" else peekCString cStr\n err <- callback (toEnum $ fromIntegral scInt) (Text.pack str)\n (Fd fdInt)\n mkError (errSource err) (errCode err)\n Ex.bracket (mkEditCallback callback') freeHaskellFunPtr\n $ \\cb ->\n withCtx ctx $ \\ctxPtr ->\n withKey key $ \\keyPtr ->\n withBSBuffer $ \\buffer ->\n withDataBuffer buffer $ \\bufferPtr ->\n throwError =<< {#call gpgme_op_edit#} ctxPtr keyPtr cb nullPtr bufferPtr\n\n-----------------------------------------\n-- Process ------------------------------\n-----------------------------------------\n\n{# fun kill as ^\n { fromIntegral `CPid'\n , fromIntegral `Int'\n } -> `Int' fromIntegral #}\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"4169a78d5e9228b7cd60ef4a25192a791a867d70","subject":"Use 'SourceBufferClass buffer => buffer' replace 'SourceBuffer' as function argument.","message":"Use 'SourceBufferClass buffer => buffer' replace 'SourceBuffer' as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} \n (toSourceBuffer sb) \n (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} \n (toSourceBuffer sb)\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBufferClass buffer => buffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n (toSourceBuffer sb) \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} (toSourceBuffer sb)\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} (toSourceBuffer sb) (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} (toSourceBuffer sb)\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBufferClass buffer => buffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n (toSourceBuffer sb) \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} (toSourceBuffer sb)\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} (toSourceBuffer sb) (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} (toSourceBuffer sb)\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} (toSourceBuffer sb)\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} (toSourceBuffer sb)\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} (toSourceBuffer sb)\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} (toSourceBuffer sb)\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} (toSourceBuffer sb)\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} (toSourceBuffer sb)\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBufferClass buffer => buffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} (toSourceBuffer sb) strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n (toSourceBuffer buffer) \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n (toSourceBuffer buffer)\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBufferClass buffer => buffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} (toSourceBuffer sb) start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: SourceBufferClass buffer => Attr buffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: SourceBufferClass buffer => Attr buffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: SourceBufferClass buffer => Attr buffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: SourceBufferClass buffer => Signal buffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: SourceBufferClass buffer => Signal buffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBuffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n sb \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBuffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBuffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n sb \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBuffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBuffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBuffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBuffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n buffer \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n buffer\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n buffer\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBuffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n buffer\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBuffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: Signal SourceBuffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: Signal SourceBuffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: Signal SourceBuffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"581e0ccaf5656a77d03aeac68d6441f66c1c7eda","subject":"Fix bugs in contour commit (eb5091)","message":"Fix bugs in contour commit (eb5091)\n","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/ConnectedComponents.chs","new_file":"CV\/ConnectedComponents.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n-- | This module contains functions for extracting features from connected components\n-- of black and white images as well as extracting other shape related features. \nmodule CV.ConnectedComponents\n (\n -- * Working with connected components\n fillConnectedComponents\n ,maskConnectedComponent\n ,selectSizedComponents\n ,ContourMode(..)\n ,countBlobs\n -- * Working with Image moments\n -- |Note that these functions should probably go to a different module, since\n -- they deal with entire moments of entire images.\n ,spatialMoments\n ,centralMoments\n ,normalizedCentralMoments\n ,huMoments\n -- * Working with component contours aka. object boundaries.\n -- |This part is really old code and probably could be improved a lot.\n ,Contours\n ,ContourFunctionUS\n ,getContours\n ,contourArea\n ,contourPerimeter\n ,contourPoints\n ,mapContours\n ,contourHuMoments) \nwhere\n#include \"cvWrapLEO.h\"\n\nimport CV.Bindings.ImgProc\nimport CV.Bindings.Types\nimport Control.Monad ((>=>))\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Ptr\nimport Foreign.Storable\nimport System.IO.Unsafe\n{#import CV.Image#}\n\nimport CV.ImageOp\n\nfillConnectedComponents :: Image GrayScale D8 -> (Image GrayScale D8, Int)\nfillConnectedComponents image = unsafePerformIO $ do\n let\n count :: CInt\n count = 0\n withCloneValue image $ \\clone ->\n withImage clone $ \\pclone ->\n with count $ \\pcount -> do\n c'fillConnectedComponents (castPtr pclone) pcount\n c <- peek pcount\n return (clone, fromIntegral c)\n\nmaskConnectedComponent :: Image GrayScale D8 -> Int -> Image GrayScale D8\nmaskConnectedComponent image index = unsafePerformIO $\n withCloneValue image $ \\clone ->\n withImage image $ \\pimage ->\n withImage clone $ \\pclone -> do\n c'maskConnectedComponent (castPtr pimage) (castPtr pclone) (fromIntegral index)\n return clone\n\n-- |Count the number of connected components in the image\ncountBlobs :: Image GrayScale D8 -> Int \ncountBlobs image = fromIntegral $\u00a0unsafePerformIO $ do\n withGenImage image $ \\i ->\n {#call blobCount#} i\n\n-- |Remove all connected components that fall outside of given size range from the image.\nselectSizedComponents :: Double -> Double -> ContourMode -> Image GrayScale D8 -> Image GrayScale D8\nselectSizedComponents minSize maxSize mode image = unsafePerformIO $ do\n withGenImage image $ \\i ->\n creatingImage ({#call sizeFilter#} i (realToFrac minSize) (realToFrac maxSize) (fromIntegral $ fromEnum mode))\n\n#c\nenum ContourMode {\n ContourExternal = CV_RETR_EXTERNAL\n , ContourAll = CV_RETR_LIST\n , ContourBasicHeirarchy = CV_RETR_CCOMP\n , ContourFullHeirarchy = CV_RETR_TREE\n };\n#endc\n\n{#enum ContourMode {} #}\n\n-- * Working with Image moments. \n\n-- Utility function for getting the moments\ngetMoments :: (Ptr C'CvMoments -> CInt -> CInt -> IO (CDouble)) -> Image GrayScale D32 -> Bool -> [Double]\ngetMoments f image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments :: C'CvMoments\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n ms <- sequence [ f pmoments i j\n | i <- [0..3], j <- [0..3], i+j <= 3 ]\n return (map realToFrac ms)\n\n-- | Extract raw spatial moments of the image.\nspatialMoments = getMoments c'cvGetSpatialMoment\n\n-- | Extract central moments of the image. These are useful for describing the\n-- object shape for a classifier system.\ncentralMoments = getMoments c'cvGetCentralMoment\n\n-- | Extract normalized central moments of the image.\nnormalizedCentralMoments = getMoments c'cvGetNormalizedCentralMoment\n\n{-\ncentralMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n ms <- sequence [{#call cvGetCentralMoment#} moments i j\n | i <- [0..3], j<-[0..3], i+j <= 3]\n {#call freeCvMoments#} moments\n return (map realToFrac ms)\n-}\n\n-- |Extract Hu-moments of the image. These features are rotation invariant.\nhuMoments :: Image GrayScale D32 -> Bool -> [Double]\nhuMoments image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n hu = C'CvHuMoments 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n with hu $ \\phu -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n c'cvGetHuMoments pmoments phu\n (C'CvHuMoments hu1 hu2 hu3 hu4 hu5 hu6 hu7) <- peek phu\n return (map realToFrac [hu1,hu2,hu3,hu4,hu5,hu6,hu7])\n\n{-\nhuMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n hu <- readHu moments\n {#call freeCvMoments#} moments\n return (map realToFrac hu)\n-}\n\n-- read stuff out of hu-moments structure.. This could be done way better.\nreadHu m = do\n hu <- mallocArray 7\n {#call getHuMoments#} m hu\n hu' <- peekArray 7 hu\n free hu\n return hu'\n\n-- |Structure that contains the opencv sequence holding the contour data.\n{#pointer *FoundContours as Contours foreign newtype#}\nforeign import ccall \"& free_found_contours\" releaseContours \n :: FinalizerPtr Contours\n\n-- | This function maps an opencv contour calculation over all\n-- contours of the image. \nmapContours :: ContourFunctionUS a -> Contours -> [a]\nmapContours (CFUS op) contours = unsafePerformIO $ do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n-- |Extract contours of connected components of the image.\ngetContours :: Image GrayScale D8 -> Contours\ngetContours img = unsafePerformIO $ do\n withImage img $ \\i -> do\n ptr <- {#call get_contours#} i\n fptr <- newForeignPtr releaseContours ptr\n return $ Contours fptr \n\nnewtype ContourFunctionUS a = CFUS (Contours -> IO a)\nnewtype ContourFunctionIO a = CFIO (Contours -> IO a)\n\nrawContourOpUS op = CFUS $ \\c -> withContours c op\nrawContourOp op = CFIO $ \\c -> withContours c op\n\nprintContour = rawContourOp {#call print_contour#}\n\ncontourArea :: ContourFunctionUS Double\ncontourArea = rawContourOpUS ({#call contour_area#} >=> return.realToFrac)\n-- ^The area of a contour.\n\ncontourPerimeter :: ContourFunctionUS Double\ncontourPerimeter = rawContourOpUS $ {#call contour_perimeter#} >=> return.realToFrac\n-- ^Get the perimeter of a contour.\n\n-- |Get a list of the points in the contour.\ncontourPoints :: ContourFunctionUS [(Double,Double)]\ncontourPoints = rawContourOpUS getContourPoints'\ngetContourPoints' f = do\n count <- {#call cur_contour_size#} f\n let count' = fromIntegral count \n ----print count\n xs <- mallocArray count' \n ys <- mallocArray count'\n {#call contour_points#} f xs ys\n xs' <- peekArray count' xs\n ys' <- peekArray count' ys\n free xs\n free ys\n return $ zip (map fromIntegral xs') (map fromIntegral ys')\n\n-- |\u00a0Operation for extracting Hu-moments from a contour\ncontourHuMoments :: ContourFunctionUS [Double]\ncontourHuMoments = rawContourOpUS $ getContourHuMoments' >=> return.map realToFrac\ngetContourHuMoments' f = do\n m <- {#call contour_moments#} f \n hu <- readHu m \n {#call freeCvMoments#} m\n return hu\n\n\nmapContoursIO :: ContourFunctionIO a -> Contours -> IO [a]\nmapContoursIO (CFIO op) contours = do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n{#pointer *CvMoments as Moments foreign newtype#}\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n-- | This module contains functions for extracting features from connected components\n-- of black and white images as well as extracting other shape related features. \nmodule CV.ConnectedComponents\n (\n -- * Working with connected components\n fillConnectedComponents\n ,maskConnectedComponent\n ,selectSizedComponents\n ,contourMode\n ,countBlobs\n -- * Working with Image moments\n -- |Note that these functions should probably go to a different module, since\n -- they deal with entire moments of entire images.\n ,spatialMoments\n ,centralMoments\n ,normalizedCentralMoments\n ,huMoments\n -- * Working with component contours aka. object boundaries.\n -- |This part is really old code and probably could be improved a lot.\n ,Contours\n ,ContourFunctionUS\n ,getContours\n ,contourArea\n ,contourPerimeter\n ,contourPoints\n ,mapContours\n ,contourHuMoments) \nwhere\n#include \"cvWrapLEO.h\"\n\nimport CV.Bindings.ImgProc\nimport CV.Bindings.Types\nimport Control.Monad ((>=>))\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Ptr\nimport Foreign.Storable\nimport System.IO.Unsafe\n{#import CV.Image#}\n\nimport CV.ImageOp\n\nfillConnectedComponents :: Image GrayScale D8 -> (Image GrayScale D8, Int)\nfillConnectedComponents image = unsafePerformIO $ do\n let\n count :: CInt\n count = 0\n withCloneValue image $ \\clone ->\n withImage clone $ \\pclone ->\n with count $ \\pcount -> do\n c'fillConnectedComponents (castPtr pclone) pcount\n c <- peek pcount\n return (clone, fromIntegral c)\n\nmaskConnectedComponent :: Image GrayScale D8 -> Int -> Image GrayScale D8\nmaskConnectedComponent image index = unsafePerformIO $\n withCloneValue image $ \\clone ->\n withImage image $ \\pimage ->\n withImage clone $ \\pclone -> do\n c'maskConnectedComponent (castPtr pimage) (castPtr pclone) (fromIntegral index)\n return clone\n\n-- |Count the number of connected components in the image\ncountBlobs :: Image GrayScale D8 -> Int \ncountBlobs image = fromIntegral $\u00a0unsafePerformIO $ do\n withGenImage image $ \\i ->\n {#call blobCount#} i\n\n-- |Remove all connected components that fall outside of given size range from the image.\nselectSizedComponents :: Double -> Double -> ContourMode -> Image GrayScale D8 -> Image GrayScale D8\nselectSizedComponents minSize maxSize mode image = unsafePerformIO $ do\n withGenImage image $ \\i ->\n creatingImage ({#call sizeFilter#} i (realToFrac minSize) (realToFrac maxSize) (fromIntegral $ fromEnum mode))\n\n#c\nenum ContourMode {\n ContourExternal = CV_RETR_EXTERNAL\n , ContourAll = CV_RETR_LIST\n , ContourBasicHeirarchy = CV_RETR_CCOMP\n , ContourFullHeirarchy = CV_RETR_TREE\n };\n#endc\n\n{#enum ContourMode {} #}\n\n-- * Working with Image moments. \n\n-- Utility function for getting the moments\ngetMoments :: (Ptr C'CvMoments -> CInt -> CInt -> IO (CDouble)) -> Image GrayScale D32 -> Bool -> [Double]\ngetMoments f image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments :: C'CvMoments\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n ms <- sequence [ f pmoments i j\n | i <- [0..3], j <- [0..3], i+j <= 3 ]\n return (map realToFrac ms)\n\n-- | Extract raw spatial moments of the image.\nspatialMoments = getMoments c'cvGetSpatialMoment\n\n-- | Extract central moments of the image. These are useful for describing the\n-- object shape for a classifier system.\ncentralMoments = getMoments c'cvGetCentralMoment\n\n-- | Extract normalized central moments of the image.\nnormalizedCentralMoments = getMoments c'cvGetNormalizedCentralMoment\n\n{-\ncentralMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n ms <- sequence [{#call cvGetCentralMoment#} moments i j\n | i <- [0..3], j<-[0..3], i+j <= 3]\n {#call freeCvMoments#} moments\n return (map realToFrac ms)\n-}\n\n-- |Extract Hu-moments of the image. These features are rotation invariant.\nhuMoments :: Image GrayScale D32 -> Bool -> [Double]\nhuMoments image binary = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n moments = C'CvMoments 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n hu = C'CvHuMoments 0 0 0 0 0 0 0\n with moments $ \\pmoments -> do\n with hu $ \\phu -> do\n c'cvMoments (castPtr pimage) pmoments (if binary then 1 else 0)\n c'cvGetHuMoments pmoments phu\n (C'CvHuMoments hu1 hu2 hu3 hu4 hu5 hu6 hu7) <- peek phu\n return (map realToFrac [hu1,hu2,hu3,hu4,hu5,hu6,hu7])\n\n{-\nhuMoments image binary = unsafePerformIO $ do\n moments <- withImage image $ \\i -> {#call getMoments#} i (if binary then 1 else 0)\n hu <- readHu moments\n {#call freeCvMoments#} moments\n return (map realToFrac hu)\n-}\n\n-- read stuff out of hu-moments structure.. This could be done way better.\nreadHu m = do\n hu <- mallocArray 7\n {#call getHuMoments#} m hu\n hu' <- peekArray 7 hu\n free hu\n return hu'\n\n-- |Structure that contains the opencv sequence holding the contour data.\n{#pointer *FoundContours as Contours foreign newtype#}\nforeign import ccall \"& free_found_contours\" releaseContours \n :: FinalizerPtr Contours\n\n-- | This function maps an opencv contour calculation over all\n-- contours of the image. \nmapContours :: ContourFunctionUS a -> Contours -> [a]\nmapContours (CFUS op) contours = unsafePerformIO $ do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n-- |Extract contours of connected components of the image.\ngetContours :: Image GrayScale D8 -> Contours\ngetContours img = unsafePerformIO $ do\n withImage img $ \\i -> do\n ptr <- {#call get_contours#} i\n fptr <- newForeignPtr releaseContours ptr\n return $ Contours fptr \n\nnewtype ContourFunctionUS a = CFUS (Contours -> IO a)\nnewtype ContourFunctionIO a = CFIO (Contours -> IO a)\n\nrawContourOpUS op = CFUS $ \\c -> withContours c op\nrawContourOp op = CFIO $ \\c -> withContours c op\n\nprintContour = rawContourOp {#call print_contour#}\n\ncontourArea :: ContourFunctionUS Double\ncontourArea = rawContourOpUS ({#call contour_area#} >=> return.realToFrac)\n-- ^The area of a contour.\n\ncontourPerimeter :: ContourFunctionUS Double\ncontourPerimeter = rawContourOpUS $ {#call contour_perimeter#} >=> return.realToFrac\n-- ^Get the perimeter of a contour.\n\n-- |Get a list of the points in the contour.\ncontourPoints :: ContourFunctionUS [(Double,Double)]\ncontourPoints = rawContourOpUS getContourPoints'\ngetContourPoints' f = do\n count <- {#call cur_contour_size#} f\n let count' = fromIntegral count \n ----print count\n xs <- mallocArray count' \n ys <- mallocArray count'\n {#call contour_points#} f xs ys\n xs' <- peekArray count' xs\n ys' <- peekArray count' ys\n free xs\n free ys\n return $ zip (map fromIntegral xs') (map fromIntegral ys')\n\n-- |\u00a0Operation for extracting Hu-moments from a contour\ncontourHuMoments :: ContourFunctionUS [Double]\ncontourHuMoments = rawContourOpUS $ getContourHuMoments' >=> return.map realToFrac\ngetContourHuMoments' f = do\n m <- {#call contour_moments#} f \n hu <- readHu m \n {#call freeCvMoments#} m\n return hu\n\n\nmapContoursIO :: ContourFunctionIO a -> Contours -> IO [a]\nmapContoursIO (CFIO op) contours = do\n let loop acc cp = do\n more <- withContours cp {#call more_contours#}\n if more < 1 \n then return acc \n else do\n x <- op cp\n (i::CInt) <- withContours cp {#call next_contour#}\n loop (x:acc) cp\n \n acc <- loop [] contours\n withContours contours ({#call reset_contour#})\n return acc\n\n{#pointer *CvMoments as Moments foreign newtype#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"841053c442e71a4cdd5e8564a0db576af682e58f","subject":"Add bgraToGray8.","message":"Add bgraToGray8.\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, bgraTobgr8\n, bgrTobgra8\n, bgraToGray8\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 bgrTobgra8 <$> unsafeloadUsing imageTo8Bit 1 fp\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\nbgraToGray8 :: Image BGRA D8 -> Image GrayScale D8\nbgraToGray8 = S . convert8UTo BGR2GRAY 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\nbgraTobgr8 :: Image BGRA D8 -> Image BGR D8\nbgraTobgr8 = S . convert8UTo BGRA2BGR 3 . unS\n\nbgrTobgra8 :: Image BGR D8 -> Image BGRA D8\nbgrTobgra8 = 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\ninstance Blittable BGRA D8\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, 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, bgraTobgr8\n, bgrTobgra8\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 bgrTobgra8 <$> unsafeloadUsing imageTo8Bit 1 fp\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\nbgraTobgr8 :: Image BGRA D8 -> Image BGR D8\nbgraTobgr8 = S . convert8UTo BGRA2BGR 3 . unS\n\nbgrTobgra8 :: Image BGR D8 -> Image BGRA D8\nbgrTobgra8 = 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\ninstance Blittable BGRA D8\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":"03b9a71d9e466468eabd6c1d4679af19044612bc","subject":"gstreamer: document M.S.G.Core.Clock","message":"gstreamer: document M.S.G.Core.Clock\n\ndarcs-hash:20080116191205-21862-44e807359cb5252de1789258b300e107453b31b1.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-- | 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","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.Clock (\n \n Clock,\n ClockClass,\n castToClock,\n toClock,\n \n ClockTime,\n clockTimeNone,\n clockTimeIsValid,\n second,\n msecond,\n usecond,\n nsecond,\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID,\n \n ClockFlags(..),\n clockGetFlags,\n clockSetFlags,\n clockUnsetFlags,\n \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 clockTimeout,\n clockWindowSize,\n clockWindowThreshold\n \n ) where\n\nimport Data.Ratio ( Ratio\n , (%)\n , numerator\n , denominator )\nimport Control.Monad (liftM, 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\nclockGetFlags :: ClockClass clockT\n => clockT\n -> IO [ClockFlags]\nclockGetFlags = mkObjectGetFlags\n\nclockSetFlags :: ClockClass clockT\n => clockT\n -> [ClockFlags]\n -> IO ()\nclockSetFlags = mkObjectSetFlags\n\nclockUnsetFlags :: ClockClass clockT\n => clockT\n -> [ClockFlags]\n -> IO ()\nclockUnsetFlags = mkObjectUnsetFlags\n\nclockTimeIsValid :: ClockTime\n -> Bool\nclockTimeIsValid = (\/= clockTimeNone)\n\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\nclockSetMaster :: (ClockClass clock, ClockClass master)\n => clock\n -> master\n -> IO Bool\nclockSetMaster clock master =\n liftM toBool $ {# call clock_set_master #} (toClock clock) (toClock master)\n\nclockGetMaster :: ClockClass clock\n => clock\n -> IO (Maybe Clock)\nclockGetMaster clock =\n {# call clock_get_master #} (toClock clock) >>= maybePeek takeObject\n\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\nclockGetResolution :: ClockClass clock\n => clock\n -> IO ClockTime\nclockGetResolution clock =\n liftM fromIntegral $\n {# call clock_get_resolution #} (toClock clock)\n\nclockGetTime :: ClockClass clock\n => clock\n -> IO ClockTime\nclockGetTime clock =\n liftM fromIntegral $\n {# call clock_get_time #} (toClock clock)\n\nclockNewSingleShotID :: ClockClass clock\n => clock\n -> ClockTime\n -> IO ClockID\nclockNewSingleShotID clock time =\n {# call clock_new_single_shot_id #} (toClock clock)\n (fromIntegral time) >>=\n takeClockID . castPtr\n\nclockNewPeriodicID :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> IO ClockID\nclockNewPeriodicID clock startTime interval =\n {# call clock_new_periodic_id #} (toClock clock)\n (fromIntegral startTime)\n (fromIntegral interval) >>=\n takeClockID . castPtr\n\nclockGetInternalTime :: ClockClass clock\n => clock\n -> IO ClockTime\nclockGetInternalTime clock =\n liftM fromIntegral $\n {# call clock_get_internal_time #} (toClock clock)\n\nclockGetCalibration :: ClockClass clock\n => clock\n -> IO (ClockTime, ClockTime, Ratio ClockTime)\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\nclockSetCalibration :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> Ratio ClockTime\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\nclockIDGetTime :: ClockID\n -> IO ClockTime\nclockIDGetTime clockID =\n liftM fromIntegral $ withClockID clockID $\n {# call clock_id_get_time #} . castPtr\n\nclockIDWait :: ClockID\n -> IO (ClockReturn, ClockTimeDiff)\nclockIDWait clockID =\n alloca $ \\jitterPtr ->\n do result <- withClockID clockID $ \\clockIDPtr ->\n {# call clock_id_wait #} (castPtr clockIDPtr) jitterPtr\n jitter <- peek jitterPtr\n return $ (cToEnum result, fromIntegral jitter)\n\nclockIDUnschedule :: 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":"f9562d8adaf6534a8ec8676383463de8a6548f5e","subject":"Add support for constants of Float and Bool types","message":"Add support for constants of Float and Bool types\n","repos":"hamishmack\/haskell-gi-base,ford-prefect\/haskell-gi,hamishmack\/haskell-gi,ford-prefect\/haskell-gi,hamishmack\/haskell-gi","old_file":"GI\/Value.chs","new_file":"GI\/Value.chs","new_contents":"\nmodule GI.Value\n ( Value(..)\n , fromArgument\n , valueType\n ) where\n\nimport Control.Applicative ((<$>))\nimport Data.Int\nimport Data.Word\nimport Foreign (peekByteOff,Ptr)\nimport Foreign.C\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GI.Type\nimport GI.Internal.Types\n\n#include \n\ndata Value\n = VVoid\n | VBoolean Bool\n | VInt8 Int8\n | VUInt8 Word8\n | VInt16 Int16\n | VUInt16 Word16\n | VInt32 Int32\n | VUInt32 Word32\n | VInt64 Int64\n | VUInt64 Word64\n | VFloat Float\n | VDouble Double\n | VGType Word32\n | VUTF8 String\n | VFileName String\n deriving (Eq, Show)\n\nvalueType :: Value -> Type\nvalueType VVoid = TBasicType TVoid\nvalueType (VBoolean _) = TBasicType TBoolean\nvalueType (VInt8 _) = TBasicType TInt8\nvalueType (VUInt8 _) = TBasicType TUInt8\nvalueType (VInt16 _) = TBasicType TInt16\nvalueType (VUInt16 _) = TBasicType TUInt16\nvalueType (VInt32 _) = TBasicType TInt32\nvalueType (VUInt32 _) = TBasicType TUInt32\nvalueType (VInt64 _) = TBasicType TInt64\nvalueType (VUInt64 _) = TBasicType TUInt64\nvalueType (VFloat _) = TBasicType TFloat\nvalueType (VDouble _) = TBasicType TDouble\nvalueType (VGType _) = TBasicType TGType\nvalueType (VUTF8 _) = TBasicType TUTF8\nvalueType (VFileName _) = TBasicType TFileName\n\nfromArgument :: TypeInfo -> Argument -> Value\nfromArgument ti (Argument arg) =\n case typeFromTypeInfo ti of\n TBasicType t -> unsafePerformIO $ basic t\n t -> error $ \"don't know how to decode argument of type \" ++\n show t\n\n where\n\n basic TInt8 = VInt8 <$> fromIntegral <$> {# get GIArgument->v_int8 #} arg\n basic TUInt8 = VUInt8 <$> fromIntegral <$> {# get GIArgument->v_uint8 #} arg\n basic TInt16 = VInt16 <$> fromIntegral <$> {# get GIArgument->v_int16 #} arg\n basic TUInt16 = VUInt16 <$> fromIntegral <$> {# get GIArgument->v_uint16 #} arg\n basic TInt32 = VInt32 <$> fromIntegral <$> {# get GIArgument->v_int32 #} arg\n basic TUInt32 = VUInt32 <$> fromIntegral <$> {# get GIArgument->v_uint32 #} arg\n basic TInt64 = VInt64 <$> fromIntegral <$> {# get GIArgument->v_int64 #} arg\n basic TUInt64 = VUInt64 <$> fromIntegral <$> {# get GIArgument->v_uint64 #} arg\n basic TBoolean = VBoolean <$> (\/= 0) <$> {# get GIArgument->v_boolean #} arg\n -- XXX: Loss of precision?\n basic TFloat = VFloat <$> fromRational <$> toRational <$> {# get GIArgument->v_float #} arg\n -- XXX: Loss of precision?\n basic TDouble = VDouble <$> fromRational <$> toRational <$> {# get GIArgument->v_double #} arg\n basic TUTF8 = VUTF8 <$> (peekCString =<< {# get GIArgument->v_string #} arg)\n basic t = error $ \"a: implement me: \" ++ show t\n\n","old_contents":"\nmodule GI.Value\n ( Value(..)\n , fromArgument\n , valueType\n ) where\n\nimport Control.Applicative ((<$>))\nimport Data.Int\nimport Data.Word\nimport Foreign (peekByteOff,Ptr)\nimport Foreign.C\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GI.Type\nimport GI.Internal.Types\n\n#include \n\ndata Value\n = VVoid\n | VBoolean Bool\n | VInt8 Int8\n | VUInt8 Word8\n | VInt16 Int16\n | VUInt16 Word16\n | VInt32 Int32\n | VUInt32 Word32\n | VInt64 Int64\n | VUInt64 Word64\n | VFloat Float\n | VDouble Double\n | VGType Word32\n | VUTF8 String\n | VFileName String\n deriving (Eq, Show)\n\nvalueType :: Value -> Type\nvalueType VVoid = TBasicType TVoid\nvalueType (VBoolean _) = TBasicType TBoolean\nvalueType (VInt8 _) = TBasicType TInt8\nvalueType (VUInt8 _) = TBasicType TUInt8\nvalueType (VInt16 _) = TBasicType TInt16\nvalueType (VUInt16 _) = TBasicType TUInt16\nvalueType (VInt32 _) = TBasicType TInt32\nvalueType (VUInt32 _) = TBasicType TUInt32\nvalueType (VInt64 _) = TBasicType TInt64\nvalueType (VUInt64 _) = TBasicType TUInt64\nvalueType (VFloat _) = TBasicType TFloat\nvalueType (VDouble _) = TBasicType TDouble\nvalueType (VGType _) = TBasicType TGType\nvalueType (VUTF8 _) = TBasicType TUTF8\nvalueType (VFileName _) = TBasicType TFileName\n\nfromArgument :: TypeInfo -> Argument -> Value\nfromArgument ti (Argument arg) =\n case typeFromTypeInfo ti of\n TBasicType t -> unsafePerformIO $ basic t\n t -> error $ \"don't know how to decode argument of type \" ++\n show t\n\n where\n\n basic TInt8 = VInt8 <$> fromIntegral <$> {# get GIArgument->v_int8 #} arg\n basic TUInt8 = VUInt8 <$> fromIntegral <$> {# get GIArgument->v_uint8 #} arg\n basic TInt16 = VInt16 <$> fromIntegral <$> {# get GIArgument->v_int16 #} arg\n basic TUInt16 = VUInt16 <$> fromIntegral <$> {# get GIArgument->v_uint16 #} arg\n basic TInt32 = VInt32 <$> fromIntegral <$> {# get GIArgument->v_int32 #} arg\n basic TUInt32 = VUInt32 <$> fromIntegral <$> {# get GIArgument->v_uint32 #} arg\n basic TInt64 = VInt64 <$> fromIntegral <$> {# get GIArgument->v_int64 #} arg\n basic TUInt64 = VUInt64 <$> fromIntegral <$> {# get GIArgument->v_uint64 #} arg\n -- XXX: Loss of precision?\n basic TDouble = VDouble <$> fromRational <$> toRational <$> {# get GIArgument->v_double #} arg\n basic TUTF8 = VUTF8 <$> (peekCString =<< {# get GIArgument->v_string #} arg)\n basic t = error $ \"a: implement me: \" ++ show t\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"3c91aca064dbc015efc9bcf7c8755256cd1c891b","subject":"[project @ 2003-11-03 14:21:54 by juhp] Emacs file variables only work on the first line.","message":"[project @ 2003-11-03 14:21:54 by juhp]\nEmacs file variables only work on the first line.\n","repos":"vincenthz\/webkit","old_file":"gtk\/multiline\/TextIter.chs","new_file":"gtk\/multiline\/TextIter.chs","new_contents":"{-# OPTIONS -cpp #-} -- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter TextBuffer@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.11 $ from $Date: 2003\/11\/03 14:21:54 $\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-- @ref data 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 @ref data 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 FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (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 (text_iter_free iterPtr)\n\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall unsafe \">k_text_iter_free\"\n text_iter_free' :: FinalizerPtr TextIter\n\ntext_iter_free :: Ptr TextIter -> FinalizerPtr TextIter\ntext_iter_free _ = text_iter_free'\n\n#elif __GLASGOW_HASKELL__>=504\n\nforeign import ccall unsafe \"gtk_text_iter_free\"\n text_iter_free :: Ptr TextIter -> IO ()\n\n#else\n\nforeign import ccall \"gtk_text_iter_free\" unsafe\n text_iter_free :: Ptr TextIter -> IO ()\n\n#endif\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 (text_iter_free iterPtr)\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 (text_iter_free 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref data Pixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe Pixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (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-- @method textIterGetAttributes@ Get the text attributes at the iterator.\n--\n-- * The @ref arg ta@ argument gives the default values if no specific \n-- attributes are set at that specific location.\n--\n-- * The function returns @literal Nothing@ if the text at the iterator has \n-- the same attributes.\ntextIterGetAttributes = undefined\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\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall \"wrapper\" mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#else\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#endif\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 $ withUTFString 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 $ withUTFString 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":"{-# OPTIONS -cpp #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter TextBuffer@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.10 $ from $Date: 2003\/10\/21 21:28:53 $\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-- @ref data 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 @ref data 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 FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (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 (text_iter_free iterPtr)\n\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall unsafe \">k_text_iter_free\"\n text_iter_free' :: FinalizerPtr TextIter\n\ntext_iter_free :: Ptr TextIter -> FinalizerPtr TextIter\ntext_iter_free _ = text_iter_free'\n\n#elif __GLASGOW_HASKELL__>=504\n\nforeign import ccall unsafe \"gtk_text_iter_free\"\n text_iter_free :: Ptr TextIter -> IO ()\n\n#else\n\nforeign import ccall \"gtk_text_iter_free\" unsafe\n text_iter_free :: Ptr TextIter -> IO ()\n\n#endif\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 (text_iter_free iterPtr)\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 (text_iter_free 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref data Pixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe Pixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (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-- @method textIterGetAttributes@ Get the text attributes at the iterator.\n--\n-- * The @ref arg ta@ argument gives the default values if no specific \n-- attributes are set at that specific location.\n--\n-- * The function returns @literal Nothing@ if the text at the iterator has \n-- the same attributes.\ntextIterGetAttributes = undefined\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\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall \"wrapper\" mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#else\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#endif\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 $ withUTFString 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 $ withUTFString 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":"8ec9e10a8b7127c284d5f9b8323cdafbca280099","subject":"Make valueInit less conservative.","message":"Make valueInit less conservative.\n\ndarcs-hash:20060201212808-91c87-61bbb605c6855623d93cc3d11ea99eac64c70658.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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 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","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@(GValue gvPtr) gt = 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 {# 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":"cfcad874baeacf4c0cd7e595ac13ea1a43f2fee2","subject":"[project @ 2002-10-21 11:58:05 by as49]","message":"[project @ 2002-10-21 11:58:05 by as49]\n\nRemoved a pair of offending parentesis in signal grab_focus.\n\ndarcs-hash:20021021115805-d90cf-5a18987218c536dfc7a0edb568962eb218c306cc.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"7dfcac6256c90cc6d1421d71b8301cc1afd6f46d","subject":"Missing link","message":"Missing link","repos":"vincenthz\/webkit","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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and mainGUI then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"f3ba1d2290bb09413abe5ce264f1274f4aac35e8","subject":"Added TemplateMatching.matchShapes","message":"Added TemplateMatching.matchShapes","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/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-- TODO: Make this somehow smarter #PotentialDanger\ndata 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","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-- TODO: Make this somehow smarter #PotentialDanger\ndata 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"193c4c20ff7c8213855d81815f593b2c641cf1d3","subject":"Cleaned up description of the Matrix datatype.","message":"Cleaned up description of the Matrix datatype.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Matrix.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation.\n--\n-- The Matrix type represents a 2x2 transformation matrix along with a\n-- translation vector. @Matrix a1 a2 b1 b2 c1 c2@ describes the\n-- transformation of a point with coordinates x,y that is defined by\n--\n-- > \/ x' \\ = \/ a1 b1 \\ \/ x \\ + \/ c1 \\\n-- > \\ y' \/ \\ a2 b2 \/ \\ y \/ \\ c2 \/\n--\n-- or\n--\n-- > x' = a1 * x + b1 * y + c1\n-- > y' = a2 * x + b2 * y + c2\n\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Matrix\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-- Matrix math\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.Matrix (\n Matrix(Matrix)\n , MatrixPtr\n , identity\n , translate\n , scale\n , rotate\n , transformDistance\n , transformPoint\n , scalarMultiply\n , adjoint\n , invert\n ) where\n\nimport Foreign hiding (rotate)\nimport CForeign\n\n-- | Representation of a 2-D affine transformation as a matrix.\n--\n-- The 'Matrix' type actually represents as 3x3 matrix but with some elements\n-- are constant and so are not included. Specifically if we assume that our\n-- coordinates are row vectors then correspondence is:\n--\n-- > Matrix xx yx xy yy x0 y0\n-- > ==\n-- > \/ xx yx 0 \\\n-- > | xy yy 0 |\n-- > \\ x0 y0 1 \/\n--\n-- and the matrix operates on @(x,y)@ coordinates:\n--\n-- > (x y 1) \/ xx yx 0 \\ = (x' y' 1)\n-- > | xy yy 0 | where x' = xx * x + xy * y + x0\n-- > \\ x0 y0 1 \/ y' = yx * x + yy * y + y0\n--\ndata Matrix = Matrix { xx :: !Double, yx :: !Double,\n xy :: !Double, yy :: !Double,\n x0 :: !Double, y0 :: !Double }\n deriving (Show, Eq)\n\n{#pointer *cairo_matrix_t as MatrixPtr -> Matrix#}\n\ninstance Storable Matrix where\n sizeOf _ = {#sizeof cairo_matrix_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n xx <- {#get cairo_matrix_t->xx#} p\n yx <- {#get cairo_matrix_t->yx#} p\n xy <- {#get cairo_matrix_t->xy#} p\n yy <- {#get cairo_matrix_t->yy#} p\n x0 <- {#get cairo_matrix_t->x0#} p\n y0 <- {#get cairo_matrix_t->y0#} p\n return $ Matrix (realToFrac xx) (realToFrac yx)\n (realToFrac xy) (realToFrac yy)\n (realToFrac x0) (realToFrac y0)\n\n poke p (Matrix xx yx xy yy x0 y0) = do\n {#set cairo_matrix_t->xx#} p (realToFrac xx)\n {#set cairo_matrix_t->yx#} p (realToFrac yx)\n {#set cairo_matrix_t->xy#} p (realToFrac xy)\n {#set cairo_matrix_t->yy#} p (realToFrac yy)\n {#set cairo_matrix_t->x0#} p (realToFrac x0)\n {#set cairo_matrix_t->y0#} p (realToFrac y0)\n return ()\n\ninstance Num Matrix where\n (*) (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (xx * xx' + yx * xy')\n (xx * yx' + yx * yy')\n (xy * xx' + yy * xy')\n (xy * yx' + yy * yy')\n (x0 * xx' + y0 * xy' + x0')\n (x0 * yx' + y0 * yy' + y0')\n\n (+) = pointwise2 (+)\n (-) = pointwise2 (-)\n\n negate = pointwise negate\n abs = pointwise abs\n signum = pointwise signum\n\n -- this definition of fromInteger means that 2*m = scale 2 m\n -- and it means 1 = identity\n fromInteger n = Matrix (fromInteger n) 0 0 (fromInteger n) 0 0\n\n{-# INLINE pointwise #-}\npointwise f (Matrix xx yx xy yy x0 y0) =\n Matrix (f xx) (f yx) (f xy) (f yy) (f x0) (f y0)\n\n{-# INLINE pointwise2 #-}\npointwise2 f (Matrix xx yx xy yy x0 y0) (Matrix xx' yx' xy' yy' x0' y0') =\n Matrix (f xx xx') (f yx yx') (f xy xy') (f yy yy') (f x0 x0') (f y0 y0')\n\nidentity :: Matrix\nidentity = Matrix 1 0 0 1 0 0\n\ntranslate :: Double -> Double -> Matrix -> Matrix\ntranslate tx ty m = m * (Matrix 1 0 0 1 tx ty)\n\nscale :: Double -> Double -> Matrix -> Matrix\nscale sx sy m = m * (Matrix sx 0 0 sy 0 0)\n\nrotate :: Double -> Matrix -> Matrix\nrotate r m = m * (Matrix c s (-s) c 0 0)\n where s = sin r\n c = cos r\n\ntransformDistance :: Matrix -> (Double,Double) -> (Double,Double)\ntransformDistance (Matrix xx yx xy yy _ _) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy\n newY = yx * dx + yy * dy\n\ntransformPoint :: Matrix -> (Double,Double) -> (Double,Double)\ntransformPoint (Matrix xx yx xy yy x0 y0) (dx,dy) =\n newX `seq` newY `seq` (newX,newY)\n where newX = xx * dx + xy * dy + x0\n newY = yx * dx + yy * dy + y0\n\nscalarMultiply :: Double -> Matrix -> Matrix\nscalarMultiply scalar = pointwise (*scalar)\n\nadjoint :: Matrix -> Matrix\nadjoint (Matrix a b c d tx ty) =\n Matrix d (-b) (-c) a (c*ty - d*tx) (b*tx - a*ty)\n\ninvert :: Matrix -> Matrix\ninvert m@(Matrix xx yx xy yy _ _) = scalarMultiply (recip det) $ adjoint m\n where det = xx*yy - yx*xy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"2dc5a8904881df47bdf01385ebb6b315e1dab47d","subject":"A very minor haddock tweak in for callbacks.","message":"A very minor haddock tweak in for callbacks.\n\nIgnore-this: b867cabbda8b6bb0aa821421c40ba05c\n\ndarcs-hash:20090308135818-ed7c9-fb655fc018bb2b40193ed067d2c6b0d70aff17f1.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-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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(..), XMLParseError(..),\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 Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = do\n ok <- withHandlers parser $ doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\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 error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return True\n-- to continue parsing as normal, or False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return True to continue parsing as normal, or False to\n-- terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return True to continue\n-- parsing as normal, or False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","old_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n-- Copyright (C) 2009 Stephen Blackheath \n\n-- | A very low-level interface to Expat. Unless you need extreme speed, this\n-- should normally be avoided in favour of the interface provided by \"Text-XML-Expat-Tree\".\n-- 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(..), XMLParseError(..),\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 Control.Parallel.Strategies\nimport Control.Monad\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\ninstance Show Parser where\n showsPrec _ (Parser fp _ _ _) = showsPrec 0 fp\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\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. It returns Nothing on success, or Just the parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO (Maybe XMLParseError)\nparseChunk parser xml final = do\n ok <- withHandlers parser $ doParseChunk parser xml final\n if ok\n then return Nothing\n else Just `fmap` getError parser\n\ngetError parser = withParser parser $ \\p -> do\n code <- xmlGetErrorCode p\n cerr <- xmlErrorString code\n err <- peekCString cerr\n line <- xmlGetCurrentLineNumber p\n col <- xmlGetCurrentColumnNumber p\n return $ XMLParseError err\n (fromIntegral line) (fromIntegral col)\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 error, consisting of message text, line number, and column number\ndata XMLParseError = XMLParseError String Integer Integer deriving (Eq, Show)\n\ninstance NFData XMLParseError where\n rnf (XMLParseError msg lin col) = rnf (msg, lin, col)\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser. It returns Nothing\n-- on success, or Just the parse error.\nparse :: Parser -> BSL.ByteString -> IO (Maybe XMLParseError)\nparse parser@(Parser _ _ _ _) bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return Nothing\n feedChunk (c:cs) = do\n ok <- doParseChunk parser c (null cs)\n if ok\n then feedChunk cs\n else Just `fmap` getError parser\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs. Return False to terminate the parse.\ntype StartElementHandler = CString -> [(CString, CString)] -> IO Bool\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name. Return False to terminate the parse.\ntype EndElementHandler = CString -> IO Bool\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. Return False to terminate the parse.\ntype CharacterDataHandler = CStringLen -> IO Bool\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall unsafe \"expat.h XML_GetErrorCode\" xmlGetErrorCode\n :: ParserPtr -> IO CInt\nforeign import ccall unsafe \"expat.h XML_GetCurrentLineNumber\" xmlGetCurrentLineNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_GetCurrentColumnNumber\" xmlGetCurrentColumnNumber\n :: ParserPtr -> IO CUInt -- to do: Get 64-bit value if supported (how?)\nforeign import ccall unsafe \"expat.h XML_ErrorString\" xmlErrorString\n :: CInt -> IO CString\nforeign import ccall unsafe \"expat.h XML_StopParser\" xmlStopParser\n :: ParserPtr -> CInt -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\n\nwrapStartElementHandler :: Parser -> StartElementHandler -> CStartElementHandler\nwrapStartElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname cattrs = do\n cattrlist <- peekArray0 nullPtr cattrs\n stillRunning <- handler cname (pairwise cattrlist)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler =\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler parser handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: Parser -> EndElementHandler -> CEndElementHandler\nwrapEndElementHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cname = do\n stillRunning <- handler cname\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler =\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler parser handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall safe \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: Parser -> CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler parser@(Parser _ _ _ _) handler = h\n where\n h ptr cdata len = do\n stillRunning <- handler (cdata, fromIntegral len)\n unless stillRunning $\n withParser parser $ \\p -> xmlStopParser p 0 \n\n-- | Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler =\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler parser handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"fd23e0719e39052dcbc75925de517a8194d22f32","subject":"GDALType no longer needs to be Typeable","message":"GDALType no longer needs to be Typeable\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE ExistentialQuantification #-}\n\nmodule OSGeo.GDAL.Internal (\n GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , registerAllDrivers\n , destroyDriverManager\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 , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , withDataset\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..))\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\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)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown 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 GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset (t::DatasetMode) a = Dataset (ForeignPtr (Dataset t a), Mutex)\n\nunDataset :: Dataset a t -> ForeignPtr (Dataset a t)\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\n\nwithDataset :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunBand :: Band s a t -> Ptr (Band s a t)\nunBand (Band b) = b\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName s = do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall t. GDALType t\n => Driver -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate drv path nx ny bands options = do\n create' drv path nx ny bands (datatype (Proxy :: Proxy t)) options\n\ncreate'\n :: forall t. GDALType t\n => 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 d <- driverByName drv\n withOptionList options $ \\opts ->\n c_create d 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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: GDALType a => FilePath -> IO (RODataset a)\nopenReadOnly p = withCString p $ \\p' ->\n open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> IO (RWDataset a)\nopenReadWrite p = withCString p $ \\p' ->\n open_ p' (fromEnumC GA_Update) >>= newDatasetHandle >>= checkType\n\ncheckType :: forall t a. GDALType a => Dataset t a -> IO (Dataset t a)\ncheckType ds\n | datasetBandCount ds > 0 = withBand ds 1 $ \\b ->\n if datatype (Proxy :: Proxy a) == bandDatatype b\n then return ds\n else throw InvalidType\n | otherwise = return ds\n\n{-\ndata SomeDataset t = forall a. GDALType a => SomeDataset (Dataset t a)\n\nopenAnyReadOnly :: FilePath -> IO (SomeDataset ReadOnly)\nopenAnyReadOnly p = withCString p $ \\p' ->\n open_ p' (fromEnumC GA_ReadOnly) >>= (fmap SomeDataset . newDatasetHandle)\n\nopenAnyReadWrite :: FilePath -> IO (SomeDataset ReadWrite)\nopenAnyReadWrite p = withCString p $ \\p' ->\n open_ p' (fromEnumC GA_Update) >>= (fmap SomeDataset . newDatasetHandle)\n-}\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset t a) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset t a) -> Bool -> DriverOptions\n -> IO (RWDataset a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\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 :: GDALType a => Ptr (Dataset t a) -> IO (Dataset t a)\nnewDatasetHandle p =\n if p==nullPtr\n then throw NullDatasetHandle\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\n :: GDALType t\n => Int -> Int -> Int -> DriverOptions -> IO (Dataset ReadWrite 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 -> Int\ndatasetBandCount d\n = unsafePerformIO $ 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 -> (forall s. Band s 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 (InvalidBand band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band s a t))\n\n\nbandDatatype :: (Band s a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s 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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s a t) -> CInt\n\n\nbandNodataValue :: (Band s 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 s a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s 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 s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s 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 s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\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 (Proxy :: Proxy 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 s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\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 $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> IO (Vector a)\nreadBandBlock b x y = 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 s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector a -> IO ()\nwriteBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\nclass Storable a => GDALType a where\n datatype :: Proxy a -> Datatype\n\ninstance GDALType Word8 where datatype _ = GDT_Byte\ninstance GDALType Word16 where datatype _ = GDT_UInt16\ninstance GDALType Word32 where datatype _ = GDT_UInt32\ninstance GDALType Int16 where datatype _ = GDT_Int16\ninstance GDALType Int32 where datatype _ = GDT_Int32\ninstance GDALType Float where datatype _ = GDT_Float32\ninstance GDALType Double where datatype _ = GDT_Float64\ninstance GDALType (Complex Int16) where datatype _ = GDT_CInt16\ninstance GDALType (Complex Int32) where datatype _ = GDT_CInt32\ninstance GDALType (Complex Float) where datatype _ = GDT_CFloat32\ninstance GDALType (Complex Double) where datatype _ = GDT_CFloat64\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{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n\nmodule OSGeo.GDAL.Internal (\n GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , registerAllDrivers\n , destroyDriverManager\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 , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , withDataset\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..))\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown 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 GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype Dataset a t = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset :: Dataset a t -> ForeignPtr (Dataset a t)\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\n\nwithDataset :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s a t) = Band (Ptr (Band s a t))\n\nunBand :: Band s a t -> Ptr (Band s a t)\nunBand (Band b) = b\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName s = do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall t. GDALType t\n => Driver -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate drv path nx ny bands options = do\n create' drv path nx ny bands (datatype (Proxy :: Proxy t)) options\n\ncreate'\n :: forall t. GDALType t\n => 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 d <- driverByName drv\n withOptionList options $ \\opts ->\n c_create d 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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: GDALType a => FilePath -> IO (RODataset a)\nopenReadOnly p = withCString p $ \\p' ->\n open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle >>= checkType\n\nopenReadWrite :: GDALType a => FilePath -> IO (RWDataset a)\nopenReadWrite p = withCString p $ \\p' ->\n open_ p' (fromEnumC GA_Update) >>= newDatasetHandle >>= checkType\n\ncheckType :: forall t a. GDALType a => Dataset t a -> IO (Dataset t a)\ncheckType ds\n | datasetBandCount ds > 0 = withBand ds 1 $ \\b ->\n if isValidDatatype b (Proxy :: Proxy a)\n then return ds\n else throw InvalidType\n | otherwise = return ds\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 = do\n d <- driverByName driver\n withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n Driver -> FilePath -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\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 NullDatasetHandle\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\n :: GDALType t\n => Int -> Int -> Int -> DriverOptions -> IO (Dataset ReadWrite 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 -> Int\ndatasetBandCount d\n = unsafePerformIO $ 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 -> (forall s. Band s 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 (InvalidBand band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band s a t))\n\n\nbandDatatype :: (Band s a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s 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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s a t) -> CInt\n\n\nbandNodataValue :: (Band s 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 s a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s 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 s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s 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 s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t a)\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 (Proxy :: Proxy 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 s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall s a. GDALType a\n => (RWBand s a)\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 $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> IO (Vector a)\nreadBandBlock b x y = 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 s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector a -> IO ()\nwriteBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw InvalidBlockSize\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 s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\nclass (Storable a, Typeable a) => GDALType a where\n datatype :: Proxy a -> Datatype\n\ninstance GDALType Word8 where datatype _ = GDT_Byte\ninstance GDALType Word16 where datatype _ = GDT_UInt16\ninstance GDALType Word32 where datatype _ = GDT_UInt32\ninstance GDALType Int16 where datatype _ = GDT_Int16\ninstance GDALType Int32 where datatype _ = GDT_Int32\ninstance GDALType Float where datatype _ = GDT_Float32\ninstance GDALType Double where datatype _ = GDT_Float64\ninstance GDALType (Complex Int16) where datatype _ = GDT_CInt16\ninstance GDALType (Complex Int32) where datatype _ = GDT_CInt32\ninstance GDALType (Complex Float) where datatype _ = GDT_CFloat32\ninstance GDALType (Complex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall s a t v. Typeable v\n => Band s a t -> Proxy v -> Bool\nisValidDatatype b v\n = let vt = typeOf v\n in case bandDatatype b of\n GDT_Byte -> vt == typeOf (Proxy :: Proxy Word8)\n GDT_UInt16 -> vt == typeOf (Proxy :: Proxy Word16)\n GDT_UInt32 -> vt == typeOf (Proxy :: Proxy Word32)\n GDT_Int16 -> vt == typeOf (Proxy :: Proxy Int16)\n GDT_Int32 -> vt == typeOf (Proxy :: Proxy Int32)\n GDT_Float32 -> vt == typeOf (Proxy :: Proxy Float)\n GDT_Float64 -> vt == typeOf (Proxy :: Proxy Double)\n GDT_CInt16 -> vt == typeOf (Proxy :: Proxy (Complex Int16))\n GDT_CInt32 -> vt == typeOf (Proxy :: Proxy (Complex Int32))\n GDT_CFloat32 -> vt == typeOf (Proxy :: Proxy (Complex Float))\n GDT_CFloat64 -> vt == typeOf (Proxy :: Proxy (Complex Double))\n _ -> False\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"b3399671b3af80e5d5f6ae961720a04f04836691","subject":"add wrapPError","message":"add wrapPError\n","repos":"Delan90\/opencl,IFCA\/opencl,Delan90\/opencl,IFCA\/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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLImageFormat(..), CLPlatformInfo(..), CLMemFlag(..),\n -- * Functions\n clSuccess, wrapPError, getProfilingInfoValue, getImageFormat, \n getDeviceTypeValue, getDeviceLocalMemType, getDeviceMemCacheType, \n getCommandType, getCommandExecutionStatus, bitmaskToDeviceTypes, \n bitmaskFromDeviceTypes, bitmaskToCommandQueueProperties, bitmaskFromMemFlags,\n bitmaskFromCommandQueueProperties, bitmaskToFPConfig, bitmaskToExecCapability, \n getPlatformInfoValue )\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\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n CLBUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n CLCOMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n CLDEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n CLDEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n CLIMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n CLIMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n CLINVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n CLINVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n CLINVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n CLINVALID_BINARY=CL_INVALID_BINARY,\n CLINVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n CLINVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n CLINVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n CLINVALID_CONTEXT=CL_INVALID_CONTEXT,\n CLINVALID_DEVICE=CL_INVALID_DEVICE,\n CLINVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n CLINVALID_EVENT=CL_INVALID_EVENT,\n CLINVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n CLINVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n CLINVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n CLINVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n CLINVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n CLINVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n CLINVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n CLINVALID_KERNEL=CL_INVALID_KERNEL,\n CLINVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n CLINVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n CLINVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n CLINVALID_OPERATION=CL_INVALID_OPERATION,\n CLINVALID_PLATFORM=CL_INVALID_PLATFORM,\n CLINVALID_PROGRAM=CL_INVALID_PROGRAM,\n CLINVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n CLINVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n CLINVALID_SAMPLER=CL_INVALID_SAMPLER,\n CLINVALID_VALUE=CL_INVALID_VALUE,\n CLINVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n CLINVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n CLINVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n CLMAP_FAILURE=CL_MAP_FAILURE,\n CLMEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n CLMEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n CLOUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n CLOUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n CLPROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n CLSUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n* 'CLBUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CLCOMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CLDEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CLDEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CLIMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CLIMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CLINVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CLINVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CLINVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CLINVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CLINVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CLINVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CLINVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CLINVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CLINVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CLINVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CLINVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CLINVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CLINVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CLINVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CLINVALID_HOST_PTR', Returned if host_ptr is NULL and 'CLMEM_USE_HOST_PTR'\nor 'CLMEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CLMEM_COPY_HOST_PTR' or 'CLMEM_USE_HOST_PTR' are not set in flags.\n\n * 'CLINVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CLINVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CLINVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CLINVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CLINVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CLINVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CLINVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CLINVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CLINVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CLINVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CLINVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CLINVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CLINVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CLINVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CLINVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CLINVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CLINVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CLMAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CLMEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CLMEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CLOUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CLPROFILING_INFO_NOT_AVAILABLE', Returned if the 'CLQUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CLSUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {} deriving( Show, Eq ) #}\n\nwrapPError :: (Ptr CLint -> IO a) -> IO (Either CLError a)\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- peek perr >>= return . toEnum . fromIntegral\n if errcode == CLSUCCESS\n then return $ Right v\n else return $ Left errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} deriving( Show ) #}\n\ngetPlatformInfoValue :: CLPlatformInfo -> CLPlatformInfo_\ngetPlatformInfoValue = fromIntegral . fromEnum\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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-- -----------------------------------------------------------------------------\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-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n CLMEM_READ_WRITE=CL_MEM_READ_WRITE,\n CLMEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n CLMEM_READ_ONLY=CL_MEM_READ_ONLY,\n CLMEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n CLMEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n CLMEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n* 'CLMEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CLMEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CLMEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CLMEM_ALLOC_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CLMEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CLMEM_COPY_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually\nexclusive. 'CLMEM_COPY_HOST_PTR' can be used with 'CLMEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {} deriving( Show ) #}\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\nbitmaskFromMemFlags :: [CLMemFlag] -> CLMemFlags_\nbitmaskFromMemFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\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 -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n -- * High Level Types\n CLError(..), ErrorCode(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLImageFormat(..), CLPlatformInfo(..), CLMemFlag(..),\n -- * Functions\n clSuccess, getProfilingInfoValue, getImageFormat, getDeviceTypeValue, \n getDeviceLocalMemType, getDeviceMemCacheType, getCommandType, \n getCommandExecutionStatus, bitmaskToDeviceTypes, bitmaskFromDeviceTypes, \n bitmaskToCommandQueueProperties, bitmaskFromCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, getPlatformInfoValue )\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\n-- -----------------------------------------------------------------------------\nnewtype ErrorCode = ErrorCode CLint deriving( Eq )\n\nclSuccess :: ErrorCode\nclSuccess = ErrorCode (0)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n CLBUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n CLCOMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n CLDEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n CLDEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n CLIMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n CLIMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n CLINVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n CLINVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n CLINVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n CLINVALID_BINARY=CL_INVALID_BINARY,\n CLINVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n CLINVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n CLINVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n CLINVALID_CONTEXT=CL_INVALID_CONTEXT,\n CLINVALID_DEVICE=CL_INVALID_DEVICE,\n CLINVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n CLINVALID_EVENT=CL_INVALID_EVENT,\n CLINVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n CLINVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n CLINVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n CLINVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n CLINVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n CLINVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n CLINVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n CLINVALID_KERNEL=CL_INVALID_KERNEL,\n CLINVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n CLINVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n CLINVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n CLINVALID_OPERATION=CL_INVALID_OPERATION,\n CLINVALID_PLATFORM=CL_INVALID_PLATFORM,\n CLINVALID_PROGRAM=CL_INVALID_PROGRAM,\n CLINVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n CLINVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n CLINVALID_SAMPLER=CL_INVALID_SAMPLER,\n CLINVALID_VALUE=CL_INVALID_VALUE,\n CLINVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n CLINVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n CLINVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n CLMAP_FAILURE=CL_MAP_FAILURE,\n CLMEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n CLMEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n CLOUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n CLOUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n CLPROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n CLSUCCESS=CL_SUCCESS\n };\n#endc\n\n\n{-| \n* 'CLBUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CLCOMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CLDEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CLDEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CLIMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CLIMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CLINVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CLINVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CLINVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CLINVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CLINVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CLINVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CLINVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CLINVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CLINVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CLINVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CLINVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CLINVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CLINVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CLINVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CLINVALID_HOST_PTR', Returned if host_ptr is NULL and 'CLMEM_USE_HOST_PTR'\nor 'CLMEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CLMEM_COPY_HOST_PTR' or 'CLMEM_USE_HOST_PTR' are not set in flags.\n\n * 'CLINVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CLINVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CLINVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CLINVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CLINVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CLINVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CLINVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CLINVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CLINVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CLINVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CLINVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CLINVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CLINVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CLINVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CLINVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CLINVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CLINVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CLMAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CLMEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CLMEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CLOUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CLPROFILING_INFO_NOT_AVAILABLE', Returned if the 'CLQUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CLSUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\nCLPLATFORM_PROFILE=CL_PLATFORM_PROFILE,\nCLPLATFORM_VERSION=CL_PLATFORM_VERSION,\nCLPLATFORM_NAME=CL_PLATFORM_NAME,\nCLPLATFORM_VENDOR=CL_PLATFORM_VENDOR,\nCLPLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CLPLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CLPLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CLPLATFORM_NAME', Platform name string.\n \n * 'CLPLATFORM_VENDOR', Platform vendor string.\n \n * 'CLPLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {} deriving( Show ) #}\n\ngetPlatformInfoValue :: CLPlatformInfo -> CLPlatformInfo_\ngetPlatformInfoValue = fromIntegral . fromEnum\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 \nprocessor 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 \ndevice 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 \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral 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-- -----------------------------------------------------------------------------\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-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n CLMEM_READ_WRITE=CL_MEM_READ_WRITE,\n CLMEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n CLMEM_READ_ONLY=CL_MEM_READ_ONLY,\n CLMEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n CLMEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n CLMEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n* 'CLMEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CLMEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CLMEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CLMEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CLMEM_ALLOC_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CLMEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CLMEM_COPY_HOST_PTR' and 'CLMEM_USE_HOST_PTR' are mutually\nexclusive. 'CLMEM_COPY_HOST_PTR' can be used with 'CLMEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {} deriving( Show ) #}\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"83e9fc340c4344b7d1ca356e986e785e47ff48ca","subject":"Add withNewClient.","message":"Add withNewClient.\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\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\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 putStrLn \"clientWaitForInitialMetadata(..)\"\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 putStrLn (\"metadata: \" ++ show md)\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err -> do\n putStrLn \"clientWaitForInitialMetadata: callBatch failed\"\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n putStrLn \"clientReadInitialMetadata(..)\"\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n putStrLn \"clientRead(..)\"\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n putStrLn \"recvMessage(..)\"\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\nclientSendClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendClose 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\nsendClose :: Rpc req resp ()\nsendClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendClose 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","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 putStrLn \"clientWaitForInitialMetadata(..)\"\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 putStrLn (\"metadata: \" ++ show md)\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err -> do\n putStrLn \"clientWaitForInitialMetadata: callBatch failed\"\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n putStrLn \"clientReadInitialMetadata(..)\"\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n putStrLn \"clientRead(..)\"\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n putStrLn \"recvMessage(..)\"\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\nclientSendClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendClose 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\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\nsendClose :: Rpc req resp ()\nsendClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendClose 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":"2ec602c6c1b0fd6a9bc764e4c54a1429b9111ba3","subject":"Haddock wibble","message":"Haddock wibble\n","repos":"mwu-tow\/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 : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Utility functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Utils (driverVersion)\n where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\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--\n{-# INLINEABLE driverVersion #-}\ndriverVersion :: IO Int\ndriverVersion = resultIfOk =<< cuDriverGetVersion\n\n{-# INLINE cuDriverGetVersion #-}\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 : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Utility functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Utils (driverVersion)\n where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\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--\n{-# INLINEABLE driverVersion #-}\ndriverVersion :: IO Int\ndriverVersion = resultIfOk =<< cuDriverGetVersion\n\n{-# INLINE cuDriverGetVersion #-}\n{# fun unsafe cuDriverGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"aebd222108d0dd3e8464d77455f1bdfab5c037ff","subject":"slightly better error messages","message":"slightly better error messages\n\nIgnore-this: 3f84db1930247040095d1aba6715fe3b\n\ndarcs-hash:20090928090016-115f9-f16170f2165b30f45b405a30fd9d6db78fb9d4bb.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/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 withDevicePtrByteOff,\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 peekArrayElemOff,\n pokeArray,\n pokeArrayElemOff,\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-- Similar to `withDevicePtr', but with the address advanced by the given offset\n-- in bytes.\n--\nwithDevicePtrByteOff :: DevicePtr a -> Int -> (Ptr a -> IO b) -> IO b\nwithDevicePtrByteOff dptr offset action =\n withForeignPtr dptr $ \\p -> action (p `plusPtr` offset)\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 (moduleForceEither `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 = peekArrayElemOff 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--\npeekArrayElemOff :: Storable a => Int -> Int -> DevicePtr a -> IO (Either String [a])\npeekArrayElemOff 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 = pokeArrayElemOff 0\n\n\n-- |\n-- Store the list elements consecutively in device memory, beginning at the\n-- specified index (from zero)\n--\npokeArrayElemOff :: Storable a => Int -> DevicePtr a -> [a] -> IO (Maybe String)\npokeArrayElemOff 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 moduleForceEither `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 moduleForceEither `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\nmoduleForceEither :: Either String a -> a\nmoduleForceEither (Left s) = moduleErr \"Marshal\" s\nmoduleForceEither (Right r) = r\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 withDevicePtrByteOff,\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 peekArrayElemOff,\n pokeArray,\n pokeArrayElemOff,\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-- Similar to `withDevicePtr', but with the address advanced by the given offset\n-- in bytes.\n--\nwithDevicePtrByteOff :: DevicePtr a -> Int -> (Ptr a -> IO b) -> IO b\nwithDevicePtrByteOff dptr offset action =\n withForeignPtr dptr $ \\p -> action (p `plusPtr` offset)\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 = peekArrayElemOff 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--\npeekArrayElemOff :: Storable a => Int -> Int -> DevicePtr a -> IO (Either String [a])\npeekArrayElemOff 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 = pokeArrayElemOff 0\n\n\n-- |\n-- Store the list elements consecutively in device memory, beginning at the\n-- specified index (from zero)\n--\npokeArrayElemOff :: Storable a => Int -> DevicePtr a -> [a] -> IO (Maybe String)\npokeArrayElemOff 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"381bae4ff0631fb39c9723e88f65dc43fb6d3e02","subject":"Add pixbufRenderThresholdAlpha","message":"Add pixbufRenderThresholdAlpha\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/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":"70a47447712124f9ca040a3b4c529872658c9a16","subject":"part 2: stream module throws exceptions","message":"part 2: stream module throws exceptions\n\nIgnore-this: 2d920d6fb0630a8ccf1b47d88174c4eb\n\ndarcs-hash:20091219114334-dcabc-fd8ad61981ed372fb700a2abf90a9ad15054890b.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Stream.chs","new_file":"Foreign\/CUDA\/Runtime\/Stream.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Stream\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Stream management routines\n--\n--------------------------------------------------------------------------------\n\n\nmodule Foreign.CUDA.Runtime.Stream\n (\n Stream,\n\n -- ** Stream management\n create, destroy, finished, block\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\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A processing stream\n--\nnewtype Stream = Stream { useStream :: {# type cudaStream_t #}}\n deriving (Show)\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new asynchronous stream\n--\ncreate :: IO Stream\ncreate = resultIfOk =<< cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peekStream* } -> `Status' cToEnum #}\n where peekStream = liftM Stream . peekIntConv\n\n\n-- |\n-- Destroy and clean up an asynchronous stream\n--\ndestroy :: Stream -> IO ()\ndestroy s = nothingIfOk =<< cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Determine if all operations in a stream have completed\n--\nfinished :: Stream -> IO Bool\nfinished s =\n cudaStreamQuery s >>= \\rv -> do\n case rv of\n Success -> return True\n NotReady -> return False\n _ -> resultIfOk (rv,undefined)\n\n{# fun unsafe cudaStreamQuery\n { useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Block until all operations in a Stream have been completed\n--\nblock :: Stream -> IO ()\nblock s = nothingIfOk =<< cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { useStream `Stream' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Stream\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Stream management routines\n--\n--------------------------------------------------------------------------------\n\n\nmodule Foreign.CUDA.Runtime.Stream\n (\n Stream,\n\n -- ** Stream management\n create,\n destroy,\n finished,\n block\n )\n where\n\nimport Foreign\nimport Foreign.C\nimport Control.Monad\t\t\t(liftM)\n\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Stream = Stream { useStream :: {# type cudaStream_t #}}\n deriving (Show)\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new asynchronous stream\n--\ncreate :: IO (Either String Stream)\ncreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' stream* } -> `Status' cToEnum #}\n where stream = liftM Stream . peekIntConv\n\n\n-- |\n-- Destroy and clean up an asynchronous stream\n--\ndestroy :: Stream -> IO (Maybe String)\ndestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Determine if all operations in a stream have completed\n--\nfinished :: Stream -> IO (Either String Bool)\nfinished s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (describe rv)\n\n{# fun unsafe cudaStreamQuery\n { useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Block until all operations in a stream have been completed\n--\nblock :: Stream -> IO (Maybe String)\nblock s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { useStream `Stream' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9ddb24ed2651f82d7f46ac0c7062568d20df9646","subject":"combined temporary allocate and initialisation","message":"combined temporary allocate and initialisation\n\nIgnore-this: dc329df9df7eb4a5141a2080afbd42be\n\ndarcs-hash:20090911024416-115f9-d0a8d0cac3d593a51a5b8f09616b6d219878d2e4.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/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.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\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","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\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\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-- 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":"283e7b9463196439e42141bf85bed4ac7e33da45","subject":"glade: remove glade\/Glade.chs (not sure why this file is here...)","message":"glade: remove glade\/Glade.chs (not sure why this file is here...)\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"glade\/Glade.chs","new_file":"glade\/Glade.chs","new_contents":"","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to Libglade -*-haskell-*-\n-- for loading XML widget specifications\n--\n-- Author : Manuel M T Chakravarty\n-- Created: 13 March 2002\n--\n-- Copyright (c) 2002 Manuel M T Chakravarty\n-- Modified 2003 by Duncan Coutts (gtk2hs port)\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-- |\n--\n-- Libglade facilitates loading of XML specifications of whole widget trees\n-- that have been interactively designed with the GUI builder Glade. The\n-- present module exports operations for manipulating 'GladeXML' objects.\n--\n-- @glade_xml_signal_autoconnect()@ is not supported. The C variant is not\n-- suitable for Haskell as @-rdynamic@ leads to huge executable and we\n-- usually don't want to connect staticly named functions, but closures.\n--\n-- * @glade_xml_construct()@ is not bound, as it doesn't seem to be useful\n-- in Haskell. As usual, the @signal_connect_data@ variant for\n-- registering signal handlers isn't bound either. Moreover, the\n-- @connect_full@ functions are not bound.\n--\n-- * This binding does not support Libglade functionality that is\n-- exclusively meant for extending Libglade with new widgets. Like new\n-- widgets, such functionality is currently expected to be implemented in\n-- C.\n--\n\nmodule Glade (\n\n -- * Data types\n --\n GladeXMLClass, GladeXML,\n\n -- * Creation operations\n --\n xmlNew, xmlNewWithRootAndDomain,\n\n -- * Obtaining widget handles\n --\n xmlGetWidget, xmlGetWidgetRaw\n\n) where\n\nimport Monad\t(liftM)\nimport FFI\nimport GType\nimport Object (makeNewObject)\nimport GObject (makeNewGObject)\n{#import Hierarchy#}\n{#import GladeType#}\nimport GList\n\n{#context lib=\"glade\" prefix =\"glade\"#}\n\n\n-- | Create a new XML object (and the corresponding\n-- widgets) from the given XML file; corresponds to\n-- 'xmlNewWithRootAndDomain', but without the ability to specify a root\n-- widget or translation domain.\n--\nxmlNew :: FilePath -> IO (Maybe GladeXML)\nxmlNew file =\n withCString file $ \\strPtr1 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 nullPtr nullPtr\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Create a new GladeXML object (and\n-- the corresponding widgets) from the given XML file with an optional\n-- root widget and translation domain.\n--\n-- * If the second argument is not @Nothing@, the interface will only be built\n-- from the widget whose name is given. This feature is useful if you only\n-- want to build say a toolbar or menu from the XML file, but not the window\n-- it is embedded in. Note also that the XML parse tree is cached to speed\n-- up creating another \\'XML\\' object for the same file.\n--\nxmlNewWithRootAndDomain :: FilePath -> Maybe String -> Maybe String -> IO (Maybe GladeXML)\nxmlNewWithRootAndDomain file rootWidgetName domain =\n withCString file $ \\strPtr1 ->\n withMaybeCString rootWidgetName $ \\strPtr2 ->\n withMaybeCString domain $ \\strPtr3 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 strPtr2 strPtr3\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Get the widget that has the given name in\n-- the interface description. If the named widget cannot be found\n-- or is of the wrong type the result is an error.\n--\n-- * the second parameter should be a dynamic cast function that\n-- returns the type of object that you expect, eg castToButton\n--\n-- * the third parameter is the ID of the widget in the glade xml\n-- file, eg \\\"button1\\\".\n--\nxmlGetWidget :: (WidgetClass widget) => GladeXML -> (GObject -> widget) -> String -> IO widget\nxmlGetWidget xml cast name = do\n maybeWidget <- xmlGetWidgetRaw xml name\n return $ case maybeWidget of\n Just widget -> cast (toGObject widget) --the cast will return an error if the object is of the wrong type\n Nothing -> error $ \"glade.xmlGetWidget: no object named \" ++ show name ++ \" in the glade file\"\n\nxmlGetWidgetRaw :: GladeXML -> String -> IO (Maybe Widget)\nxmlGetWidgetRaw xml name =\n withCString name $ \\strPtr1 -> do\n widgetPtr <- {#call unsafe xml_get_widget#} xml strPtr1\n if widgetPtr==nullPtr then return Nothing\n else liftM Just $ makeNewObject mkWidget (return widgetPtr)\n\n-- Auxilliary routines\n-- -------------------\n\n-- Marshall an optional string\n--\nwithMaybeCString :: Maybe String -> (Ptr CChar -> IO a) -> IO a\nwithMaybeCString = maybeWith withCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9b5d2fd7caab412dbd20aee14b2a39630441e44b","subject":"Low-level metadata bindings","message":"Low-level metadata bindings\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\n--import Control.Applicative\nimport Control.Monad\nimport Data.Word\nimport Foreign\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\nimport System.Posix.IO\nimport System.Posix.Types\n\n#include \"rdkafka.h\"\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) #}\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_errno2err as ^\n {`Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\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 }\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 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\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 rdKafkaTopicPartitionListDestroy :: FunPtr (Ptr RdKafkaTopicPartitionListT -> IO ())\n\nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy 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 rdKafkaTopicPartitionListDestroy 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 -> Ptr Word8 -> 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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetRebalanceCb' c cb'\n return ()\n\n---- Delivery Callback\ntype DeliveryCallback = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> Word8Ptr -> 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 cb\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 -> Word8Ptr -> 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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetOffsetCommitCb' c cb'\n return ()\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---- Stats Callback\ntype StatsCallback = Ptr RdKafkaT -> CString -> CSize -> Word8Ptr -> 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 cb\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 rdKafkaQueueDestroy :: FunPtr (Ptr RdKafkaQueueT -> IO ())\n\nnewRdKafkaQueue :: RdKafkaTPtr -> IO RdKafkaQueueTPtr\nnewRdKafkaQueue k = do\n q <- rdKafkaQueueNew k\n addForeignPtrFinalizer rdKafkaQueueDestroy q\n return q\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', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaSubscription :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaSubscription k = alloca $ \\psPtr -> do\n err <- rdKafkaSubscription' k psPtr\n case err of\n RdKafkaRespErrNoError -> do\n lst <- peek psPtr >>= newForeignPtr rdKafkaTopicPartitionListDestroy\n return (Right lst)\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', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaAssignment :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaAssignment k = alloca $ \\psPtr -> do\n err <- rdKafkaAssignment' k psPtr\n case err of\n RdKafkaRespErrNoError -> do\n lst <- peek psPtr >>= newForeignPtr rdKafkaTopicPartitionListDestroy\n return (Right lst)\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 foreign -> RdKafkaGroupMemberInfoT #}\n\ndata RdKafkaGroupInfoT = RdKafkaGroupInfoT\n { broker'RdKafkaGroupInfoT :: Ptr RdKafkaMetadataBrokerT\n , group'RdKafkaGroupInfoT :: CString\n , err'RdKafkaGroupInfoT :: RdKafkaRespErrT\n , state'RdKafkaGroupInfoT :: CString\n , protocolType'RdKafkaGroupInfoT :: CString\n , protocol'RdKafkaGroupInfoT :: CString\n , members'RdKafkaGroupInfoT :: Ptr RdKafkaGroupMemberInfoT\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 ^\n {`RdKafkaTPtr', `String', castPtr `Ptr (Ptr RdKafkaGroupListT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_list_groups\"\n rdKafkaGroupListDestroy :: FunPtr (Ptr RdKafkaGroupListT -> IO ())\n\n-- listRdKafkaGroups :: RdKafkaTPtr -> String -> Int -> IO (Either RdKafkaRespErrT RdKafkaGroupListTPtr)\n-- listRdKafkaGroups k g t = alloca $ \\lstDblPtr -> do\n-- err <- rdKafkaListGroups k g lstDblPtr t\n-- case err of\n-- RdKafkaRespErrNoError -> do\n-- lstPtr <- peek lstDblPtr\n-- lst <- peek lstPtr\n-- addForeignPtrFinalizer rdKafkaGroupListDestroy lstPtr\n-- return $ Right lstPtr\n-- e -> return $ Left e\n-------------------------------------------------------------------------------------------------\n\n-- rd_kafka_message\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_message_destroy\"\n rdKafkaMessageDestroyF :: FunPtr (Ptr RdKafkaMessageT -> IO ())\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_message_destroy\"\n rdKafkaMessageDestroy :: Ptr RdKafkaMessageT -> IO ()\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 unsafe rd_kafka_message_timestamp as ^\n {`RdKafkaMessageTPtr', `RdKafkaTimestampTypeTPtr'} -> `CInt64T' cIntConv #}\n\n{#fun unsafe 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 :: FunPtr (Ptr RdKafkaConfT -> IO ())\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 :: FunPtr (Ptr RdKafkaTopicConfT -> IO ())\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 unsafe \"rdkafka.h &rd_kafka_destroy\"\n rdKafkaDestroy :: FunPtr (Ptr RdKafkaT -> IO ())\n\nnewRdKafkaT :: RdKafkaTypeT -> RdKafkaConfTPtr -> IO (Either String 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 peekCString charPtr >>= return . Left\n else do\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_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-- 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 `Word8Ptr'}\n -> `Int' #}\n\n{#fun rd_kafka_produce_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', `RdKafkaMessageTPtr', `Int'} -> `Int' #}\n\ncastMetadata :: Ptr (Ptr RdKafkaMetadataT) -> Ptr (Ptr ())\ncastMetadata ptr = castPtr ptr\n\n-- rd_kafka_metadata\n\n{#fun rd_kafka_metadata as rdKafkaMetadata'\n {`RdKafkaTPtr', boolToCInt `Bool', `RdKafkaTopicTPtr',\n castMetadata `Ptr (Ptr RdKafkaMetadataT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_metadata_destroy\"\n rdKafkaMetadataDestroy :: FunPtr (Ptr RdKafkaMetadataT -> IO ())\n\nrdKafkaMetadata :: RdKafkaTPtr -> Maybe RdKafkaTopicTPtr -> IO (Either RdKafkaRespErrT RdKafkaMetadataTPtr)\nrdKafkaMetadata k mt = alloca $ \\mptr -> do\n tptr <- maybe (newForeignPtr_ nullPtr) pure mt\n err <- rdKafkaMetadata' k True tptr mptr 0\n case err of\n RdKafkaRespErrNoError -> do\n meta <- peek mptr >>= newForeignPtr rdKafkaMetadataDestroy\n return (Right meta)\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\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' :: FunPtr (Ptr RdKafkaTopicT -> IO ())\n\nnewUnmanagedRdKafkaTopicT :: RdKafkaTPtr -> String -> RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewUnmanagedRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- 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 -> RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- rdKafkaTopicConfDup topicConfPtr\n ret <- rdKafkaTopicNew kafkaPtr topic duper\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then kafkaErrnoString >>= return . Left\n else do\n addForeignPtrFinalizer rdKafkaTopicDestroy' ret\n return $ Right ret\n\n-- Marshall \/ Unmarshall\nenumToCInt :: Enum a => a -> CInt\nenumToCInt = fromIntegral . fromEnum\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\nboolToCInt :: Bool -> CInt\nboolToCInt True = CInt 1\nboolToCInt False = CInt 0\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\n--import Control.Applicative\nimport Control.Monad\nimport Data.Word\nimport Foreign\nimport Foreign.C.Error\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO\nimport System.Posix.IO\nimport System.Posix.Types\n\n#include \"rdkafka.h\"\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) #}\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_errno2err as ^\n {`Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\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 }\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 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\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 rdKafkaTopicPartitionListDestroy :: FunPtr (Ptr RdKafkaTopicPartitionListT -> IO ())\n\nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroy 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 rdKafkaTopicPartitionListDestroy 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 -> Ptr Word8 -> 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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetRebalanceCb' c cb'\n return ()\n\n---- Delivery Callback\ntype DeliveryCallback = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> Word8Ptr -> 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 cb\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 -> Word8Ptr -> 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 o -> cb k (cIntToEnum e) p o)\n withForeignPtr conf $ \\c -> rdKafkaConfSetOffsetCommitCb' c cb'\n return ()\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---- Stats Callback\ntype StatsCallback = Ptr RdKafkaT -> CString -> CSize -> Word8Ptr -> 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 cb\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 rdKafkaQueueDestroy :: FunPtr (Ptr RdKafkaQueueT -> IO ())\n\nnewRdKafkaQueue :: RdKafkaTPtr -> IO RdKafkaQueueTPtr\nnewRdKafkaQueue k = do\n q <- rdKafkaQueueNew k\n addForeignPtrFinalizer rdKafkaQueueDestroy q\n return q\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', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaSubscription :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaSubscription k = alloca $ \\psPtr -> do\n err <- rdKafkaSubscription' k psPtr\n case err of\n RdKafkaRespErrNoError -> do\n lst <- peek psPtr >>= newForeignPtr rdKafkaTopicPartitionListDestroy\n return (Right lst)\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', castPtr `Ptr (Ptr RdKafkaTopicPartitionListT)'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaAssignment :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaAssignment k = alloca $ \\psPtr -> do\n err <- rdKafkaAssignment' k psPtr\n case err of\n RdKafkaRespErrNoError -> do\n lst <- peek psPtr >>= newForeignPtr rdKafkaTopicPartitionListDestroy\n return (Right lst)\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 foreign -> RdKafkaGroupMemberInfoT #}\n\ndata RdKafkaGroupInfoT = RdKafkaGroupInfoT\n { broker'RdKafkaGroupInfoT :: Ptr RdKafkaMetadataBrokerT\n , group'RdKafkaGroupInfoT :: CString\n , err'RdKafkaGroupInfoT :: RdKafkaRespErrT\n , state'RdKafkaGroupInfoT :: CString\n , protocolType'RdKafkaGroupInfoT :: CString\n , protocol'RdKafkaGroupInfoT :: CString\n , members'RdKafkaGroupInfoT :: Ptr RdKafkaGroupMemberInfoT\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 ^\n {`RdKafkaTPtr', `String', castPtr `Ptr (Ptr RdKafkaGroupListT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_list_groups\"\n rdKafkaGroupListDestroy :: FunPtr (Ptr RdKafkaGroupListT -> IO ())\n\n-- listRdKafkaGroups :: RdKafkaTPtr -> String -> Int -> IO (Either RdKafkaRespErrT RdKafkaGroupListTPtr)\n-- listRdKafkaGroups k g t = alloca $ \\lstDblPtr -> do\n-- err <- rdKafkaListGroups k g lstDblPtr t\n-- case err of\n-- RdKafkaRespErrNoError -> do\n-- lstPtr <- peek lstDblPtr\n-- lst <- peek lstPtr\n-- addForeignPtrFinalizer rdKafkaGroupListDestroy lstPtr\n-- return $ Right lstPtr\n-- e -> return $ Left e\n-------------------------------------------------------------------------------------------------\n\n-- rd_kafka_message\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_message_destroy\"\n rdKafkaMessageDestroyF :: FunPtr (Ptr RdKafkaMessageT -> IO ())\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_message_destroy\"\n rdKafkaMessageDestroy :: Ptr RdKafkaMessageT -> IO ()\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 unsafe rd_kafka_message_timestamp as ^\n {`RdKafkaMessageTPtr', `RdKafkaTimestampTypeTPtr'} -> `CInt64T' cIntConv #}\n\n{#fun unsafe 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 :: FunPtr (Ptr RdKafkaConfT -> IO ())\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 :: FunPtr (Ptr RdKafkaTopicConfT -> IO ())\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 unsafe \"rdkafka.h &rd_kafka_destroy\"\n rdKafkaDestroy :: FunPtr (Ptr RdKafkaT -> IO ())\n\nnewRdKafkaT :: RdKafkaTypeT -> RdKafkaConfTPtr -> IO (Either String 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 peekCString charPtr >>= return . Left\n else do\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_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-- 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 `Word8Ptr'}\n -> `Int' #}\n\n{#fun rd_kafka_produce_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', `RdKafkaMessageTPtr', `Int'} -> `Int' #}\n\ncastMetadata :: Ptr (Ptr RdKafkaMetadataT) -> Ptr (Ptr ())\ncastMetadata ptr = castPtr ptr\n\n-- rd_kafka_metadata\n\n{#fun rd_kafka_metadata as ^\n {`RdKafkaTPtr', boolToCInt `Bool', `RdKafkaTopicTPtr',\n castMetadata `Ptr (Ptr RdKafkaMetadataT)', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{# fun rd_kafka_metadata_destroy as ^\n {castPtr `Ptr RdKafkaMetadataT'} -> `()' #}\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\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' :: FunPtr (Ptr RdKafkaTopicT -> IO ())\n\nnewUnmanagedRdKafkaTopicT :: RdKafkaTPtr -> String -> RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewUnmanagedRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- 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 -> RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- rdKafkaTopicConfDup topicConfPtr\n ret <- rdKafkaTopicNew kafkaPtr topic duper\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then kafkaErrnoString >>= return . Left\n else do\n addForeignPtrFinalizer rdKafkaTopicDestroy' ret\n return $ Right ret\n\n-- Marshall \/ Unmarshall\nenumToCInt :: Enum a => a -> CInt\nenumToCInt = fromIntegral . fromEnum\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\nboolToCInt :: Bool -> CInt\nboolToCInt True = CInt 1\nboolToCInt False = CInt 0\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":"5cbb5ff3368357d1e0c393e9b3888f757b90631e","subject":"prevent emulation mode (9999,9999) overflowing to 10k","message":"prevent emulation mode (9999,9999) overflowing to 10k\n\nIgnore-this: ffcb1d78cdb004bf13a6ae2a389b4083\n\ndarcs-hash:20090724073253-115f9-59b0fca9f69e53c0fd5825797c3d86f3ebaaf392.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Device.chs","new_file":"Foreign\/CUDA\/Device.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Device\n (\n ComputeMode,\n DeviceFlags,\n DeviceProperties(..),\n\n -- ** Device management\n choose,\n get,\n count,\n props,\n set,\n setFlags,\n setOrder\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum cudaComputeMode as ComputeMode { }\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlags { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Double, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\nchoose :: DeviceProperties -> IO (Either String Int)\nchoose dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n-- |\n-- Returns which device is currently being used\n--\nget :: IO (Either String Int)\nget = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Return information about the selected compute device\n--\nprops :: Int -> IO (Either String DeviceProperties)\nprops n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek* ,\n `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set device to be used for GPU execution\n--\nset :: Int -> IO (Maybe String)\nset n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set flags to be used for device executions\n--\nsetFlags :: [DeviceFlags] -> IO (Maybe String)\nsetFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\nsetOrder :: [Int] -> IO (Maybe String)\nsetOrder l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\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-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Device\n (\n ComputeMode,\n DeviceFlags,\n DeviceProperties(..),\n\n -- ** Device management\n choose,\n get,\n count,\n props,\n set,\n setFlags,\n setOrder\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum cudaComputeMode as ComputeMode { }\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlags { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Float, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\nchoose :: DeviceProperties -> IO (Either String Int)\nchoose dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n-- |\n-- Returns which device is currently being used\n--\nget :: IO (Either String Int)\nget = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Return information about the selected compute device\n--\nprops :: Int -> IO (Either String DeviceProperties)\nprops n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek* ,\n `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set device to be used for GPU execution\n--\nset :: Int -> IO (Maybe String)\nset n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set flags to be used for device executions\n--\nsetFlags :: [DeviceFlags] -> IO (Maybe String)\nsetFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\nsetOrder :: [Int] -> IO (Maybe String)\nsetOrder l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d2c35d0f9bc29f7d71f712063c3b4f811fa9a6fc","subject":"Add destroy attributes function","message":"Add destroy attributes function\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":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"062f7e048c527199939b52db0c125a6c3b977967","subject":"gstreamer: more docs in M.S.G.Core.Caps","message":"gstreamer: more docs in M.S.G.Core.Caps\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit","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":"120649c1ba2ce7bdffcc252690c1489491964ed9","subject":"Add mutex functions to Gtk and remove the funky threaded intialisation function.","message":"Add mutex functions to Gtk and remove the funky threaded intialisation function.","repos":"vincenthz\/webkit","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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n threadsEnter,\n threadsLeave,\n \n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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\nunsafeInitGUIForThreadedRTS = initGUI\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 header 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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\n--\n-- * If you want to use Gtk2Hs and in a multi-threaded application then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'. See also 'threadsEnter'.\n--\ninitGUI :: IO [String]\ninitGUI = do\n when rtsSupportsBoundThreads initialiseGThreads\n threadsEnter\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\n\n-- | Acquired the global Gtk lock.\n--\n-- * During normal operation, this lock is held by the thread from which all\n-- interaction with Gtk is performed. When calling 'mainGUI', the thread will\n-- release this global lock before it waits for user interaction. During this\n-- time it is, in principle, possible to use a different OS thread (any other\n-- Haskell thread that is bound to the Gtk OS thread will be blocked anyway)\n-- to interact with Gtk by explicitly acquiring the lock, calling Gtk functions\n-- and releasing the lock. However, the Gtk functions that are called from this\n-- different thread may not trigger any calls to the OS since this will\n-- lead to a crash on Windows (the Win32 API can only be used from a single\n-- thread). Since it is very hard to tell which function only interacts on\n-- Gtk data structures and which function call actual OS functions, it\n-- is best not to use this feature at all. A better way to perform updates\n-- in the background is to spawn a Haskell thread and to perform the update\n-- to Gtk widgets using 'postGUIAsync' or 'postGUISync'. These will execute\n-- their arguments from the main loop, that is, from the OS thread of Gtk,\n-- thereby ensuring that any Gtk and OS function can be called.\n--\n{#fun unsafe gdk_threads_enter as threadsEnter {} -> `()' #}\n\n-- | Release the global Gtk lock.\n--\n-- * The use of this function is not recommended. See 'threadsEnter'.\n--\n{#fun unsafe gdk_threads_leave as threadsLeave {} -> `()' #}\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-- 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 -- * Initialisation\n initGUI,\n\n -- ** Support for OS threads\n unsafeInitGUIForThreadedRTS,\n postGUISync,\n postGUIAsync,\n\n -- * Main event loop\n mainGUI,\n mainQuit,\n\n -- ** Less commonly used event loop functions\n eventsPending,\n mainLevel,\n mainIteration,\n mainIterationDo,\n \n -- * Grab widgets\n grabAdd,\n grabGetCurrent,\n grabRemove,\n \n -- * Timeout and idle callbacks\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.Concurrent (rtsSupportsBoundThreads, newEmptyMVar,\n putMVar, takeMVar)\nimport Data.IORef (IORef, newIORef, readIORef, writeIORef)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\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 header 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.\n--\n-- This must be called before any other function in the Gtk2Hs library.\n--\n-- This function initializes 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: @error \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n name <- getProgName\n when (rtsSupportsBoundThreads && name \/= \"\") $ fail $ \"\\n\" ++\n \"initGUI: Gtk+ is single threaded and so cannot safely be used from\\n\" ++\n \"multiple Haskell threads when using GHC's threaded RTS. You can\\n\" ++\n \"avoid this error by relinking your program without using the\\n\" ++\n \"'-threaded' flag. If you have to use the threaded RTS and are\\n\" ++\n \"absolutely sure that you only ever call Gtk+ from a single OS\\n\" ++\n \"thread then you can use the function: unsafeInitGUIForThreadedRTS\\n\"\n\n unsafeInitGUIForThreadedRTS\n\n{-# NOINLINE unsafeInitGUIForThreadedRTS #-}\n-- | Same as initGUI except that it prints no warning when used with GHC's\n-- threaded RTS.\n--\n-- If you want to use Gtk2Hs and the threaded RTS then it is your obligation\n-- to ensure that all calls to Gtk+ happen on a single OS thread.\n-- If you want to make calls to Gtk2Hs functions from a Haskell thread other\n-- than the one that calls this functions and 'mainGUI' then you will have to\n-- \\'post\\' your GUI actions to the main GUI thread. You can do this using\n-- 'postGUISync' or 'postGUIAsync'.\n--\nunsafeInitGUIForThreadedRTS :: IO [String]\nunsafeInitGUIForThreadedRTS = do\n when rtsSupportsBoundThreads initialiseGThreads\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-- g_thread_init aborts the whole program if it's called more than once so\n-- we've got to keep track of whether or not we've called it already. Sigh.\n--\nforeign import ccall \"hsgthread.h gtk2hs_threads_initialise\"\n initialiseGThreads :: IO ()\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread blocks until the action completes and the result is\n-- returned.\n--\npostGUISync :: IO a -> IO a\npostGUISync action = do\n resultVar <- newEmptyMVar\n idleAdd (action >>= putMVar resultVar >> return False) priorityDefault\n takeMVar resultVar\n\n-- | Post an action to be run in the main GUI thread.\n--\n-- The current thread continues and does not wait for the result of the\n-- action.\n--\npostGUIAsync :: IO () -> IO ()\npostGUIAsync action = do\n idleAdd (action >> return False) priorityDefault\n return ()\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":"49d77a8359c7b18b7ccfff4f487bacc48ea14f39","subject":"unfortunately need to export the accessor; must fix this!","message":"unfortunately need to export the accessor; must fix this!\n\nIgnore-this: 5b262b31d6c264545674ca68dcd5e446\n\ndarcs-hash:20091124051426-9241b-46bae7fda937489831cc5b30c8881a2ca61839c1.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Device.chs","new_file":"Foreign\/CUDA\/Driver\/Device.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device\n (\n Device(..), -- should be exported abstractly\n DeviceProperties(..), Attribute(..),\n\n initialise, capability, get, attribute, count, name, props, totalMem\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as Attribute\n { underscoreToCase }\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> DeviceProperties nocode #}\n\n\n-- |\n-- Properties of the compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n maxThreadsPerBlock :: Int, -- ^ Maximum number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Maximum size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Maximum size of each dimension of a grid\n sharedMemPerBlock :: Int, -- ^ Shared memory available per block in bytes\n totalConstantMemory :: Int, -- ^ Constant memory available on device in bytes\n warpSize :: Int, -- ^ Warp size in threads (SIMD width)\n memPitch :: Int, -- ^ Maximum pitch in bytes allowed by memory copies\n regsPerBlock :: Int, -- ^ 32-bit registers available per block\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n textureAlign :: Int -- ^ Alignment requirement for textures\n }\n deriving (Show)\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset' :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset' :: Ptr CInt)\n\n return DeviceProperties\n {\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n sharedMemPerBlock = sm,\n totalConstantMemory = cm,\n warpSize = ws,\n memPitch = mp,\n regsPerBlock = rb,\n clockRate = cl,\n textureAlign = ta\n }\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. Fills in the `flags' parameter with the\n-- required zero value. Must be called before any other driver function.\n--\ninitialise :: IO (Maybe String)\ninitialise = nothingIfOk `fmap` cuInit 0\n\n{# fun unsafe cuInit\n { cIntConv `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\ncapability :: Device -> IO (Either String Double)\ncapability dev =\n (\\(s,a,b) -> resultIfOk (s,cap a b)) `fmap` cuDeviceComputeCapability dev\n where\n cap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a device handle\n--\nget :: Int -> IO (Either String Device)\nget d = resultIfOk `fmap` cuDeviceGet d\n\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Return the selected attribute for the given device\n--\nattribute :: Device -> Attribute -> IO (Either String Int)\nattribute d a = resultIfOk `fmap` cuDeviceGetAttribute a d\n\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `Attribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cuDeviceGetCount\n\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Name of the device\n--\nname :: Device -> IO (Either String String)\nname d = resultIfOk `fmap` cuDeviceGetName d\n\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\nprops :: Device -> IO (Either String DeviceProperties)\nprops d = resultIfOk `fmap` cuDeviceGetProperties d\n\n{# fun unsafe cuDeviceGetProperties\n { alloca- `DeviceProperties' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Total memory available on the device (bytes)\n--\ntotalMem :: Device -> IO (Either String Int)\ntotalMem d = resultIfOk `fmap` cuDeviceTotalMem d\n\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Device\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Device\n (\n Device, DeviceProperties(..), Attribute(..),\n\n initialise, capability, get, attribute, count, name, props, totalMem\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (liftM)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\nnewtype Device = Device { useDevice :: {# type CUdevice #}}\n deriving (Show)\n\n\n-- |\n-- Device attributes\n--\n{# enum CUdevice_attribute as Attribute\n { underscoreToCase }\n with prefix=\"CU_DEVICE_ATTRIBUTE\" deriving (Eq, Show) #}\n\n{# pointer *CUdevprop as ^ foreign -> DeviceProperties nocode #}\n\n\n-- |\n-- Properties of the compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n maxThreadsPerBlock :: Int, -- ^ Maximum number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Maximum size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Maximum size of each dimension of a grid\n sharedMemPerBlock :: Int, -- ^ Shared memory available per block in bytes\n totalConstantMemory :: Int, -- ^ Constant memory available on device in bytes\n warpSize :: Int, -- ^ Warp size in threads (SIMD width)\n memPitch :: Int, -- ^ Maximum pitch in bytes allowed by memory copies\n regsPerBlock :: Int, -- ^ 32-bit registers available per block\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n textureAlign :: Int -- ^ Alignment requirement for textures\n }\n deriving (Show)\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof CUdevprop#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n tb <- cIntConv `fmap` {#get CUdevprop.maxThreadsPerBlock#} p\n sm <- cIntConv `fmap` {#get CUdevprop.sharedMemPerBlock#} p\n cm <- cIntConv `fmap` {#get CUdevprop.totalConstantMemory#} p\n ws <- cIntConv `fmap` {#get CUdevprop.SIMDWidth#} p\n mp <- cIntConv `fmap` {#get CUdevprop.memPitch#} p\n rb <- cIntConv `fmap` {#get CUdevprop.regsPerBlock#} p\n cl <- cIntConv `fmap` {#get CUdevprop.clockRate#} p\n ta <- cIntConv `fmap` {#get CUdevprop.textureAlign#} p\n\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset' :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset' :: Ptr CInt)\n\n return DeviceProperties\n {\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n sharedMemPerBlock = sm,\n totalConstantMemory = cm,\n warpSize = ws,\n memPitch = mp,\n regsPerBlock = rb,\n clockRate = cl,\n textureAlign = ta\n }\n\n--------------------------------------------------------------------------------\n-- Initialisation\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise the CUDA driver API. Fills in the `flags' parameter with the\n-- required zero value. Must be called before any other driver function.\n--\ninitialise :: IO (Maybe String)\ninitialise = nothingIfOk `fmap` cuInit 0\n\n{# fun unsafe cuInit\n { cIntConv `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the compute compatibility revision supported by the device\n--\ncapability :: Device -> IO (Either String Double)\ncapability dev =\n (\\(s,a,b) -> resultIfOk (s,cap a b)) `fmap` cuDeviceComputeCapability dev\n where\n cap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n\n{# fun unsafe cuDeviceComputeCapability\n { alloca- `Int' peekIntConv*\n , alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a device handle\n--\nget :: Int -> IO (Either String Device)\nget d = resultIfOk `fmap` cuDeviceGet d\n\n{# fun unsafe cuDeviceGet\n { alloca- `Device' dev*\n , cIntConv `Int' } -> `Status' cToEnum #}\n where dev = liftM Device . peekIntConv\n\n\n-- |\n-- Return the selected attribute for the given device\n--\nattribute :: Device -> Attribute -> IO (Either String Int)\nattribute d a = resultIfOk `fmap` cuDeviceGetAttribute a d\n\n{# fun unsafe cuDeviceGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `Attribute'\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the number of device with compute capability > 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cuDeviceGetCount\n\n{# fun unsafe cuDeviceGetCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Name of the device\n--\nname :: Device -> IO (Either String String)\nname d = resultIfOk `fmap` cuDeviceGetName d\n\n{# fun unsafe cuDeviceGetName\n { allocaS- `String'& peekS*\n , useDevice `Device' } -> `Status' cToEnum #}\n where\n len = 512\n allocaS a = allocaBytes len $ \\p -> a (p, cIntConv len)\n peekS s _ = peekCString s\n\n\n-- |\n-- Return the properties of the selected device\n--\nprops :: Device -> IO (Either String DeviceProperties)\nprops d = resultIfOk `fmap` cuDeviceGetProperties d\n\n{# fun unsafe cuDeviceGetProperties\n { alloca- `DeviceProperties' peek*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n\n-- |\n-- Total memory available on the device (bytes)\n--\ntotalMem :: Device -> IO (Either String Int)\ntotalMem d = resultIfOk `fmap` cuDeviceTotalMem d\n\n{# fun unsafe cuDeviceTotalMem\n { alloca- `Int' peekIntConv*\n , useDevice `Device' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3f37251e6a8e07763dcb28cbd4f86ff69dd86069","subject":"removed phantom type from Datasource","message":"removed phantom type from Datasource\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2ee7103fb594a168050ae37e272bdf4d6654b73d","subject":"fixed memory leak","message":"fixed memory leak\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/OSGeo\/GDAL\/Internal.chs","new_file":"src\/OSGeo\/GDAL\/Internal.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7364b75971376929c9d44ea44dba1c3ddf1135af","subject":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM","message":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0dd85f17291985842227f5440f9d34ea232d2478","subject":"Added webDataSourceGetData","message":"Added webDataSourceGetData\n\nThis requires a version of glib with GString patch applied.\n","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content.The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\nwebDataSourceGetData :: WebDataSourceClass self => self\n -> IO (Maybe String)\nwebDataSourceGetData ds = do\n gstr <- {#call webkit_web_data_source_get_data #}\n (toWebDataSource ds)\n readGString gstr\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n -- webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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 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-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content.The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\n-- \n-- webDataSourceGetData :: WebDataSourceClass self => self\n-- -> IO (Maybe String)\n-- webDataSourceGetData ds = do\n-- ptr <- {#call webkit_web_data_source_get_data #}\n-- (toWebDataSource ds)\n-- if strPtr == nullPtr\n-- then return Nothing\n-- else liftM Just $ peekCStringLen (strPtr, strLen)\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0c3722bf6db201d443d60c9a9622dd2a31b5fd2a","subject":"log size wibble","message":"log size wibble\n\nThe size returned by nvvmGet*Size includes the NULL terminator. Make sure we don't include that when marshaling to a ByteString.\n","repos":"nvidia-compiler-sdk\/hsnvvm","old_file":"Foreign\/LibNVVM\/Compile.chs","new_file":"Foreign\/LibNVVM\/Compile.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- |\n-- Module : Foreign.LibNVVM.Compile\n-- Copyright : 2012 Sean Lee\n-- 2014 Trevor L. McDonell\n-- License :\n--\n-- Maintainer : Sean Lee \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\nmodule Foreign.LibNVVM.Compile (\n\n -- * Compilation result\n Result(..), CompileFlag(..), VerifyFlag,\n\n -- * Compilation\n compileModule, compileModules,\n\n) where\n\nimport Prelude hiding ( log )\nimport Data.ByteString ( ByteString )\nimport Data.Word\nimport Control.Exception\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Unsafe as B\nimport qualified Data.ByteString.Internal as B\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Marshal\nimport Foreign.Storable\nimport Foreign.CUDA.Analysis\nimport Foreign.LibNVVM.Error\nimport Foreign.LibNVVM.Internal\n\n#include \n\n{# context lib=\"nvvm\" #}\n\n\n-- | The return type of compiling a module(s) is the compilation log together\n-- with the resulting binary ptx\/cubin.\n--\ndata Result = Result {\n -- | Any compilation or verification messages and warnings that were\n -- generated during compilation of the NVVM module. Note that even upon\n -- successful completion, the log may not be empty.\n --\n nvvmLog :: {-# UNPACK #-} !ByteString\n , nvvmResult :: {-# UNPACK #-} !ByteString\n }\n\n\n-- | An opaque handle to an NVVM program\n--\nnewtype Program = Program { useProgram :: {# type nvvmProgram #}}\n deriving (Eq, Show)\n\n\n-- | The available program compilation flags\n--\ndata CompileFlag\n -- | Level of optimisation to apply (0-3) (Default: 3)\n = OptimisationLevel !Int\n\n -- | Compute architecture to target (Default: Compute 2.0)\n | Target !Compute\n\n -- | Flush denormal values to zero when performing single-precision floating\n -- point operations (Default: preserve denormal values)\n | FlushToZero\n\n -- | Use a faster approximation for single-precision floating-point square\n -- root (Default: use IEEE round-to-nearest mode)\n | FastSqrt\n\n -- | Use a faster approximation for single-precision floating-point division\n -- and reciprocal operations (Default: use IEEE round-to-nearest mode)\n | FastDiv\n\n -- | Disable fused-multiply-add contraction (Default: enabled)\n | DisableFMA\n\n -- | Generate debugging symbols (-g) (Default: no)\n | GenerateDebugInfo\n\n\n-- | The available program verification flags\n--\ndata VerifyFlag\n\n\ncompileFlagToArg :: CompileFlag -> String\ncompileFlagToArg f =\n case f of\n OptimisationLevel o -> printf \"-opt=%d\" o\n Target (Compute n m) -> printf \"-arch=compute_%d%d\" n m\n FlushToZero -> \"-ftz=1\"\n FastSqrt -> \"-prec-sqrt=0\"\n FastDiv -> \"-prec-div=0\"\n DisableFMA -> \"-fma=0\"\n GenerateDebugInfo -> \"-g\"\n\n\nverifyFlagToArg :: VerifyFlag -> String\nverifyFlagToArg _ = error \"verifyFlagToArg\"\n\n\n-- High-level interface\n-- --------------------\n\n-- | Compile an NVVM IR module according to the specified options. If an error\n-- occurs an exception is thrown, otherwise the generated PTX is returned\n-- together with any warning or verification messages generated during\n-- compilation.\n--\n-- The input NVVM IR module can be either in the bitcode representation or the\n-- text representation.\n--\ncompileModule\n :: String -- ^ name of the module (optional)\n -> ByteString -- ^ module NVVM IR\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModule name bc = compileModules [(name,bc)]\n\n\n-- | Compile and link multiple NVVM IR modules together to form a single\n-- program. The compiled result is represented in PTX.\n--\n-- Each NVVM IR module may individually be in either the bitcode representation\n-- or in the text representation.\n--\ncompileModules\n :: [(String, ByteString)] -- ^ modules to compile and link\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModules modules opts verify =\n bracket create destroy $ \\prg -> do\n res <- try $ do\n mapM_ (uncurry (addModule prg)) modules\n when verify (verifyProgram prg [])\n compileProgram prg opts\n compilerResult prg\n log <- compilerLog prg\n case res of\n Left (err :: NVVMException) -> nvvmError (unlines [show err, B.unpack log])\n Right ptx -> return $ Result log ptx\n\n\n-- The raw interface to libNVVM\n-- ----------------------------\n\n-- | Create a new program handle\n--\ncreate :: IO Program\ncreate = resultIfOk =<< nvvmCreateProgram\n\n{-# INLINE nvvmCreateProgram #-}\n{# fun unsafe nvvmCreateProgram\n { alloca- `Program' peekProgram*\n }\n -> `Status' cToEnum #}\n where\n peekProgram = liftM Program . peek\n\n\n-- | Destroy a program handle\n--\ndestroy :: Program -> IO ()\ndestroy p = nothingIfOk =<< nvvmDestroyProgram p\n\n{-# INLINE nvvmDestroyProgram #-}\n{# fun unsafe nvvmDestroyProgram\n { withProgram* `Program' } -> `Status' cToEnum #}\n where\n withProgram = with . useProgram\n\n\n-- | Add an NVVM IR module to the given program compilation unit. An exception\n-- is raised if:\n--\n-- * The 'Program' to add to is invalid; or\n--\n-- * The NVVM module IR is invalid.\n--\naddModule :: Program -> String -> ByteString -> IO ()\naddModule prg name mdl =\n B.unsafeUseAsCStringLen mdl $ \\(b,n) -> do\n nothingIfOk =<< nvvmAddModuleToProgram prg b n name\n\n{-# INLINE nvvmAddModuleToProgram #-}\n{# fun unsafe nvvmAddModuleToProgram\n { useProgram `Program'\n , id `CString'\n , cIntConv `Int'\n , withCString'* `String'\n }\n -> `Status' cToEnum #}\n where\n withCString' [] f = f nullPtr -- defaults to \"\"\n withCString' s f = withCString s f\n\n\n-- | Compile the given 'Program' and all modules that have been previously added\n-- to it.\n--\ncompileProgram :: Program -> [CompileFlag] -> IO ()\ncompileProgram prg opts =\n bracket\n (mapM (newCString . compileFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmCompileProgram prg))\n\n{-# INLINE nvvmCompileProgram #-}\n{# fun unsafe nvvmCompileProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the result of compiling a 'Program' as a 'ByteString' containing\n-- the generated PTX. An exception is raised if the compilation unit is invalid.\n--\ncompilerResult :: Program -> IO ByteString\ncompilerResult prg = do\n n <- resultIfOk =<< nvvmGetCompiledResultSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetCompiledResult prg log\n return $! B.fromForeignPtr log 0 (n-1) -- size includes the NULL terminator\n\n{-# INLINE nvvmGetCompiledResult #-}\n{# fun unsafe nvvmGetCompiledResult\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetCompiledResultSize #-}\n{# fun unsafe nvvmGetCompiledResultSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the log of compiling a 'Program' as a 'ByteString'.\n--\ncompilerLog :: Program -> IO ByteString\ncompilerLog prg = do\n n <- resultIfOk =<< nvvmGetProgramLogSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetProgramLog prg log\n return $! B.fromForeignPtr log 0 (n-1) -- size includes the NULL terminator\n\n{-# INLINE nvvmGetProgramLog #-}\n{# fun unsafe nvvmGetProgramLog\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetProgramLogSize #-}\n{# fun unsafe nvvmGetProgramLogSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Verify the NVVM program. If an error is encountered, an exception is\n-- thrown.\n--\nverifyProgram :: Program -> [VerifyFlag] -> IO ()\nverifyProgram prg opts =\n bracket\n (mapM (newCString . verifyFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmVerifyProgram prg))\n\n{# fun unsafe nvvmVerifyProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n-- |\n-- Module : Foreign.LibNVVM.Compile\n-- Copyright : 2012 Sean Lee\n-- 2014 Trevor L. McDonell\n-- License :\n--\n-- Maintainer : Sean Lee \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\nmodule Foreign.LibNVVM.Compile (\n\n -- * Compilation result\n Result(..), CompileFlag(..), VerifyFlag,\n\n -- * Compilation\n compileModule, compileModules,\n\n) where\n\nimport Prelude hiding ( log )\nimport Data.ByteString ( ByteString )\nimport Data.Word\nimport Control.Exception\nimport Control.Monad\nimport Text.Printf\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Unsafe as B\nimport qualified Data.ByteString.Internal as B\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Marshal\nimport Foreign.Storable\nimport Foreign.CUDA.Analysis\nimport Foreign.LibNVVM.Error\nimport Foreign.LibNVVM.Internal\n\n#include \n\n{# context lib=\"nvvm\" #}\n\n\n-- | The return type of compiling a module(s) is the compilation log together\n-- with the resulting binary ptx\/cubin.\n--\ndata Result = Result {\n -- | Any compilation or verification messages and warnings that were\n -- generated during compilation of the NVVM module. Note that even upon\n -- successful completion, the log may not be empty.\n --\n nvvmLog :: {-# UNPACK #-} !ByteString\n , nvvmResult :: {-# UNPACK #-} !ByteString\n }\n\n\n-- | An opaque handle to an NVVM program\n--\nnewtype Program = Program { useProgram :: {# type nvvmProgram #}}\n deriving (Eq, Show)\n\n\n-- | The available program compilation flags\n--\ndata CompileFlag\n -- | Level of optimisation to apply (0-3) (Default: 3)\n = OptimisationLevel !Int\n\n -- | Compute architecture to target (Default: Compute 2.0)\n | Target !Compute\n\n -- | Flush denormal values to zero when performing single-precision floating\n -- point operations (Default: preserve denormal values)\n | FlushToZero\n\n -- | Use a faster approximation for single-precision floating-point square\n -- root (Default: use IEEE round-to-nearest mode)\n | FastSqrt\n\n -- | Use a faster approximation for single-precision floating-point division\n -- and reciprocal operations (Default: use IEEE round-to-nearest mode)\n | FastDiv\n\n -- | Disable fused-multiply-add contraction (Default: enabled)\n | DisableFMA\n\n -- | Generate debugging symbols (-g) (Default: no)\n | GenerateDebugInfo\n\n\n-- | The available program verification flags\n--\ndata VerifyFlag\n\n\ncompileFlagToArg :: CompileFlag -> String\ncompileFlagToArg f =\n case f of\n OptimisationLevel o -> printf \"-opt=%d\" o\n Target (Compute n m) -> printf \"-arch=compute_%d%d\" n m\n FlushToZero -> \"-ftz=1\"\n FastSqrt -> \"-prec-sqrt=0\"\n FastDiv -> \"-prec-div=0\"\n DisableFMA -> \"-fma=0\"\n GenerateDebugInfo -> \"-g\"\n\n\nverifyFlagToArg :: VerifyFlag -> String\nverifyFlagToArg _ = error \"verifyFlagToArg\"\n\n\n-- High-level interface\n-- --------------------\n\n-- | Compile an NVVM IR module according to the specified options. If an error\n-- occurs an exception is thrown, otherwise the generated PTX is returned\n-- together with any warning or verification messages generated during\n-- compilation.\n--\n-- The input NVVM IR module can be either in the bitcode representation or the\n-- text representation.\n--\ncompileModule\n :: String -- ^ name of the module (optional)\n -> ByteString -- ^ module NVVM IR\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModule name bc = compileModules [(name,bc)]\n\n\n-- | Compile and link multiple NVVM IR modules together to form a single\n-- program. The compiled result is represented in PTX.\n--\n-- Each NVVM IR module may individually be in either the bitcode representation\n-- or in the text representation.\n--\ncompileModules\n :: [(String, ByteString)] -- ^ modules to compile and link\n -> [CompileFlag] -- ^ compilation options\n -> Bool -- ^ verify program?\n -> IO Result\ncompileModules modules opts verify =\n bracket create destroy $ \\prg -> do\n res <- try $ do\n mapM_ (uncurry (addModule prg)) modules\n when verify (verifyProgram prg [])\n compileProgram prg opts\n compilerResult prg\n log <- compilerLog prg\n case res of\n Left (err :: NVVMException) -> nvvmError (unlines [show err, B.unpack log])\n Right ptx -> return $ Result log ptx\n\n\n-- The raw interface to libNVVM\n-- ----------------------------\n\n-- | Create a new program handle\n--\ncreate :: IO Program\ncreate = resultIfOk =<< nvvmCreateProgram\n\n{-# INLINE nvvmCreateProgram #-}\n{# fun unsafe nvvmCreateProgram\n { alloca- `Program' peekProgram*\n }\n -> `Status' cToEnum #}\n where\n peekProgram = liftM Program . peek\n\n\n-- | Destroy a program handle\n--\ndestroy :: Program -> IO ()\ndestroy p = nothingIfOk =<< nvvmDestroyProgram p\n\n{-# INLINE nvvmDestroyProgram #-}\n{# fun unsafe nvvmDestroyProgram\n { withProgram* `Program' } -> `Status' cToEnum #}\n where\n withProgram = with . useProgram\n\n\n-- | Add an NVVM IR module to the given program compilation unit. An exception\n-- is raised if:\n--\n-- * The 'Program' to add to is invalid; or\n--\n-- * The NVVM module IR is invalid.\n--\naddModule :: Program -> String -> ByteString -> IO ()\naddModule prg name mdl =\n B.unsafeUseAsCStringLen mdl $ \\(b,n) -> do\n nothingIfOk =<< nvvmAddModuleToProgram prg b n name\n\n{-# INLINE nvvmAddModuleToProgram #-}\n{# fun unsafe nvvmAddModuleToProgram\n { useProgram `Program'\n , id `CString'\n , cIntConv `Int'\n , withCString'* `String'\n }\n -> `Status' cToEnum #}\n where\n withCString' [] f = f nullPtr -- defaults to \"\"\n withCString' s f = withCString s f\n\n\n-- | Compile the given 'Program' and all modules that have been previously added\n-- to it.\n--\ncompileProgram :: Program -> [CompileFlag] -> IO ()\ncompileProgram prg opts =\n bracket\n (mapM (newCString . compileFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmCompileProgram prg))\n\n{-# INLINE nvvmCompileProgram #-}\n{# fun unsafe nvvmCompileProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the result of compiling a 'Program' as a 'ByteString' containing\n-- the generated PTX. An exception is raised if the compilation unit is invalid.\n--\ncompilerResult :: Program -> IO ByteString\ncompilerResult prg = do\n n <- resultIfOk =<< nvvmGetCompiledResultSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetCompiledResult prg log\n return $ B.fromForeignPtr log 0 n\n\n{-# INLINE nvvmGetCompiledResult #-}\n{# fun unsafe nvvmGetCompiledResult\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetCompiledResultSize #-}\n{# fun unsafe nvvmGetCompiledResultSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Retrieve the log of compiling a 'Program' as a 'ByteString'.\n--\ncompilerLog :: Program -> IO ByteString\ncompilerLog prg = do\n n <- resultIfOk =<< nvvmGetProgramLogSize prg\n log <- B.mallocByteString n\n nothingIfOk =<< nvvmGetProgramLog prg log\n return $ B.fromForeignPtr log 0 n\n\n{-# INLINE nvvmGetProgramLog #-}\n{# fun unsafe nvvmGetProgramLog\n { useProgram `Program'\n , withForeignPtr'* `ForeignPtr Word8'\n }\n -> `Status' cToEnum #}\n where\n withForeignPtr' p f = withForeignPtr (castForeignPtr p) f\n\n{-# INLINE nvvmGetProgramLogSize #-}\n{# fun unsafe nvvmGetProgramLogSize\n { useProgram `Program'\n , alloca- `Int' peekIntConv*\n }\n -> `Status' cToEnum #}\n\n\n-- | Verify the NVVM program. If an error is encountered, an exception is\n-- thrown.\n--\nverifyProgram :: Program -> [VerifyFlag] -> IO ()\nverifyProgram prg opts =\n bracket\n (mapM (newCString . verifyFlagToArg) opts)\n (mapM free)\n (\\args -> nothingIfOk =<< withArrayLen args (nvvmVerifyProgram prg))\n\n{# fun unsafe nvvmVerifyProgram\n { useProgram `Program'\n , cIntConv `Int'\n , id `Ptr CString'\n }\n -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"622cdfe5103c78edda46cb0fa70e0cd891c7f865","subject":"give device pointers a (nil) type variable","message":"give device pointers a (nil) type variable\n\nIgnore-this: 7c0a0ce8c5b8517e8966eae66fd34b6a\n\ndarcs-hash:20090721124847-115f9-70ddedbc5b25d10ec53c782a4c1326bee0977747.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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\ntype DevicePtr a = ForeignPtr a\n\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\nnewDevicePtr :: Ptr () -> IO (DevicePtr ())\nnewDevicePtr p = (doAutoRelease free_) >>= \\f -> newForeignPtr f p\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 ()))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> newDevicePtr ptr >>= (return.Right)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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 (),Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> newDevicePtr ptr >>= \\dp -> return.Right $ (dp,pitch)\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\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 (),Int64))\nmalloc3D = error \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr () -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr ()' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr () -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr ()' ,\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 () -- ^ 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 = error \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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","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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\nnewtype DevicePtr = DevicePtr (ForeignPtr ())\n\nwithDevicePtr :: DevicePtr -> (Ptr () -> IO b) -> IO b\nwithDevicePtr (DevicePtr d) = withForeignPtr d\n\nnewDevicePtr :: FinalizerPtr () -> Ptr () -> IO DevicePtr\nnewDevicePtr fp p = newForeignPtr fp p >>= (return.DevicePtr)\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)\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> doAutoRelease free_ >>= \\fp ->\n newDevicePtr fp ptr >>= (return.Right)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\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,Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease free_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\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\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,Int64))\nmalloc3D = error \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr -> Int64 -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr' ,\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 -- ^ 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 = error \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 = 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-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f7d80c08a1987a4864f4c303af826a6c208f30cc","subject":"Remove extraneous | chars from the haddock documentation","message":"Remove extraneous | chars from 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--\n-- > LT input 1 \n--\n-- is the current token. Or a negative offset may be specified, where: \n--\n-- > LT input (-1) \n--\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--\n-- > tokenGetAntlrString token\n--\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:\n--\n-- > LT input 1 \n--\n-- | is the current token. Or a negative offset may be specified, where: \n--\n-- > LT input (-1) \n--\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--\n-- > tokenGetAntlrString token\n--\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2c2b70600ebff1a57d9786c385408f1ebc41d87a","subject":"Add property functions for Char type","message":"Add property functions for Char type\n\ndarcs-hash:20070528165852-adfee-365e05f8c8f171f40b47df6d54f18e5343fe3092.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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 objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\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\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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 writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"9b3e644f2075052fe860d4aff1efaa5c3d76366d","subject":"fixes for 7.8.4","message":"fixes for 7.8.4\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGR.chs","new_file":"src\/GDAL\/Internal\/OGR.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n , OGR\n , OGRConduit\n , OGRSource\n , OGRSink\n , runOGR\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , dataSourceName\n\n , createLayer\n , createLayerWithDef\n\n , getLayer\n , getLayerByName\n\n , sourceLayer\n , sourceLayer_\n , conduitInsertLayer\n , conduitInsertLayer_\n , sinkInsertLayer\n , sinkInsertLayer_\n , sinkUpdateLayer\n\n , executeSQL\n\n , syncLayerToDisk\n , syncToDisk\n\n , layerSpatialFilter\n , setLayerSpatialFilter\n\n , dataSourceLayerCount\n , layerName\n , layerExtent\n , layerFeatureCount\n , layerFeatureDef\n\n , createFeature\n , createFeatureWithFid\n , createFeature_\n , getFeature\n , updateFeature\n , deleteFeature\n\n , unsafeToReadOnlyLayer\n\n , registerAll\n , cleanupAll\n\n , liftOGR\n , closeLayer\n , unDataSource\n , unLayer\n , layerHasCapability\n , driverHasCapability\n , dataSourceHasCapability\n , nullLayerH\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.ByteString.Char8 (ByteString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport Data.Conduit\nimport qualified Data.Conduit.List as CL\nimport Data.Maybe (isNothing, fromMaybe)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.String (IsString)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector as V\n\nimport Control.Applicative (Applicative, (<$>), (<*>), pure)\nimport Control.Monad (liftM, when, void, (>=>), (<=<))\nimport Control.Monad.Base (MonadBase)\nimport Control.Monad.Catch (\n MonadThrow(..)\n , MonadCatch\n , MonadMask\n , bracket\n , finally\n )\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Resource (MonadResource)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..))\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\n#endif\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport Foreign.Storable (Storable, peek)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH #}\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) =\n DataSource { unDataSource :: DataSourceH }\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nnewtype OGR s l a = OGR (GDAL s a)\n\nderiving instance Functor (OGR s l)\nderiving instance Applicative (OGR s l)\nderiving instance Monad (OGR s l)\nderiving instance MonadIO (OGR s l)\nderiving instance MonadThrow (OGR s l)\nderiving instance MonadCatch (OGR s l)\nderiving instance MonadMask (OGR s l)\nderiving instance MonadBase IO (OGR s l)\nderiving instance MonadResource (OGR s l)\n\nrunOGR :: (forall l. OGR s l a )-> GDAL s a\nrunOGR (OGR a) = a\n\nliftOGR :: GDAL s a -> OGR s l a\nliftOGR = OGR\n\ntype OGRConduit s l i o = Conduit i (OGR s l) o\ntype OGRSource s l o = Source (OGR s l) o\ntype OGRSink s l i = Sink i (OGR s l)\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s l (t::AccessMode) a) = Layer (ReleaseKey, LayerH)\n\nunLayer :: Layer s l t a -> LayerH\nunLayer (Layer (_,l)) = l\n\ncloseLayer :: MonadIO m => Layer s l t a -> m ()\ncloseLayer (Layer (rk,_)) = release rk\n\ntype ROLayer s l = Layer s l ReadOnly\ntype RWLayer s l = Layer s l ReadWrite\n\nunsafeToReadOnlyLayer :: RWLayer s l a -> ROLayer s l a\nunsafeToReadOnlyLayer = coerce\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p =\n newDataSourceHandle $ withCString p $ \\p' ->\n checkGDALCall checkIt ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGROpen\"\n\n\nnewDataSourceHandle\n :: IO DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle act = liftM snd $ allocate alloc free\n where\n alloc = liftM DataSource act\n free ds\n | dsPtr \/= nullDataSourceH = {#call OGR_DS_Destroy as ^#} dsPtr\n | otherwise = return ()\n where dsPtr = unDataSource ds\n\nnewtype Driver =\n Driver ByteString deriving (Eq, IsString, Typeable)\n\ninstance Show Driver where\n show (Driver s) = show s\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n checkGDALCall checkIt\n (withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGR_Dr_CreateDataSource\"\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: Driver -> IO DriverH\ndriverByName (Driver name) = useAsCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullPtr\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: forall s l a. OGRFeatureDef a\n => RWDataSource s -> ApproxOK -> OptionList -> GDAL s (RWLayer s l a)\ncreateLayer ds = createLayerWithDef ds (featureDef (Proxy :: Proxy a))\n\n\n\ncreateLayerWithDef\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s l a)\ncreateLayerWithDef ds FeatureDef{..} approxOk options =\n liftM Layer $\n flip allocate (const (return ())) $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList options $ \\pOpts -> do\n pL <- checkGDALCall checkIt $\n {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts\n V.forM_ fdFields $ \\(n,f) -> withFieldDefnH n f $ \\pFld ->\n checkOGRError \"CreateField\" $\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if SUPPORTS_MULTI_GEOM_FIELDS\n V.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 = unDataSource 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\ngetLayerSchema :: LayerH -> IO FeatureDefnH\ngetLayerSchema = {#call OGR_L_GetLayerDefn as ^#}\n\ncreateFeatureWithFidIO\n :: OGRFeature a => LayerH -> Maybe Fid -> a -> IO (Maybe Fid)\ncreateFeatureWithFidIO pL fid feat = do\n pFd <- getLayerSchema pL\n featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" ({#call OGR_L_CreateFeature as ^#} pL pF)\n getFid pF\n\ncreateFeatureWithFid\n :: OGRFeature a => RWLayer s l a -> Maybe Fid -> a -> GDAL s (Maybe Fid)\ncreateFeatureWithFid layer fid =\n liftIO . createFeatureWithFidIO (unLayer layer) fid\n\ncreateFeature :: OGRFeature a => RWLayer s l a -> a -> GDAL s Fid\ncreateFeature layer =\n createFeatureWithFid layer Nothing >=>\n maybe (throwBindingException UnexpectedNullFid) return\n\ncreateFeature_ :: OGRFeature a => RWLayer s l a -> a -> GDAL s ()\ncreateFeature_ layer = void . createFeatureWithFid layer Nothing\n\nupdateFeature :: OGRFeature a => RWLayer s l a -> Fid -> a -> GDAL s ()\nupdateFeature layer fid feat = liftIO $ do\n pFd <- getLayerSchema pL\n featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} pL\n where pL = unLayer layer\n\ngetFeature :: OGRFeature a => Layer s l t a -> Fid -> GDAL s (Maybe a)\ngetFeature layer (Fid fid) = liftIO $ do\n when (not (pL `layerHasCapability` RandomRead)) $\n throwBindingException (UnsupportedLayerCapability RandomRead)\n fDef <- layerFeatureDefIO pL\n liftM (fmap snd) $ featureFromHandle fDef $\n checkGDALCall checkIt ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n where\n checkIt (Just GDALException{gdalErrNum=AppDefined}) _ = Nothing\n checkIt e _ = e\n pL = unLayer layer\n\ndeleteFeature :: Layer s l t a -> Fid -> GDAL s ()\ndeleteFeature layer (Fid fid) = liftIO $\n checkOGRError \"DeleteFeature\" $\n {#call OGR_L_DeleteFeature as ^#} (unLayer layer) (fromIntegral fid)\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if SUPPORTS_MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\nsyncToDisk :: RWDataSource s -> GDAL s ()\nsyncToDisk =\n liftIO .\n checkOGRError \"syncToDisk\" .\n {#call OGR_DS_SyncToDisk as ^#} .\n unDataSource\n\nsyncLayerToDiskIO :: RWLayer s l a -> IO ()\nsyncLayerToDiskIO =\n checkOGRError \"syncLayerToDisk\" . {#call OGR_L_SyncToDisk as ^#} . unLayer\n\nsyncLayerToDisk :: RWLayer s l a -> GDAL s ()\nsyncLayerToDisk = liftIO . syncLayerToDiskIO\n\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayer ix ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n {#call OGR_DS_GetLayer as ^#} (unDataSource 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\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayerByName name ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n useAsEncodedCString name $\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerName name)\n\n\nsourceLayer\n :: OGRFeature a\n => GDAL s (Layer s l t a)\n -> OGRSource s l (Maybe Fid, a)\nsourceLayer alloc = layerTransaction alloc' loop\n where\n alloc' = do\n l <- alloc\n liftIO $ {#call OGR_L_ResetReading as ^#} (unLayer l)\n fDef <- layerFeatureDef l\n return (l, fDef)\n\n loop seed = do\n next <- liftIO $\n featureFromHandle (snd seed) $\n {#call OGR_L_GetNextFeature as ^#} (unLayer (fst seed))\n case next of\n Just v -> yield v >> loop seed\n Nothing -> return ()\n\nsourceLayer_\n :: OGRFeature a => GDAL s (Layer s l t a) -> OGRSource s l a\nsourceLayer_ = (=$= (CL.map snd)) . sourceLayer\n\n\nconduitInsertLayer\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l (Maybe Fid, a) (Maybe Fid)\nconduitInsertLayer = flip conduitFromLayer createIt\n where\n createIt (l, pFd) = awaitForever $ \\(fid, feat) -> do\n fid' <- liftIO $ featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" $\n {#call OGR_L_CreateFeature as ^#} (unLayer l) pF\n getFid pF\n yield fid'\n\nconduitInsertLayer_\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l a (Maybe Fid)\nconduitInsertLayer_ = (CL.map (\\i->(Nothing,i)) =$=) . conduitInsertLayer\n\nsinkInsertLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Maybe Fid, a) ()\nsinkInsertLayer = (=$= CL.sinkNull) . conduitInsertLayer\n\nsinkInsertLayer_\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l a ()\nsinkInsertLayer_ =\n ((=$= CL.sinkNull) . ((CL.map (\\i->(Nothing,i))) =$=)) . conduitInsertLayer\n\nsinkUpdateLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Fid, a) ()\nsinkUpdateLayer = flip conduitFromLayer updateIt\n where\n updateIt (l, pFd) = awaitForever $ \\(fid, feat) ->\n liftIO $ featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} (unLayer l)\n\n\nlayerTransaction\n :: GDAL s (Layer s l t a, e)\n -> ((Layer s l t a, e) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nlayerTransaction alloc inside = do\n alloc' <- lift (liftOGR (unsafeGDALToIO alloc))\n (rbKey, seed) <- allocate alloc' rollback\n liftIO $ checkOGRError \"StartTransaction\" $\n {#call OGR_L_StartTransaction as ^#} (unLayer (fst seed))\n addCleanup (const (release rbKey))\n (inside seed >> liftIO (commit rbKey seed))\n where\n free = closeLayer . fst\n commit rbKey seed = bracket (unprotect rbKey) (const (free seed)) $ \\m -> do\n when (isNothing m) (error \"layerTransaction: this should not happen\")\n checkOGRError \"CommitTransaction\" $\n {#call OGR_L_CommitTransaction as ^#} (unLayer (fst seed))\n checkOGRError \"SyncToDisk\" $\n {#call OGR_L_SyncToDisk as ^#} (unLayer (fst seed))\n\n rollback seed =\n (checkOGRError \"RollbackTransaction\" $\n {#call OGR_L_RollbackTransaction as ^#} (unLayer (fst seed)))\n `finally` free seed\n\n\n\nconduitFromLayer\n :: GDAL s (RWLayer s l a)\n -> ((RWLayer s l a, FeatureDefnH) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nconduitFromLayer alloc = layerTransaction alloc'\n where\n alloc' = do\n l <- alloc\n schema <- liftIO $ getLayerSchema (unLayer l)\n return (l, schema)\n\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it to the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> maybeNewSpatialRefBorrowedHandle\n ({#call unsafe OGR_L_GetSpatialRef as ^#} p)\n <*> pure True\n\ndataSourceLayerCount :: DataSource s t -> GDAL s Int\ndataSourceLayerCount = liftM fromIntegral\n . liftIO . {#call OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndataSourceName :: DataSource s t -> GDAL s String\ndataSourceName =\n liftIO . (peekCString <=< {#call OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = unsafeUseAsCString \"SQLITE\\0\"\nwithSQLDialect OGRDialect = unsafeUseAsCString \"OGRSQL\\0\"\n\nexecuteSQL\n :: OGRFeature a\n => SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s l a)\nexecuteSQL dialect query mSpatialFilter ds =\n liftM Layer $ allocate execute freeIfNotNull\n where\n execute =\n checkGDALCall checkit $\n withMaybeGeometry mSpatialFilter $ \\pF ->\n useAsEncodedCString query $ \\pQ ->\n withSQLDialect dialect $ {#call OGR_DS_ExecuteSQL as ^#} pDs pQ pF\n\n freeIfNotNull pL\n | pL \/= nullLayerH = {#call unsafe OGR_DS_ReleaseResultSet as ^#} pDs pL\n | otherwise = return ()\n\n pDs = unDataSource 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\nlayerName :: Layer s l t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerExtent :: Layer s l t a -> GDAL s EnvelopeReal\nlayerExtent l = liftIO $ alloca $ \\pE -> do\n checkOGRError \"GetExtent\" ({#call OGR_L_GetExtent as ^#} (unLayer l) pE 1)\n peek pE\n\nlayerFeatureDef :: Layer s l t a -> GDAL s FeatureDef\nlayerFeatureDef = liftIO . layerFeatureDefIO . unLayer\n\nlayerFeatureDefIO :: LayerH -> IO FeatureDef\nlayerFeatureDefIO pL = do\n gfd <- layerGeomFieldDef pL\n getLayerSchema pL >>= featureDefFromHandle gfd\n\nlayerFeatureCount :: Layer s l t a -> Bool -> GDAL s (Maybe Int)\nlayerFeatureCount layer force = liftIO $ do\n c <- liftM fromIntegral $\n {#call OGR_L_GetFeatureCount as ^#} (unLayer layer) (fromBool force)\n if c<0 then return Nothing else return (Just c)\n\nlayerSpatialFilter :: Layer s l t a -> GDAL s (Maybe Geometry)\nlayerSpatialFilter l = liftIO $\n {#call unsafe OGR_L_GetSpatialFilter as ^#} (unLayer l) >>= maybeCloneGeometry\n\nsetLayerSpatialFilter :: Layer s l t a -> Geometry -> GDAL s ()\nsetLayerSpatialFilter l g = liftIO $\n withGeometry g $ {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGR (\n DataSource\n , DataSourceH\n , SQLDialect (..)\n , ApproxOK (..)\n , Layer\n , LayerH (..)\n , RODataSource\n , RWDataSource\n , ROLayer\n , RWLayer\n , Driver\n , OGR\n , OGRConduit\n , OGRSource\n , OGRSink\n , runOGR\n\n , openReadOnly\n , openReadWrite\n , create\n , createMem\n , canCreateMultipleGeometryFields\n\n , dataSourceName\n\n , createLayer\n , createLayerWithDef\n\n , getLayer\n , getLayerByName\n\n , sourceLayer\n , sourceLayer_\n , conduitInsertLayer\n , conduitInsertLayer_\n , sinkInsertLayer\n , sinkInsertLayer_\n , sinkUpdateLayer\n\n , executeSQL\n\n , syncLayerToDisk\n , syncToDisk\n\n , layerSpatialFilter\n , setLayerSpatialFilter\n\n , dataSourceLayerCount\n , layerName\n , layerExtent\n , layerFeatureCount\n , layerFeatureDef\n\n , createFeature\n , createFeatureWithFid\n , createFeature_\n , getFeature\n , updateFeature\n , deleteFeature\n\n , unsafeToReadOnlyLayer\n\n , registerAll\n , cleanupAll\n\n , liftOGR\n , closeLayer\n , unDataSource\n , unLayer\n , layerHasCapability\n , driverHasCapability\n , dataSourceHasCapability\n , nullLayerH\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\"#}\n\nimport Data.ByteString.Char8 (ByteString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport Data.Conduit\nimport qualified Data.Conduit.List as CL\nimport Data.Maybe (isNothing, fromMaybe)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.String (IsString)\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector as V\n\nimport Control.Applicative (Applicative, (<$>), (<*>), pure)\nimport Control.Monad (liftM, when, void, (>=>), (<=<))\nimport Control.Monad.Base (MonadBase)\nimport Control.Monad.Catch (\n MonadThrow(..)\n , MonadCatch\n , MonadMask\n , bracket\n , finally\n )\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Trans.Resource (MonadResource)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Foreign.C.String (CString, peekCString, withCString)\nimport Foreign.C.Types (CInt(..), CChar(..), CLong(..))\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\n#endif\nimport Foreign.Ptr (Ptr, nullPtr)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport Foreign.Storable (Storable, peek)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n{#import GDAL.Internal.OSR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.CPLString#}\nimport GDAL.Internal.CPLError\nimport GDAL.Internal.Util\nimport GDAL.Internal.Types\n\n#include \"ogr_api.h\"\n\n{#fun RegisterAll as ^ {} -> `()' #}\n{#fun CleanupAll as ^ {} -> `()' #}\n\n{#pointer OGRSFDriverH as DriverH #}\n\n\n{#pointer DataSourceH newtype#}\nnewtype DataSource s (t::AccessMode) =\n DataSource { unDataSource :: DataSourceH }\n\nderiving instance Eq DataSourceH\n\nnullDataSourceH :: DataSourceH\nnullDataSourceH = DataSourceH nullPtr\n\ntype RODataSource s = DataSource s ReadOnly\ntype RWDataSource s = DataSource s ReadWrite\n\nnewtype OGR s l a = OGR (GDAL s a)\n\nderiving instance Functor (OGR s l)\nderiving instance Applicative (OGR s l)\nderiving instance Monad (OGR s l)\nderiving instance MonadIO (OGR s l)\nderiving instance MonadThrow (OGR s l)\nderiving instance MonadCatch (OGR s l)\nderiving instance MonadMask (OGR s l)\nderiving instance MonadBase IO (OGR s l)\nderiving instance MonadResource (OGR s l)\n\nrunOGR :: (forall l. OGR s l a )-> GDAL s a\nrunOGR (OGR a) = a\n\nliftOGR :: GDAL s a -> OGR s l a\nliftOGR = OGR\n\ntype OGRConduit s l i o = Conduit i (OGR s l) o\ntype OGRSource s l o = Source (OGR s l) o\ntype OGRSink s l i = Sink i (OGR s l)\n\n{#pointer LayerH newtype#}\n\nderiving instance Storable LayerH\nderiving instance Eq LayerH\n\nnullLayerH :: LayerH\nnullLayerH = LayerH nullPtr\n\nnewtype (Layer s l (t::AccessMode) a) = Layer (ReleaseKey, LayerH)\n\nunLayer :: Layer s l t a -> LayerH\nunLayer (Layer (_,l)) = l\n\ncloseLayer :: MonadIO m => Layer s l t a -> m ()\ncloseLayer (Layer (rk,_)) = release rk\n\ntype ROLayer s l = Layer s l ReadOnly\ntype RWLayer s l = Layer s l ReadWrite\n\nunsafeToReadOnlyLayer :: RWLayer s l a -> ROLayer s l a\nunsafeToReadOnlyLayer = coerce\n\n{#enum define OGRAccess\n { FALSE as OGR_ReadOnly\n , TRUE as OGR_Update\n } deriving (Eq, Show) #}\n\n\nopenReadOnly :: String -> GDAL s (RODataSource s)\nopenReadOnly p = openWithMode OGR_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataSource s)\nopenReadWrite p = openWithMode OGR_Update p\n\nopenWithMode :: OGRAccess -> String -> GDAL s (DataSource s t)\nopenWithMode m p =\n newDataSourceHandle $ withCString p $ \\p' ->\n checkGDALCall checkIt ({#call OGROpen as ^#} p' (fromEnumC m) nullPtr)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGROpen\"\n\n\nnewDataSourceHandle\n :: IO DataSourceH -> GDAL s (DataSource s t)\nnewDataSourceHandle act = liftM snd $ allocate alloc free\n where\n alloc = liftM DataSource act\n free ds\n | dsPtr \/= nullDataSourceH = {#call OGR_DS_Destroy as ^#} dsPtr\n | otherwise = return ()\n where dsPtr = unDataSource ds\n\nnewtype Driver =\n Driver ByteString deriving (Eq, IsString, Typeable)\n\ninstance Show Driver where\n show (Driver s) = show s\n\ncreate :: Driver -> String -> OptionList -> GDAL s (RWDataSource s)\ncreate driverName name options = newDataSourceHandle $ do\n pDr <- driverByName driverName\n withCString name $ \\pName ->\n checkGDALCall checkIt\n (withOptionList options $ {#call OGR_Dr_CreateDataSource as ^#} pDr pName)\n where\n checkIt e p' |\u00a0p'==nullDataSourceH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALException CE_Failure OpenFailed \"OGR_Dr_CreateDataSource\"\n\ncreateMem :: OptionList -> GDAL s (RWDataSource s)\ncreateMem = create \"Memory\" \"\"\n\ndriverByName :: Driver -> IO DriverH\ndriverByName (Driver name) = useAsCString name $ \\pName -> do\n drv <- {#call unsafe GetDriverByName as ^#} pName\n if drv == nullPtr\n then throwBindingException (UnknownDriver name)\n else return drv\n\n{#enum define ApproxOK\n { TRUE as ApproxOK\n , FALSE as StrictOK\n } deriving (Eq, Show) #}\n\ncreateLayer\n :: forall s l a. OGRFeatureDef a\n => RWDataSource s -> ApproxOK -> OptionList -> GDAL s (RWLayer s l a)\ncreateLayer ds = createLayerWithDef ds (featureDef (Proxy :: Proxy a))\n\n\n\ncreateLayerWithDef\n :: RWDataSource s -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s l a)\ncreateLayerWithDef ds FeatureDef{..} approxOk options =\n liftM Layer $\n flip allocate (const (return ())) $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList options $ \\pOpts -> do\n pL <- checkGDALCall checkIt $\n {#call OGR_DS_CreateLayer as ^#} pDs pName pSrs gType pOpts\n V.forM_ fdFields $ \\(n,f) -> withFieldDefnH n f $ \\pFld ->\n checkOGRError \"CreateField\" $\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (V.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if SUPPORTS_MULTI_GEOM_FIELDS\n V.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 = unDataSource 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\ngetLayerSchema :: LayerH -> IO FeatureDefnH\ngetLayerSchema = {#call OGR_L_GetLayerDefn as ^#}\n\ncreateFeatureWithFidIO\n :: OGRFeature a => LayerH -> Maybe Fid -> a -> IO (Maybe Fid)\ncreateFeatureWithFidIO pL fid feat = do\n pFd <- getLayerSchema pL\n featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" ({#call OGR_L_CreateFeature as ^#} pL pF)\n getFid pF\n\ncreateFeatureWithFid\n :: OGRFeature a => RWLayer s l a -> Maybe Fid -> a -> GDAL s (Maybe Fid)\ncreateFeatureWithFid layer fid =\n liftIO . createFeatureWithFidIO (unLayer layer) fid\n\ncreateFeature :: OGRFeature a => RWLayer s l a -> a -> GDAL s Fid\ncreateFeature layer =\n createFeatureWithFid layer Nothing >=>\n maybe (throwBindingException UnexpectedNullFid) return\n\ncreateFeature_ :: OGRFeature a => RWLayer s l a -> a -> GDAL s ()\ncreateFeature_ layer = void . createFeatureWithFid layer Nothing\n\nupdateFeature :: OGRFeature a => RWLayer s l a -> Fid -> a -> GDAL s ()\nupdateFeature layer fid feat = liftIO $ do\n pFd <- getLayerSchema pL\n featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} pL\n where pL = unLayer layer\n\ngetFeature :: OGRFeature a => Layer s l t a -> Fid -> GDAL s (Maybe a)\ngetFeature layer (Fid fid) = liftIO $ do\n when (not (pL `layerHasCapability` RandomRead)) $\n throwBindingException (UnsupportedLayerCapability RandomRead)\n fDef <- layerFeatureDefIO pL\n liftM (fmap snd) $ featureFromHandle fDef $\n checkGDALCall checkIt ({#call OGR_L_GetFeature as ^#} pL (fromIntegral fid))\n where\n checkIt (Just GDALException{gdalErrNum=AppDefined}) _ = Nothing\n checkIt e _ = e\n pL = unLayer layer\n\ndeleteFeature :: Layer s l t a -> Fid -> GDAL s ()\ndeleteFeature layer (Fid fid) = liftIO $\n checkOGRError \"DeleteFeature\" $\n {#call OGR_L_DeleteFeature as ^#} (unLayer layer) (fromIntegral fid)\n\ncanCreateMultipleGeometryFields :: Bool\ncanCreateMultipleGeometryFields =\n#if SUPPORTS_MULTI_GEOM_FIELDS\n True\n#else\n False\n#endif\n\nsyncToDisk :: RWDataSource s -> GDAL s ()\nsyncToDisk =\n liftIO .\n checkOGRError \"syncToDisk\" .\n {#call OGR_DS_SyncToDisk as ^#} .\n unDataSource\n\nsyncLayerToDiskIO :: RWLayer s l a -> IO ()\nsyncLayerToDiskIO =\n checkOGRError \"syncLayerToDisk\" . {#call OGR_L_SyncToDisk as ^#} . unLayer\n\nsyncLayerToDisk :: RWLayer s l a -> GDAL s ()\nsyncLayerToDisk = liftIO . syncLayerToDiskIO\n\n\ngetLayer :: Int -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayer ix ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n {#call OGR_DS_GetLayer as ^#} (unDataSource 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\n\ngetLayerByName :: Text -> DataSource s t -> GDAL s (Layer s l t a)\ngetLayerByName name ds =\n liftM Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n useAsEncodedCString name $\n {#call OGR_DS_GetLayerByName as ^#} (unDataSource ds)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerName name)\n\n\nsourceLayer\n :: OGRFeature a\n => GDAL s (Layer s l t a)\n -> OGRSource s l (Maybe Fid, a)\nsourceLayer alloc = layerTransaction alloc' loop\n where\n alloc' = do\n l <- alloc\n liftIO $ {#call OGR_L_ResetReading as ^#} (unLayer l)\n fDef <- layerFeatureDef l\n return (l, fDef)\n\n loop seed = do\n next <- liftIO $\n featureFromHandle (snd seed) $\n {#call OGR_L_GetNextFeature as ^#} (unLayer (fst seed))\n case next of\n Just v -> yield v >> loop seed\n Nothing -> return ()\n\nsourceLayer_\n :: OGRFeature a => GDAL s (Layer s l t a) -> OGRSource s l a\nsourceLayer_ = (=$= (CL.map snd)) . sourceLayer\n\n\nconduitInsertLayer\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l (Maybe Fid, a) (Maybe Fid)\nconduitInsertLayer = flip conduitFromLayer createIt\n where\n createIt (l, pFd) = awaitForever $ \\(fid, feat) -> do\n fid' <- liftIO $ featureToHandle pFd fid feat $ \\pF -> do\n checkOGRError \"CreateFeature\" $\n {#call OGR_L_CreateFeature as ^#} (unLayer l) pF\n getFid pF\n yield fid'\n\nconduitInsertLayer_\n :: OGRFeature a\n => GDAL s (RWLayer s l a) -> OGRConduit s l a (Maybe Fid)\nconduitInsertLayer_ = (CL.map (\\i->(Nothing,i)) =$=) . conduitInsertLayer\n\nsinkInsertLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Maybe Fid, a) ()\nsinkInsertLayer = (=$= CL.sinkNull) . conduitInsertLayer\n\nsinkInsertLayer_\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l a ()\nsinkInsertLayer_ =\n ((=$= CL.sinkNull) . ((CL.map (\\i->(Nothing,i))) =$=)) . conduitInsertLayer\n\nsinkUpdateLayer\n :: OGRFeature a => GDAL s (RWLayer s l a) -> OGRSink s l (Fid, a) ()\nsinkUpdateLayer = flip conduitFromLayer updateIt\n where\n updateIt (l, pFd) = awaitForever $ \\(fid, feat) ->\n liftIO $ featureToHandle pFd (Just fid) feat $\n checkOGRError \"SetFeature\" . {#call OGR_L_SetFeature as ^#} (unLayer l)\n\n\nlayerTransaction\n :: GDAL s (Layer s l t a, e)\n -> ((Layer s l t a, e) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nlayerTransaction alloc inside = do\n alloc' <- lift (liftOGR (unsafeGDALToIO alloc))\n (rbKey, seed) <- allocate alloc' rollback\n liftIO $ checkOGRError \"StartTransaction\" $\n {#call OGR_L_StartTransaction as ^#} (unLayer (fst seed))\n addCleanup (const (release rbKey))\n (inside seed >> liftIO (commit rbKey seed))\n where\n free = closeLayer . fst\n commit rbKey seed = bracket (unprotect rbKey) (const (free seed)) $ \\m -> do\n when (isNothing m) (error \"layerTransaction: this should not happen\")\n checkOGRError \"CommitTransaction\" $\n {#call OGR_L_CommitTransaction as ^#} (unLayer (fst seed))\n checkOGRError \"SyncToDisk\" $\n {#call OGR_L_SyncToDisk as ^#} (unLayer (fst seed))\n\n rollback seed =\n (checkOGRError \"RollbackTransaction\" $\n {#call OGR_L_RollbackTransaction as ^#} (unLayer (fst seed)))\n `finally` free seed\n\n\n\nconduitFromLayer\n :: GDAL s (RWLayer s l a)\n -> ((RWLayer s l a, FeatureDefnH) -> OGRConduit s l i o)\n -> OGRConduit s l i o\nconduitFromLayer alloc = layerTransaction alloc'\n where\n alloc' = do\n l <- alloc\n schema <- liftIO $ getLayerSchema (unLayer l)\n return (l, schema)\n\n\n-- | GDAL < 1.11 only supports 1 geometry field and associates it to the layer\nlayerGeomFieldDef :: LayerH -> IO GeomFieldDef\nlayerGeomFieldDef p =\n GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_L_GetGeomType\tas ^#} p)\n <*> maybeNewSpatialRefBorrowedHandle\n ({#call unsafe OGR_L_GetSpatialRef as ^#} p)\n <*> pure True\n\ndataSourceLayerCount :: DataSource s t -> GDAL s Int\ndataSourceLayerCount = liftM fromIntegral\n . liftIO . {#call OGR_DS_GetLayerCount as ^#} . unDataSource\n\ndataSourceName :: DataSource s t -> GDAL s String\ndataSourceName =\n liftIO . (peekCString <=< {#call OGR_DS_GetName as ^#} . unDataSource)\n\n\ndata SQLDialect\n = DefaultDialect\n | SqliteDialect\n | OGRDialect\n deriving (Eq, Show, Enum)\n\nwithSQLDialect :: SQLDialect -> (CString -> IO a) -> IO a\nwithSQLDialect DefaultDialect = ($ nullPtr)\nwithSQLDialect SqliteDialect = unsafeUseAsCString \"SQLITE\\0\"\nwithSQLDialect OGRDialect = unsafeUseAsCString \"OGRSQL\\0\"\n\nexecuteSQL\n :: OGRFeature a\n => SQLDialect -> Text -> Maybe Geometry -> RODataSource s\n -> GDAL s (ROLayer s l a)\nexecuteSQL dialect query mSpatialFilter ds =\n liftM Layer $ allocate execute freeIfNotNull\n where\n execute =\n checkGDALCall checkit $\n withMaybeGeometry mSpatialFilter $ \\pF ->\n useAsEncodedCString query $ \\pQ ->\n withSQLDialect dialect $ {#call OGR_DS_ExecuteSQL as ^#} pDs pQ pF\n\n freeIfNotNull pL\n | pL \/= nullLayerH = {#call unsafe OGR_DS_ReleaseResultSet as ^#} pDs pL\n | otherwise = return ()\n\n pDs = unDataSource 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\nlayerName :: Layer s l t a -> GDAL s Text\nlayerName =\n liftIO . (peekEncodedCString <=< {#call unsafe OGR_L_GetName as ^#} . unLayer)\n\nlayerExtent :: Layer s l t a -> GDAL s EnvelopeReal\nlayerExtent l = liftIO $ alloca $ \\pE -> do\n checkOGRError \"GetExtent\" ({#call OGR_L_GetExtent as ^#} (unLayer l) pE 1)\n peek pE\n\nlayerFeatureDef :: Layer s l t a -> GDAL s FeatureDef\nlayerFeatureDef = liftIO . layerFeatureDefIO . unLayer\n\nlayerFeatureDefIO :: LayerH -> IO FeatureDef\nlayerFeatureDefIO pL = do\n gfd <- layerGeomFieldDef pL\n getLayerSchema pL >>= featureDefFromHandle gfd\n\nlayerFeatureCount :: Layer s l t a -> Bool -> GDAL s (Maybe Int)\nlayerFeatureCount layer force = liftIO $ do\n c <- liftM fromIntegral $\n {#call OGR_L_GetFeatureCount as ^#} (unLayer layer) (fromBool force)\n if c<0 then return Nothing else return (Just c)\n\nlayerSpatialFilter :: Layer s l t a -> GDAL s (Maybe Geometry)\nlayerSpatialFilter l = liftIO $\n {#call unsafe OGR_L_GetSpatialFilter as ^#} (unLayer l) >>= maybeCloneGeometry\n\nsetLayerSpatialFilter :: Layer s l t a -> Geometry -> GDAL s ()\nsetLayerSpatialFilter l g = liftIO $\n withGeometry g $ {#call unsafe OGR_L_SetSpatialFilter as ^#} (unLayer l)\n\ndriverHasCapability :: DriverH -> DriverCapability -> Bool\ndriverHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_Dr_TestCapability as ^#} d)\n\nlayerHasCapability :: LayerH -> LayerCapability -> Bool\nlayerHasCapability l c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_L_TestCapability as ^#} l)\n\ndataSourceHasCapability :: DataSourceH -> DataSourceCapability -> Bool\ndataSourceHasCapability d c = unsafePerformIO $ do\n withCString (show c)\n (liftM toBool . {#call unsafe OGR_DS_TestCapability as ^#} d)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"50bc51a6c90e0112ba6a506ed518d180e6b6224c","subject":"Switch to using bird tracks for the little example code fragments in the haddock documentation","message":"Switch to using bird tracks for the little example code fragments in 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--\n-- > LT input 1 \n--\n-- | is the current token. Or a negative offset may be specified, where: \n--\n-- > LT input (-1) \n--\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--\n-- > tokenGetAntlrString token\n--\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:\n--\n-- @\n-- LT input 1 \n-- @\n--\n-- | is the current token. Or a negative offset may be specified, where: \n--\n-- @\n-- LT input (-1) \n-- @\n--\n-- | is the previous token.\n--\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--\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--\n-- @\n-- tokenGetAntlrString token\n-- @\n--\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-- @\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-- @\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-- @\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-- @\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-- @\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-- @\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-- @\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-- @\n--\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":"e79f91b3da0a11e3581cf74fc44d37c1545f831b","subject":"add compute resources for maxwell architecture","message":"add compute resources for maxwell architecture\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_file":"Foreign\/CUDA\/Analysis\/Device.chs","new_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n Compute 5 0 -> DeviceResources 32 2048 32 64 128 65536 256 65536 256 4 255 Warp -- Maxwell GM10x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","old_contents":"--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Analysis.Device\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Common device functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Analysis.Device\n (\n Compute(..), ComputeMode(..),\n DeviceProperties(..), DeviceResources(..), Allocation(..), PCI(..),\n deviceResources\n )\n where\n\n#include \"cbits\/stubs.h\"\n\nimport Data.Int\nimport Debug.Trace\n\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum CUcomputemode as ComputeMode\n { underscoreToCase }\n with prefix=\"CU_COMPUTEMODE\" deriving (Eq, Show) #}\n\n-- |\n-- GPU compute capability, major and minor revision number respectively.\n--\ndata Compute = Compute !Int !Int\n deriving Eq\n\ninstance Show Compute where\n show (Compute major minor) = show major ++ \".\" ++ show minor\n\ninstance Ord Compute where\n compare (Compute m1 n1) (Compute m2 n2) =\n case compare m1 m2 of\n EQ -> compare n1 n2\n x -> x\n\n{--\ncap :: Int -> Int -> Double\ncap a 0 = fromIntegral a\ncap a b = let a' = fromIntegral a in\n let b' = fromIntegral b in\n a' + b' \/ max 10 (10^ ((ceiling . logBase 10) b' :: Int))\n--}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: !String, -- ^ Identifier\n computeCapability :: !Compute, -- ^ Supported compute capability\n totalGlobalMem :: !Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: !Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: !Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: !Int, -- ^ 32-bit registers per block\n warpSize :: !Int, -- ^ Warp size in threads (SIMD width)\n maxThreadsPerBlock :: !Int, -- ^ Max number of threads per block\n#if CUDA_VERSION >= 4000\n maxThreadsPerMultiProcessor :: !Int, -- ^ Max number of threads per multiprocessor\n#endif\n maxBlockSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: !(Int,Int,Int), -- ^ Max size of each dimension of a grid\n#if CUDA_VERSION >= 3000\n maxTextureDim1D :: !Int, -- ^ Maximum texture dimensions\n maxTextureDim2D :: !(Int,Int),\n maxTextureDim3D :: !(Int,Int,Int),\n#endif\n clockRate :: !Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: !Int, -- ^ Number of multiprocessors on the device\n memPitch :: !Int64, -- ^ Max pitch in bytes allowed by memory copies\n#if CUDA_VERSION >= 4000\n memBusWidth :: !Int, -- ^ Global memory bus width in bits\n memClockRate :: !Int, -- ^ Peak memory clock frequency in kilohertz\n#endif\n textureAlignment :: !Int64, -- ^ Alignment requirement for textures\n computeMode :: !ComputeMode,\n deviceOverlap :: !Bool, -- ^ Device can concurrently copy memory and execute a kernel\n#if CUDA_VERSION >= 3000\n concurrentKernels :: !Bool, -- ^ Device can possibly execute multiple kernels concurrently\n eccEnabled :: !Bool, -- ^ Device supports and has enabled error correction\n#endif\n#if CUDA_VERSION >= 4000\n asyncEngineCount :: !Int, -- ^ Number of asynchronous engines\n cacheMemL2 :: !Int, -- ^ Size of the L2 cache in bytes\n tccDriverEnabled :: !Bool, -- ^ Whether this is a Tesla device using the TCC driver\n pciInfo :: !PCI, -- ^ PCI device information for the device\n#endif\n kernelExecTimeoutEnabled :: !Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: !Bool, -- ^ As opposed to discrete\n#if CUDA_VERSION >= 4000\n canMapHostMemory :: !Bool, -- ^ Device can use pinned memory\n unifiedAddressing :: !Bool -- ^ Device shares a unified address space with the host\n#else\n canMapHostMemory :: !Bool -- ^ Device can use pinned memory\n#endif\n }\n deriving (Show)\n\n\ndata PCI = PCI\n {\n busID :: !Int, -- ^ PCI bus ID of the device\n deviceID :: !Int, -- ^ PCI device ID\n domainID :: !Int -- ^ PCI domain ID\n }\n deriving (Show)\n\n\n-- GPU Hardware Resources\n--\ndata Allocation = Warp | Block\ndata DeviceResources = DeviceResources\n {\n threadsPerWarp :: !Int, -- ^ Warp size\n threadsPerMP :: !Int, -- ^ Maximum number of in-flight threads on a multiprocessor\n threadBlocksPerMP :: !Int, -- ^ Maximum number of thread blocks resident on a multiprocessor\n warpsPerMP :: !Int, -- ^ Maximum number of in-flight warps per multiprocessor\n coresPerMP :: !Int, -- ^ Number of SIMD arithmetic units per multiprocessor\n sharedMemPerMP :: !Int, -- ^ Total amount of shared memory per multiprocessor (bytes)\n sharedMemAllocUnit :: !Int, -- ^ Shared memory allocation unit size (bytes)\n regFileSize :: !Int, -- ^ Total number of registers in a multiprocessor\n regAllocUnit :: !Int, -- ^ Register allocation unit size\n regAllocWarp :: !Int, -- ^ Register allocation granularity for warps\n regPerThread :: !Int, -- ^ Maximum number of registers per thread\n allocation :: !Allocation -- ^ How multiprocessor resources are divided\n }\n\n\n-- |\n-- Extract some additional hardware resource limitations for a given device.\n--\ndeviceResources :: DeviceProperties -> DeviceResources\ndeviceResources = resources . computeCapability\n where\n -- This is mostly extracted from tables in the CUDA occupancy calculator.\n --\n resources compute = case compute of\n Compute 1 0 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G80\n Compute 1 1 -> DeviceResources 32 768 8 24 8 16384 512 8192 256 2 124 Block -- Tesla G8x\n Compute 1 2 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla G9x\n Compute 1 3 -> DeviceResources 32 1024 8 32 8 16384 512 16384 512 2 124 Block -- Tesla GT200\n Compute 2 0 -> DeviceResources 32 1536 8 48 32 49152 128 32768 64 2 63 Warp -- Fermi GF100\n Compute 2 1 -> DeviceResources 32 1536 8 48 48 49152 128 32768 64 2 63 Warp -- Fermi GF10x\n Compute 3 0 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 63 Warp -- Kepler GK10x\n Compute 3 5 -> DeviceResources 32 2048 16 64 192 49152 256 65536 256 4 255 Warp -- Kepler GK11x\n\n -- Something might have gone wrong, or the library just needs to be\n -- updated for the next generation of hardware, in which case we just want\n -- to pick a sensible default and carry on.\n --\n -- This is slightly dodgy as the warning message is coming from pure code.\n -- However, it should be OK because all library functions run in IO, so it\n -- is likely the user code is as well.\n --\n _ -> trace warning $ resources (Compute 3 0)\n where warning = unlines [ \"*** Warning: unknown CUDA device compute capability: \" ++ show compute\n , \"*** Please submit a bug report at https:\/\/github.com\/tmcdonell\/cuda\/issues\" ]\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"975c7b2f9adb848697c2ccd6739eacce6e14884d","subject":"make it explicit that the runtime version of memset only supports 8-bit values","message":"make it explicit that the runtime version of memset only supports 8-bit values\n\nIgnore-this: 5594b41b17af4e230368e91118d8ee3b\n\ndarcs-hash:20091221104523-dcabc-d149f9b2ed4610863ffc8ee325102872ff1c79bf.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Marshal.chs","new_file":"Foreign\/CUDA\/Runtime\/Marshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Marshal\n-- Copyright : (c) 2009 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 -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n\n -- * Combined Allocation and Marshalling\n newListArray, withListArray,\n\n -- * Utility\n memset\n )\n where\n\n#include \n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Ptr\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\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 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\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--\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{# fun unsafe cudaHostAlloc\n { alloca'- `HostPtr a' hptr*\n , cIntConv `Int64'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n hptr p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free page-locked host memory previously allocated with 'mallecHost'\n--\nfreeHost :: HostPtr a -> IO ()\nfreeHost p = nothingIfOk =<< cudaFreeHost p\n\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--\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{# 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.alloca\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--\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--\nfree :: DevicePtr a -> IO ()\nfree p = nothingIfOk =<< cudaFree p\n\n{# fun unsafe cudaFree\n { dptr `DevicePtr a' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\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 = 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--\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 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 = 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--\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-- 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--\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray xs dptr = F.withArrayLen xs $ \\len p -> pokeArray len p dptr\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--\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{# 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 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--\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 =<< case mst of\n Nothing -> cudaMemcpyAsync dst src bytes kind (Stream 0)\n Just st -> cudaMemcpyAsync dst src bytes kind st\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream' } -> `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 copy operations: firstly from a Haskell list into a\n-- heap-allocated array, and from there into device memory. The array should be\n-- '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 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--\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = bracket (newListArray xs) free\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise device memory to a given 8-bit value\n--\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{# 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 ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Marshal\n-- Copyright : (c) 2009 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 -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n\n -- * Combined Allocation and Marshalling\n newListArray, withListArray,\n\n -- * Utility\n memset\n )\n where\n\n#include \n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Ptr\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\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 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\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--\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{# fun unsafe cudaHostAlloc\n { alloca'- `HostPtr a' hptr*\n , cIntConv `Int64'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n hptr p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free page-locked host memory previously allocated with 'mallecHost'\n--\nfreeHost :: HostPtr a -> IO ()\nfreeHost p = nothingIfOk =<< cudaFreeHost p\n\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--\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{# 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.alloca\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--\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--\nfree :: DevicePtr a -> IO ()\nfree p = nothingIfOk =<< cudaFree p\n\n{# fun unsafe cudaFree\n { dptr `DevicePtr a' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\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 = 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--\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 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 = 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--\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-- 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--\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray xs dptr = F.withArrayLen xs $ \\len p -> pokeArray len p dptr\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--\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{# 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 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--\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 =<< case mst of\n Nothing -> cudaMemcpyAsync dst src bytes kind (Stream 0)\n Just st -> cudaMemcpyAsync dst src bytes kind st\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream' } -> `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 copy operations: firstly from a Haskell list into a\n-- heap-allocated array, and from there into device memory. The array should be\n-- '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 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--\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = bracket (newListArray xs) free\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise device memory to a given 8-bit value\n--\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int -- ^ Value to set for each byte\n -> IO ()\nmemset dptr bytes symbol = nothingIfOk =<< cudaMemset dptr symbol bytes\n\n{# fun unsafe cudaMemset\n { dptr `DevicePtr a'\n , `Int'\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f533a234b83c304a8d24a39c8ffc0abdf87daeb4","subject":"adjust iconLoaded signal","message":"adjust iconLoaded signal\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/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":"5df008ae60b9374dfc903dcffb7087f67fa5677d","subject":"errors","message":"errors\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.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: 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.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\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\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\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-------------------------------------------------------------------------------\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":"686dae8cb85d296a93bcf81e60759beb9c5faea7","subject":"Go nuts with INLINE. Stage the renaming operation a bit better.","message":"Go nuts with INLINE. Stage the renaming operation a bit better.\n","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 ,\tdynamicReOrdering\n ,\tvarIndices\n ,\tbddSize\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\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 )\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\nwithBDD :: BDD -> (Ptr BDD -> IO a) -> IO a\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 groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_DEFAULT) >> 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 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 (MkSubst len fpx fpx') f = unsafePerformIO $\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-- FIXME add an off switch\n----------------------------------------\n\n{#enum Cudd_ReorderingType as CUDDReorderingMethod {} deriving (Eq, Ord, Show)#}\n\nroMap :: [(ReorderingMethod, CUDDReorderingMethod)]\nroMap = [(ReorderSift, CUDD_REORDER_SIFT),\n (ReorderStableWindow3, CUDD_REORDER_WINDOW3)]\n\n-- | Set the dynamic variable ordering heuristic.\ndynamicReOrdering :: ReorderingMethod -> IO ()\ndynamicReOrdering rom =\n case lookup rom roMap of\n Nothing -> error $ \"CUDD.dynamicReOrdering: method not supported: \" ++ show rom\n Just brom ->\n {#call unsafe Cudd_AutodynEnable as _cudd_AutodynEnable#} ddmanager (cFromEnum brom) >> 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","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 ,\tdynamicReOrdering\n ,\tvarIndices\n ,\tbddSize\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\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 )\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\ncFromEnum :: (Integral i, Enum e) => e -> i\ncFromEnum = fromIntegral . fromEnum\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\nwithBDD :: BDD -> (Ptr BDD -> IO a) -> IO a\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 groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_DEFAULT) >> 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 = bddConstant {#call unsafe Cudd_ReadOne as _cudd_ReadOne#}\n false = bddConstant {#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\nbddConstant :: (DDManager -> IO (Ptr BDD)) -> BDD\nbddConstant f = unsafePerformIO $ f ddmanager >>= addBDDnullFinalizer\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\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 data Subst BDD = MkSubst [(BDD, BDD)]\n\n mkSubst = MkSubst\n rename = cudd_rename\n substitute = error \"CUDD substitute\" -- cudd_substitute\n\ninstance BDDOps BDD where\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\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\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\n-- | FIXME: This function is a bit touchier than you'd hope.\n-- The reaons is we use cudd_bddSwapVariables, which in fact swaps variables.\n-- This is not exactly a \"rename\" behaviour.\ncudd_rename :: Subst BDD -> BDD -> BDD\ncudd_rename (MkSubst subst) f = unsafePerformIO $\n withBDD f $ \\fp ->\n allocaArray len $ \\arrayx -> allocaArray len $ \\arrayx' ->\n do zipWithM_ (pokeSubst arrayx arrayx') subst [0..]\n bddp <- {#call unsafe cudd_bddSwapVariables#} ddmanager fp arrayx arrayx' (fromIntegral len)\n mapM_ (\\ (BDD v, BDD v') -> do touchForeignPtr v\n touchForeignPtr v') subst\n addBDDfinalizer bddp\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\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-- FIXME add an off switch\n----------------------------------------\n\n{#enum Cudd_ReorderingType as CUDDReorderingMethod {} deriving (Eq, Ord, Show)#}\n\nroMap :: [(ReorderingMethod, CUDDReorderingMethod)]\nroMap = [(ReorderSift, CUDD_REORDER_SIFT),\n (ReorderStableWindow3, CUDD_REORDER_WINDOW3)]\n\n-- | Set the dynamic variable ordering heuristic.\ndynamicReOrdering :: ReorderingMethod -> IO ()\ndynamicReOrdering rom =\n case lookup rom roMap of\n Nothing -> error $ \"CUDD.dynamicReOrdering: method not supported: \" ++ show rom\n Just brom ->\n {#call unsafe Cudd_AutodynEnable as _cudd_AutodynEnable#} ddmanager (cFromEnum brom) >> 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"1c947e526f60b431b32fa2612b4e57d428cbf4b3","subject":"Image.getChannel was missing proper type","message":"Image.getChannel was missing proper type\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, TypeFamilies #-}\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.ForeignPtr\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\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGBA\ndata 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\nforeign 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 releaseImage 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 releaseImage iptr\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\n getSize = getSize . unS\n\n--loadColorImage 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 1)\n-- bw <- imageTo32F i\n-- return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB Double -> Image LAB Double\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB Double -> Image GrayScale Double\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale Double) where\n type P (Image GrayScale Double) = Double \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB Double) where\n type P (Image RGB Double) = (Double,Double,Double) \n getPixel (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\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\n\nemptyCopy img = 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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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 :: Int -> Image RGB d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 = 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 | x <- [0..u-1] , y <- [0..v-1] \n | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, TypeFamilies #-}\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.ForeignPtr\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\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGBA\ndata 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\nforeign 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 releaseImage 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 releaseImage iptr\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\n getSize = getSize . unS\n\n--loadColorImage 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 1)\n-- bw <- imageTo32F i\n-- return $ Just bw\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB Double -> Image LAB Double\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB Double -> Image GrayScale Double\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale Double) where\n type P (Image GrayScale Double) = Double \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB Double) where\n type P (Image RGB Double) = (Double,Double,Double) \n getPixel (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\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\n\nemptyCopy img = 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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\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\n-- Manipulating regions of interest:\nsetROI (x,y) (w,h) image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\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\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI 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 pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image\n resetROI image\n return x\n\n-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n--setPixel (x,y) v image = withGenImage image $ \\img ->\n-- {#call wrapSet32F2D#} img y x 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 = 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 | x <- [0..u-1] , y <- [0..v-1] \n | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3913859d61fa72b87a8df1deb289e3b3611d8772","subject":"Fixed blit","message":"Fixed blit\n","repos":"BeautifulDestinations\/CV,aleator\/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 #-}\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 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\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\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 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\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 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\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\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 blitImg#} 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 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\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":"31ff35a153c31726814ff5d2a68e5a45e6d1fe00","subject":"Remote","message":"Remote\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Remote.chs","new_file":"src\/haskell\/Data\/HGit2\/Remote.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Remote where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Config\nimport Data.HGit2.Types\nimport Foreign\nimport Foreign.C\n\nnewtype Remote = Remote CPtr\nnewtype HeadArray = HeadArray CPtr\n\ninstance CWrapper Remote where\n unwrap (Remote r) = r\n\ninstance CWrapper HeadArray where\n unwrap (HeadArray a) = a\n\n-- | Get the information for a particular remote\nremote :: Config -> String -> IOEitherErr Remote\nremote (Config cfp) str =\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' ->\n callPeek Remote (\\out -> {#call git_remote_get#} out c str')\n\n-- | Get the remote's name\nremoteName :: Remote -> String\nremoteName (Remote rfp) = unsafePerformIO $\n withForeignPtr rfp $ \\r ->\n peekCString =<< {#call git_remote_name#} r\n\n-- | Get the remote's url\nremoteURL :: Remote -> String\nremoteURL (Remote rfp) = unsafePerformIO $\n withForeignPtr rfp $ \\r ->\n peekCString =<< {#call git_remote_url#} r\n\n-- | Get the fetch refspec\nremoteRefSpec :: Remote -> IO (Maybe RefSpec)\nremoteRefSpec (Remote rfp) =\n withForeignPtr rfp $ \\r -> do\n ptr <- mkFPtr =<< {#call git_remote_fetchspec#} r\n retRes RefSpec ptr\n\n-- | Get the push refspec\npushSpec :: Remote -> IO (Maybe RefSpec)\npushSpec (Remote rfp) =\n withForeignPtr rfp $ \\r -> do\n ptr <- mkFPtr =<< {#call git_remote_pushspec#} r\n retRes RefSpec ptr\n\n-- | Open a connection to a remote\n--\n-- The transport is selected based on the URL\nconnect :: Remote -> Int -> IOCanFail\nconnect (Remote rfp) n =\n withForeignPtr rfp $ \\r ->\n retMaybe =<< {#call git_remote_connect#} r (fromIntegral n)\n\n-- | Get a list of refs at the remote\n--\n-- The remote (or more exactly its transport) must be connected.\nremoteLs :: Remote -> HeadArray -> IOCanFail\nremoteLs (Remote rfp) (HeadArray hfp) =\n withForeignPtr rfp $ \\r ->\n withForeignPtr hfp $ \\h ->\n retMaybe =<< {#call git_remote_ls#} r h\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n\n#include \n\nmodule Data.HGit2.Remote where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Config\nimport Data.HGit2.Types\nimport Foreign\nimport Foreign.C\n\nnewtype Remote = Remote CPtr\nnewtype HeadArray = HeadArray CPtr\n\ninstance CWrapper Remote where\n unwrap (Remote r) = r\n\ninstance CWrapper HeadArray where\n unwrap (HeadArray a) = a\n\n-- | Get the information for a particular remote\nremote :: Config -> String -> IOEitherErr Remote\nremote (Config cfp) str =\n withForeignPtr cfp $ \\c ->\n withCString str $ \\str' ->\n callPeek Remote (\\out -> {#call git_remote_get#} out c str')\n\n-- | Get the remote's name\nremoteName :: Remote -> String\nremoteName = undefined -- unsafePeekStr {#call git_remote_name#}\n\n-- | Get the remote's url\nremoteURL :: Remote -> String\nremoteURL = undefined --unsafePeekStr {#call git_remote_url#}\n\n-- | Get the fetch refspec\nremoteRefSpec :: Remote -> IO (Maybe RefSpec)\nremoteRefSpec (Remote rfp) =\n withForeignPtr rfp $ \\r ->\n undefined\n {- retRes' RefSpec $ {#call git_remote_fetchspec#} r-}\n\n-- | Get the push refspec\npushSpec :: Remote -> IO (Maybe RefSpec)\npushSpec (Remote rfp) =\n withForeignPtr rfp $ \\r ->\n undefined\n {- retRes' RefSpec $ {#call git_remote_pushspec#} r-}\n\n-- | Open a connection to a remote\n--\n-- The transport is selected based on the URL\nconnect :: Remote -> Int -> IOCanFail\nconnect (Remote rfp) n =\n withForeignPtr rfp $ \\r ->\n retMaybe =<< {#call git_remote_connect#} r (fromIntegral n)\n\n-- | Get a list of refs at the remote\n--\n-- The remote (or more exactly its transport) must be connected.\nremoteLs :: Remote -> HeadArray -> IOCanFail\nremoteLs (Remote rfp) (HeadArray hfp) =\n withForeignPtr rfp $ \\r ->\n withForeignPtr hfp $ \\h ->\n retMaybe =<< {#call git_remote_ls#} r h\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"daaa4c72d008b4fae7b3c78c58305dcde59bc2e9","subject":"Add documentation for MRL","message":"Add documentation for MRL\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(..),\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","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.\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":"8e67ca9368168c553087c6bb3a6a1e07e834c4f2","subject":"Fix conflict in Screen, adding the screenGetRGBAColormap function.","message":"Fix conflict in Screen, adding the screenGetRGBAColormap function.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Screen.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Screen.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Screen\n--\n-- Author : Duncan Coutts\n--\n-- Created: 29 October 2007\n--\n-- Copyright (C) 2007 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-- Object representing a physical screen\n--\n-- * Module available since Gdk version 2.2\n--\nmodule Graphics.UI.Gtk.Gdk.Screen (\n\n-- * Detail\n--\n-- | 'Screen' objects are the GDK representation of a physical screen. It is\n-- used throughout GDK and Gtk+ to specify which screen the top level windows\n-- are to be displayed on. It is also used to query the screen specification\n-- and default settings such as the default colormap\n-- ('screenGetDefaultColormap'), the screen width ('screenGetWidth'), etc.\n--\n-- Note that a screen may consist of multiple monitors which are merged to\n-- form a large screen area.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----Screen\n-- @\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- * Types\n Screen,\n ScreenClass,\n castToScreen,\n toScreen,\n\n-- * Methods\n screenGetDefault,\n screenGetSystemColormap,\n#if GTK_CHECK_VERSION(2,8,0)\n screenGetRGBAColormap,\n#endif\n#ifndef DISABLE_DEPRECATED\n screenGetDefaultColormap,\n screenSetDefaultColormap,\n#endif\n\n-- screenGetSystemVisual,\n#if GTK_CHECK_VERSION(2,10,0)\n screenIsComposited,\n#endif\n screenGetRootWindow,\n screenGetDisplay,\n screenGetNumber,\n screenGetWidth,\n screenGetHeight,\n screenGetWidthMm,\n screenGetHeightMm,\n screenGetWidthMM,\n screenGetHeightMM,\n screenListVisuals,\n screenGetToplevelWindows,\n screenMakeDisplayName,\n screenGetNMonitors,\n screenGetMonitorGeometry,\n screenGetMonitorAtPoint,\n screenGetMonitorAtWindow,\n#if GTK_CHECK_VERSION(2,14,0)\n screenGetMonitorHeightMm,\n screenGetMonitorWidthMm,\n screenGetMonitorPlugName,\n#endif\n-- screenGetSetting,\n#if GTK_CHECK_VERSION(2,10,0)\n screenGetActiveWindow,\n screenGetWindowStack,\n#endif\n\n-- * Attributes\n screenFontOptions,\n screenResolution,\n screenDefaultColormap,\n\n-- * Signals\n screenSizeChanged,\n#if GTK_CHECK_VERSION(2,10,0)\n screenCompositedChanged,\n#if GTK_CHECK_VERSION(2,14,0)\n screenMonitorsChanged,\n#endif\n#endif\n\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Signals\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.Signals\nimport Graphics.Rendering.Cairo.Types ( FontOptions(..), mkFontOptions, \n withFontOptions)\nimport Graphics.UI.Gtk.General.Structs ( Rectangle(..) )\n\n{# context lib=\"gdk\" prefix=\"gdk\" #}\n\n#if GTK_CHECK_VERSION(2,2,0)\n--------------------\n-- Methods\n\n-- | Gets the default screen for the default display. (See\n-- 'displayGetDefault').\n--\nscreenGetDefault ::\n IO (Maybe Screen) -- ^ returns a 'Screen', or @Nothing@ if there is no\n -- default display.\nscreenGetDefault =\n maybeNull (makeNewGObject mkScreen) $\n {# call gdk_screen_get_default #}\n\nscreenGetDefaultColormap :: Screen\n -> IO Colormap -- ^ returns the default 'Colormap'.\nscreenGetDefaultColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_default_colormap #}\n self\n{-# DEPRECATED screenGetDefaultColormap \"instead of 'screenGetDefaultColormap obj' use 'get obj screenDefaultColormap'\" #-}\n\nscreenSetDefaultColormap :: Screen\n -> Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nscreenSetDefaultColormap self colormap =\n {# call gdk_screen_set_default_colormap #}\n self\n colormap\n{-# DEPRECATED screenSetDefaultColormap \"instead of 'screenSetDefaultColormap obj value' use 'set obj [ screenDefaultColormap := value ]'\" #-}\n\n-- | Gets the system default colormap for @screen@\n--\nscreenGetSystemColormap :: Screen\n -> IO Colormap -- ^ returns the default colormap for @screen@.\nscreenGetSystemColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_system_colormap #}\n self\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- | Gets a colormap to use for creating windows or pixmaps with an alpha\n-- channel. The windowing system on which Gtk+ is running may not support this\n-- capability, in which case @Nothing@ will be returned. Even if a\n-- non-@Nothing@ value is returned, its possible that the window's alpha\n-- channel won't be honored when displaying the window on the screen: in\n-- particular, for X an appropriate windowing manager and compositing manager\n-- must be running to provide appropriate display.\n--\n-- * Available since Gdk version 2.8\n--\nscreenGetRGBAColormap :: Screen\n -> IO (Maybe Colormap) -- ^ returns a colormap to use for windows with an\n -- alpha channel or @Nothing@ if the capability is not\n -- available.\nscreenGetRGBAColormap self =\n maybeNull (makeNewGObject mkColormap) $\n {# call gdk_screen_get_rgba_colormap #}\n self\n#endif\n\n-- | Get the system's default visual for @screen@. This is the visual for the\n-- root window of the display.\n--\nscreenGetSystemVisual :: Screen\n -> IO Visual -- ^ returns the system visual\nscreenGetSystemVisual self =\n makeNewGObject mkVisual $\n {# call gdk_screen_get_system_visual #}\n self\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns whether windows with an RGBA visual can reasonably be expected to\n-- have their alpha channel drawn correctly on the screen.\n--\n-- On X11 this function returns whether a compositing manager is compositing\n-- @screen@.\n--\n-- * Available since Gdk version 2.10\n--\nscreenIsComposited :: Screen\n -> IO Bool -- ^ returns Whether windows with RGBA visuals can reasonably be\n -- expected to have their alpha channels drawn correctly on the\n -- screen.\nscreenIsComposited self =\n liftM toBool $\n {# call gdk_screen_is_composited #}\n self\n#endif\n\n-- | Gets the root window of @screen@.\n--\nscreenGetRootWindow :: Screen\n -> IO DrawWindow -- ^ returns the root window\nscreenGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gdk_screen_get_root_window #}\n self\n\n-- | Gets the display to which the @screen@ belongs.\n--\nscreenGetDisplay :: Screen\n -> IO Display -- ^ returns the display to which @screen@ belongs\nscreenGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gdk_screen_get_display #}\n self\n\n-- | Gets the index of @screen@ among the screens in the display to which it\n-- belongs. (See 'screenGetDisplay')\n--\nscreenGetNumber :: Screen\n -> IO Int -- ^ returns the index\nscreenGetNumber self =\n liftM fromIntegral $\n {# call gdk_screen_get_number #}\n self\n\n-- | Gets the width of @screen@ in pixels\n--\nscreenGetWidth :: Screen\n -> IO Int -- ^ returns the width of @screen@ in pixels.\nscreenGetWidth self =\n liftM fromIntegral $\n {# call gdk_screen_get_width #}\n self\n\n-- | Gets the height of @screen@ in pixels\n--\nscreenGetHeight :: Screen\n -> IO Int -- ^ returns the height of @screen@ in pixels.\nscreenGetHeight self =\n liftM fromIntegral $\n {# call gdk_screen_get_height #}\n self\n\n-- | Gets the width of @screen@ in millimeters. Note that on some X servers\n-- this value will not be correct.\n--\nscreenGetWidthMM :: Screen\n -> IO Int -- ^ returns the width of @screen@ in millimeters.\nscreenGetWidthMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_width_mm #}\n self\n\nscreenGetWidthMm = screenGetWidthMM\n\n-- | Returns the height of @screen@ in millimeters. Note that on some X\n-- servers this value will not be correct.\n--\nscreenGetHeightMM :: Screen\n -> IO Int -- ^ returns the heigth of @screen@ in millimeters.\nscreenGetHeightMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_height_mm #}\n self\n\nscreenGetHeightMm = screenGetHeightMM\n\n-- | Lists the available visuals for the specified @screen@. A visual\n-- describes a hardware image data format. For example, a visual might support\n-- 24-bit color, or 8-bit color, and might expect pixels to be in a certain\n-- format.\n--\nscreenListVisuals :: Screen\n -> IO [Visual] -- ^ returns a list of visuals\nscreenListVisuals self =\n {# call gdk_screen_list_visuals #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkVisual . return)\n\n\n-- | Obtains a list of all toplevel windows known to GDK on the screen\n-- @screen@. A toplevel window is a child of the root window (see\n-- 'getDefaultRootWindow').\n--\nscreenGetToplevelWindows :: Screen\n -> IO [DrawWindow] -- ^ returns list of toplevel windows\nscreenGetToplevelWindows self =\n {# call gdk_screen_get_toplevel_windows #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkDrawWindow . return)\n\n\n-- | Determines the name to pass to 'displayOpen' to get a 'Display' with this\n-- screen as the default screen.\n--\nscreenMakeDisplayName :: Screen\n -> IO String -- ^ returns a newly allocated string\nscreenMakeDisplayName self =\n {# call gdk_screen_make_display_name #}\n self\n >>= readUTFString\n\n-- | Returns the number of monitors which @screen@ consists of.\n--\nscreenGetNMonitors :: Screen\n -> IO Int -- ^ returns number of monitors which @screen@ consists of.\nscreenGetNMonitors self =\n liftM fromIntegral $\n {# call gdk_screen_get_n_monitors #}\n self\n\n-- | Retrieves the 'Rectangle' representing the size and\n-- position of the individual monitor within the entire screen area.\n--\n-- Note that the size of the entire screen area can be retrieved via\n-- 'screenGetWidth' and 'screenGetHeight'.\n--\nscreenGetMonitorGeometry :: Screen\n -> Int -- ^ @monitorNum@ - the monitor number.\n -> IO Rectangle\nscreenGetMonitorGeometry self monitorNum =\n alloca $ \\rPtr -> do\n {# call gdk_screen_get_monitor_geometry #}\n self\n (fromIntegral monitorNum)\n (castPtr rPtr)\n peek rPtr\n\n-- | Returns the monitor number in which the point (@x@,@y@) is located.\n--\nscreenGetMonitorAtPoint :: Screen\n -> Int -- ^ @x@ - the x coordinate in the virtual screen.\n -> Int -- ^ @y@ - the y coordinate in the virtual screen.\n -> IO Int -- ^ returns the monitor number in which the point (@x@,@y@) lies,\n -- or a monitor close to (@x@,@y@) if the point is not in any\n -- monitor.\nscreenGetMonitorAtPoint self x y =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_point #}\n self\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Returns the number of the monitor in which the largest area of the\n-- bounding rectangle of @window@ resides.\n--\nscreenGetMonitorAtWindow :: Screen\n -> DrawWindow -- ^ @window@ - a 'DrawWindow'\n -> IO Int -- ^ returns the monitor number in which most of @window@ is\n -- located, or if @window@ does not intersect any monitors, a\n -- monitor, close to @window@.\nscreenGetMonitorAtWindow self window =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_window #}\n self\n window\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Gets the height in millimeters of the specified monitor.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorHeightMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the height of the monitor, or -1 if not available\nscreenGetMonitorHeightMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_height_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Gets the width in millimeters of the specified monitor, if available.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorWidthMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the width of the monitor, or -1 if not available\nscreenGetMonitorWidthMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_width_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Returns the output name of the specified monitor. Usually something like\n-- VGA, DVI, or TV, not the actual product name of the display device.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorPlugName :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO (Maybe String) -- ^ returns a newly-allocated string containing the name of the\n -- monitor, or @Nothing@ if the name cannot be determined\nscreenGetMonitorPlugName self monitorNum = do\n sPtr <-\n {# call gdk_screen_get_monitor_plug_name #}\n self\n (fromIntegral monitorNum)\n if sPtr==nullPtr then return Nothing else liftM Just $ readUTFString sPtr\n#endif\n\n{-\n-- | Retrieves a desktop-wide setting such as double-click time for the\n-- 'Screen'@screen@.\n--\n-- FIXME needs a list of valid settings here, or a link to more information.\n--\nscreenGetSetting :: Screen\n -> String -- ^ @name@ - the name of the setting\n -> {-GValue*-} -- ^ @value@ - location to store the value of the setting\n -> IO Bool -- ^ returns @True@ if the setting existed and a value was\n -- stored in @value@, @False@ otherwise.\nscreenGetSetting self name value =\n liftM toBool $\n withUTFString name $ \\namePtr ->\n {# call gdk_screen_get_setting #}\n self\n namePtr\n {-value-}\n-}\n\n-- these are only used for the attributes\nscreenGetFontOptions :: Screen\n -> IO (Maybe FontOptions)\nscreenGetFontOptions self = do\n fPtr <- {# call gdk_screen_get_font_options #} self\n if fPtr==nullPtr then return Nothing else liftM Just $ mkFontOptions (castPtr fPtr)\n\nscreenSetFontOptions :: Screen\n -> Maybe FontOptions\n -> IO ()\nscreenSetFontOptions self Nothing =\n {# call gdk_screen_set_font_options #} self nullPtr\nscreenSetFontOptions self (Just options) =\n withFontOptions options $ \\fPtr ->\n {# call gdk_screen_set_font_options #} self (castPtr fPtr)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the currently active window of this screen.\n--\n-- On X11, this is done by inspecting the _NET_ACTIVE_WINDOW property on the\n-- root window, as described in the Extended Window Manager Hints. If there is\n-- no currently currently active window, or the window manager does not support\n-- the _NET_ACTIVE_WINDOW hint, this function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether\n-- it is implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetActiveWindow :: Screen\n -> IO (Maybe DrawWindow) -- ^ returns the currently active window, or\n -- @Nothing@.\nscreenGetActiveWindow self =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call gdk_screen_get_active_window #}\n self\n#endif\n\n-- | Returns a list of 'DrawWindow's representing the\n-- current window stack.\n--\n-- On X11, this is done by inspecting the _NET_CLIENT_LIST_STACKING property\n-- on the root window, as described in the Extended Window Manager Hints. If\n-- the window manager does not support the _NET_CLIENT_LIST_STACKING hint, this\n-- function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether it is\n-- implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetWindowStack :: Screen\n -> IO (Maybe [DrawWindow]) -- ^ returns a list of 'DrawWindow's for the\n -- current window stack, or @Nothing@.\nscreenGetWindowStack self = do\n lPtr <- {# call gdk_screen_get_window_stack #} self\n if lPtr==nullPtr then return Nothing else liftM Just $ do\n fromGList lPtr >>= mapM (constructNewGObject mkDrawWindow . return)\n#endif\n\n--------------------\n-- Attributes\n\n-- | The default font options for the screen.\n--\nscreenFontOptions :: Attr Screen (Maybe FontOptions)\nscreenFontOptions = newAttr\n screenGetFontOptions\n screenSetFontOptions\n\n-- | The resolution for fonts on the screen.\n--\n-- Default value: -1\n--\nscreenResolution :: Attr Screen Double\nscreenResolution = newAttrFromDoubleProperty \"resolution\"\n\n-- | Sets the default @colormap@ for @screen@.\n--\n-- Gets the default colormap for @screen@.\n--\nscreenDefaultColormap :: Attr Screen Colormap\nscreenDefaultColormap = newAttr\n screenGetDefaultColormap\n screenSetDefaultColormap\n\n--------------------\n-- Signals\n\n-- | The ::size_changed signal is emitted when the pixel width or height of a\n-- screen changes.\n--\nscreenSizeChanged :: ScreenClass self => Signal self (IO ())\nscreenSizeChanged = Signal (connect_NONE__NONE \"size_changed\")\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | The 'screenCompositedChanged' signal is emitted when the composited status of\n-- the screen changes\n--\n-- * Available since Gdk version 2.10\n--\nscreenCompositedChanged :: ScreenClass self => Signal self (IO ())\nscreenCompositedChanged = Signal (connect_NONE__NONE \"composited_changed\")\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | The 'screenMonitorsChanged' signal is emitted when the number, size or\n-- position of the monitors attached to the screen change.\n--\n-- Only for X for now. Future implementations for Win32 and OS X may be a\n-- possibility.\n--\n-- * Available since Gdk version 2.14\n--\nscreenMonitorsChanged :: ScreenClass self => Signal self (IO ())\nscreenMonitorsChanged = Signal (connect_NONE__NONE \"monitors-changed\")\n#endif\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Screen\n--\n-- Author : Duncan Coutts\n--\n-- Created: 29 October 2007\n--\n-- Copyright (C) 2007 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-- Object representing a physical screen\n--\n-- * Module available since Gdk version 2.2\n--\nmodule Graphics.UI.Gtk.Gdk.Screen (\n\n-- * Detail\n--\n-- | 'Screen' objects are the GDK representation of a physical screen. It is\n-- used throughout GDK and Gtk+ to specify which screen the top level windows\n-- are to be displayed on. It is also used to query the screen specification\n-- and default settings such as the default colormap\n-- ('screenGetDefaultColormap'), the screen width ('screenGetWidth'), etc.\n--\n-- Note that a screen may consist of multiple monitors which are merged to\n-- form a large screen area.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----Screen\n-- @\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- * Types\n Screen,\n ScreenClass,\n castToScreen,\n toScreen,\n\n-- * Methods\n screenGetDefault,\n screenGetSystemColormap,\n-- screenGetSystemVisual,\n#if GTK_CHECK_VERSION(2,10,0)\n screenIsComposited,\n#endif\n screenGetRootWindow,\n screenGetDisplay,\n screenGetNumber,\n screenGetWidth,\n screenGetHeight,\n screenGetWidthMm,\n screenGetHeightMm,\n screenGetWidthMM,\n screenGetHeightMM,\n screenListVisuals,\n screenGetToplevelWindows,\n screenMakeDisplayName,\n screenGetNMonitors,\n screenGetMonitorGeometry,\n screenGetMonitorAtPoint,\n screenGetMonitorAtWindow,\n#if GTK_CHECK_VERSION(2,14,0)\n screenGetMonitorHeightMm,\n screenGetMonitorWidthMm,\n screenGetMonitorPlugName,\n#endif\n-- screenGetSetting,\n#if GTK_CHECK_VERSION(2,10,0)\n screenGetActiveWindow,\n screenGetWindowStack,\n#endif\n\n-- * Attributes\n screenFontOptions,\n screenResolution,\n screenDefaultColormap,\n\n-- * Signals\n screenSizeChanged,\n#if GTK_CHECK_VERSION(2,10,0)\n screenCompositedChanged,\n#if GTK_CHECK_VERSION(2,14,0)\n screenMonitorsChanged,\n#endif\n#endif\n\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Signals\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GList\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.Signals\nimport Graphics.Rendering.Cairo.Types ( FontOptions(..), mkFontOptions, \n withFontOptions)\nimport Graphics.UI.Gtk.General.Structs ( Rectangle(..) )\n\n{# context lib=\"gdk\" prefix=\"gdk\" #}\n\n#if GTK_CHECK_VERSION(2,2,0)\n--------------------\n-- Methods\n\n-- | Gets the default screen for the default display. (See\n-- 'displayGetDefault').\n--\nscreenGetDefault ::\n IO (Maybe Screen) -- ^ returns a 'Screen', or @Nothing@ if there is no\n -- default display.\nscreenGetDefault =\n maybeNull (makeNewGObject mkScreen) $\n {# call gdk_screen_get_default #}\n\nscreenGetDefaultColormap :: Screen\n -> IO Colormap -- ^ returns the default 'Colormap'.\nscreenGetDefaultColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_default_colormap #}\n self\n{-# DEPRECATED screenGetDefaultColormap \"instead of 'screenGetDefaultColormap obj' use 'get obj screenDefaultColormap'\" #-}\n\nscreenSetDefaultColormap :: Screen\n -> Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nscreenSetDefaultColormap self colormap =\n {# call gdk_screen_set_default_colormap #}\n self\n colormap\n{-# DEPRECATED screenSetDefaultColormap \"instead of 'screenSetDefaultColormap obj value' use 'set obj [ screenDefaultColormap := value ]'\" #-}\n\n-- | Gets the system default colormap for @screen@\n--\nscreenGetSystemColormap :: Screen\n -> IO Colormap -- ^ returns the default colormap for @screen@.\nscreenGetSystemColormap self =\n makeNewGObject mkColormap $\n {# call gdk_screen_get_system_colormap #}\n self\n\n-- | Get the system's default visual for @screen@. This is the visual for the\n-- root window of the display.\n--\nscreenGetSystemVisual :: Screen\n -> IO Visual -- ^ returns the system visual\nscreenGetSystemVisual self =\n makeNewGObject mkVisual $\n {# call gdk_screen_get_system_visual #}\n self\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns whether windows with an RGBA visual can reasonably be expected to\n-- have their alpha channel drawn correctly on the screen.\n--\n-- On X11 this function returns whether a compositing manager is compositing\n-- @screen@.\n--\n-- * Available since Gdk version 2.10\n--\nscreenIsComposited :: Screen\n -> IO Bool -- ^ returns Whether windows with RGBA visuals can reasonably be\n -- expected to have their alpha channels drawn correctly on the\n -- screen.\nscreenIsComposited self =\n liftM toBool $\n {# call gdk_screen_is_composited #}\n self\n#endif\n\n-- | Gets the root window of @screen@.\n--\nscreenGetRootWindow :: Screen\n -> IO DrawWindow -- ^ returns the root window\nscreenGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gdk_screen_get_root_window #}\n self\n\n-- | Gets the display to which the @screen@ belongs.\n--\nscreenGetDisplay :: Screen\n -> IO Display -- ^ returns the display to which @screen@ belongs\nscreenGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gdk_screen_get_display #}\n self\n\n-- | Gets the index of @screen@ among the screens in the display to which it\n-- belongs. (See 'screenGetDisplay')\n--\nscreenGetNumber :: Screen\n -> IO Int -- ^ returns the index\nscreenGetNumber self =\n liftM fromIntegral $\n {# call gdk_screen_get_number #}\n self\n\n-- | Gets the width of @screen@ in pixels\n--\nscreenGetWidth :: Screen\n -> IO Int -- ^ returns the width of @screen@ in pixels.\nscreenGetWidth self =\n liftM fromIntegral $\n {# call gdk_screen_get_width #}\n self\n\n-- | Gets the height of @screen@ in pixels\n--\nscreenGetHeight :: Screen\n -> IO Int -- ^ returns the height of @screen@ in pixels.\nscreenGetHeight self =\n liftM fromIntegral $\n {# call gdk_screen_get_height #}\n self\n\n-- | Gets the width of @screen@ in millimeters. Note that on some X servers\n-- this value will not be correct.\n--\nscreenGetWidthMM :: Screen\n -> IO Int -- ^ returns the width of @screen@ in millimeters.\nscreenGetWidthMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_width_mm #}\n self\n\nscreenGetWidthMm = screenGetWidthMM\n\n-- | Returns the height of @screen@ in millimeters. Note that on some X\n-- servers this value will not be correct.\n--\nscreenGetHeightMM :: Screen\n -> IO Int -- ^ returns the heigth of @screen@ in millimeters.\nscreenGetHeightMM self =\n liftM fromIntegral $\n {# call gdk_screen_get_height_mm #}\n self\n\nscreenGetHeightMm = screenGetHeightMM\n\n-- | Lists the available visuals for the specified @screen@. A visual\n-- describes a hardware image data format. For example, a visual might support\n-- 24-bit color, or 8-bit color, and might expect pixels to be in a certain\n-- format.\n--\nscreenListVisuals :: Screen\n -> IO [Visual] -- ^ returns a list of visuals\nscreenListVisuals self =\n {# call gdk_screen_list_visuals #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkVisual . return)\n\n\n-- | Obtains a list of all toplevel windows known to GDK on the screen\n-- @screen@. A toplevel window is a child of the root window (see\n-- 'getDefaultRootWindow').\n--\nscreenGetToplevelWindows :: Screen\n -> IO [DrawWindow] -- ^ returns list of toplevel windows\nscreenGetToplevelWindows self =\n {# call gdk_screen_get_toplevel_windows #}\n self\n >>= fromGList\n >>= mapM (makeNewGObject mkDrawWindow . return)\n\n\n-- | Determines the name to pass to 'displayOpen' to get a 'Display' with this\n-- screen as the default screen.\n--\nscreenMakeDisplayName :: Screen\n -> IO String -- ^ returns a newly allocated string\nscreenMakeDisplayName self =\n {# call gdk_screen_make_display_name #}\n self\n >>= readUTFString\n\n-- | Returns the number of monitors which @screen@ consists of.\n--\nscreenGetNMonitors :: Screen\n -> IO Int -- ^ returns number of monitors which @screen@ consists of.\nscreenGetNMonitors self =\n liftM fromIntegral $\n {# call gdk_screen_get_n_monitors #}\n self\n\n-- | Retrieves the 'Rectangle' representing the size and\n-- position of the individual monitor within the entire screen area.\n--\n-- Note that the size of the entire screen area can be retrieved via\n-- 'screenGetWidth' and 'screenGetHeight'.\n--\nscreenGetMonitorGeometry :: Screen\n -> Int -- ^ @monitorNum@ - the monitor number.\n -> IO Rectangle\nscreenGetMonitorGeometry self monitorNum =\n alloca $ \\rPtr -> do\n {# call gdk_screen_get_monitor_geometry #}\n self\n (fromIntegral monitorNum)\n (castPtr rPtr)\n peek rPtr\n\n-- | Returns the monitor number in which the point (@x@,@y@) is located.\n--\nscreenGetMonitorAtPoint :: Screen\n -> Int -- ^ @x@ - the x coordinate in the virtual screen.\n -> Int -- ^ @y@ - the y coordinate in the virtual screen.\n -> IO Int -- ^ returns the monitor number in which the point (@x@,@y@) lies,\n -- or a monitor close to (@x@,@y@) if the point is not in any\n -- monitor.\nscreenGetMonitorAtPoint self x y =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_point #}\n self\n (fromIntegral x)\n (fromIntegral y)\n\n-- | Returns the number of the monitor in which the largest area of the\n-- bounding rectangle of @window@ resides.\n--\nscreenGetMonitorAtWindow :: Screen\n -> DrawWindow -- ^ @window@ - a 'DrawWindow'\n -> IO Int -- ^ returns the monitor number in which most of @window@ is\n -- located, or if @window@ does not intersect any monitors, a\n -- monitor, close to @window@.\nscreenGetMonitorAtWindow self window =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_at_window #}\n self\n window\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Gets the height in millimeters of the specified monitor.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorHeightMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the height of the monitor, or -1 if not available\nscreenGetMonitorHeightMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_height_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Gets the width in millimeters of the specified monitor, if available.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorWidthMm :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO Int -- ^ returns the width of the monitor, or -1 if not available\nscreenGetMonitorWidthMm self monitorNum =\n liftM fromIntegral $\n {# call gdk_screen_get_monitor_width_mm #}\n self\n (fromIntegral monitorNum)\n\n-- | Returns the output name of the specified monitor. Usually something like\n-- VGA, DVI, or TV, not the actual product name of the display device.\n--\n-- * Available since Gdk version 2.14\n--\nscreenGetMonitorPlugName :: Screen\n -> Int -- ^ @monitorNum@ - number of the monitor\n -> IO (Maybe String) -- ^ returns a newly-allocated string containing the name of the\n -- monitor, or @Nothing@ if the name cannot be determined\nscreenGetMonitorPlugName self monitorNum = do\n sPtr <-\n {# call gdk_screen_get_monitor_plug_name #}\n self\n (fromIntegral monitorNum)\n if sPtr==nullPtr then return Nothing else liftM Just $ readUTFString sPtr\n#endif\n\n{-\n-- | Retrieves a desktop-wide setting such as double-click time for the\n-- 'Screen'@screen@.\n--\n-- FIXME needs a list of valid settings here, or a link to more information.\n--\nscreenGetSetting :: Screen\n -> String -- ^ @name@ - the name of the setting\n -> {-GValue*-} -- ^ @value@ - location to store the value of the setting\n -> IO Bool -- ^ returns @True@ if the setting existed and a value was\n -- stored in @value@, @False@ otherwise.\nscreenGetSetting self name value =\n liftM toBool $\n withUTFString name $ \\namePtr ->\n {# call gdk_screen_get_setting #}\n self\n namePtr\n {-value-}\n-}\n\n-- these are only used for the attributes\nscreenGetFontOptions :: Screen\n -> IO (Maybe FontOptions)\nscreenGetFontOptions self = do\n fPtr <- {# call gdk_screen_get_font_options #} self\n if fPtr==nullPtr then return Nothing else liftM Just $ mkFontOptions (castPtr fPtr)\n\nscreenSetFontOptions :: Screen\n -> Maybe FontOptions\n -> IO ()\nscreenSetFontOptions self Nothing =\n {# call gdk_screen_set_font_options #} self nullPtr\nscreenSetFontOptions self (Just options) =\n withFontOptions options $ \\fPtr ->\n {# call gdk_screen_set_font_options #} self (castPtr fPtr)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | Returns the currently active window of this screen.\n--\n-- On X11, this is done by inspecting the _NET_ACTIVE_WINDOW property on the\n-- root window, as described in the Extended Window Manager Hints. If there is\n-- no currently currently active window, or the window manager does not support\n-- the _NET_ACTIVE_WINDOW hint, this function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether\n-- it is implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetActiveWindow :: Screen\n -> IO (Maybe DrawWindow) -- ^ returns the currently active window, or\n -- @Nothing@.\nscreenGetActiveWindow self =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call gdk_screen_get_active_window #}\n self\n#endif\n\n-- | Returns a list of 'DrawWindow's representing the\n-- current window stack.\n--\n-- On X11, this is done by inspecting the _NET_CLIENT_LIST_STACKING property\n-- on the root window, as described in the Extended Window Manager Hints. If\n-- the window manager does not support the _NET_CLIENT_LIST_STACKING hint, this\n-- function returns @Nothing@.\n--\n-- On other platforms, this function may return @Nothing@, depending on whether it is\n-- implementable on that platform.\n--\n-- * Available since Gdk version 2.10\n--\nscreenGetWindowStack :: Screen\n -> IO (Maybe [DrawWindow]) -- ^ returns a list of 'DrawWindow's for the\n -- current window stack, or @Nothing@.\nscreenGetWindowStack self = do\n lPtr <- {# call gdk_screen_get_window_stack #} self\n if lPtr==nullPtr then return Nothing else liftM Just $ do\n fromGList lPtr >>= mapM (constructNewGObject mkDrawWindow . return)\n#endif\n\n--------------------\n-- Attributes\n\n-- | The default font options for the screen.\n--\nscreenFontOptions :: Attr Screen (Maybe FontOptions)\nscreenFontOptions = newAttr\n screenGetFontOptions\n screenSetFontOptions\n\n-- | The resolution for fonts on the screen.\n--\n-- Default value: -1\n--\nscreenResolution :: Attr Screen Double\nscreenResolution = newAttrFromDoubleProperty \"resolution\"\n\n-- | Sets the default @colormap@ for @screen@.\n--\n-- Gets the default colormap for @screen@.\n--\nscreenDefaultColormap :: Attr Screen Colormap\nscreenDefaultColormap = newAttr\n screenGetDefaultColormap\n screenSetDefaultColormap\n\n--------------------\n-- Signals\n\n-- | The ::size_changed signal is emitted when the pixel width or height of a\n-- screen changes.\n--\nscreenSizeChanged :: ScreenClass self => Signal self (IO ())\nscreenSizeChanged = Signal (connect_NONE__NONE \"size_changed\")\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- | The 'screenCompositedChanged' signal is emitted when the composited status of\n-- the screen changes\n--\n-- * Available since Gdk version 2.10\n--\nscreenCompositedChanged :: ScreenClass self => Signal self (IO ())\nscreenCompositedChanged = Signal (connect_NONE__NONE \"composited_changed\")\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- | The 'screenMonitorsChanged' signal is emitted when the number, size or\n-- position of the monitors attached to the screen change.\n--\n-- Only for X for now. Future implementations for Win32 and OS X may be a\n-- possibility.\n--\n-- * Available since Gdk version 2.14\n--\nscreenMonitorsChanged :: ScreenClass self => Signal self (IO ())\nscreenMonitorsChanged = Signal (connect_NONE__NONE \"monitors-changed\")\n#endif\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"13509eca0a3ddc2171a3b4232b7abb0321bb022d","subject":"[project @ 2003-11-03 14:21:54 by juhp] Emacs file variables only work on the first line.","message":"[project @ 2003-11-03 14:21:54 by juhp]\nEmacs file variables only work on the first line.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/multiline\/TextIter.chs","new_file":"gtk\/multiline\/TextIter.chs","new_contents":"{-# OPTIONS -cpp #-} -- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter TextBuffer@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.11 $ from $Date: 2003\/11\/03 14:21:54 $\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-- @ref data 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 @ref data 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 FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (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 (text_iter_free iterPtr)\n\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall unsafe \">k_text_iter_free\"\n text_iter_free' :: FinalizerPtr TextIter\n\ntext_iter_free :: Ptr TextIter -> FinalizerPtr TextIter\ntext_iter_free _ = text_iter_free'\n\n#elif __GLASGOW_HASKELL__>=504\n\nforeign import ccall unsafe \"gtk_text_iter_free\"\n text_iter_free :: Ptr TextIter -> IO ()\n\n#else\n\nforeign import ccall \"gtk_text_iter_free\" unsafe\n text_iter_free :: Ptr TextIter -> IO ()\n\n#endif\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 (text_iter_free iterPtr)\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 (text_iter_free 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref data Pixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe Pixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (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-- @method textIterGetAttributes@ Get the text attributes at the iterator.\n--\n-- * The @ref arg ta@ argument gives the default values if no specific \n-- attributes are set at that specific location.\n--\n-- * The function returns @literal Nothing@ if the text at the iterator has \n-- the same attributes.\ntextIterGetAttributes = undefined\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\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall \"wrapper\" mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#else\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#endif\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 $ withUTFString 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 $ withUTFString 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":"{-# OPTIONS -cpp #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter TextBuffer@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.10 $ from $Date: 2003\/10\/21 21:28:53 $\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-- @ref data 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 @ref data 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 FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (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 (text_iter_free iterPtr)\n\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall unsafe \">k_text_iter_free\"\n text_iter_free' :: FinalizerPtr TextIter\n\ntext_iter_free :: Ptr TextIter -> FinalizerPtr TextIter\ntext_iter_free _ = text_iter_free'\n\n#elif __GLASGOW_HASKELL__>=504\n\nforeign import ccall unsafe \"gtk_text_iter_free\"\n text_iter_free :: Ptr TextIter -> IO ()\n\n#else\n\nforeign import ccall \"gtk_text_iter_free\" unsafe\n text_iter_free :: Ptr TextIter -> IO ()\n\n#endif\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 (text_iter_free iterPtr)\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 (text_iter_free 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref data Pixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe Pixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (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-- @method textIterGetAttributes@ Get the text attributes at the iterator.\n--\n-- * The @ref arg ta@ argument gives the default values if no specific \n-- attributes are set at that specific location.\n--\n-- * The function returns @literal Nothing@ if the text at the iterator has \n-- the same attributes.\ntextIterGetAttributes = undefined\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\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall \"wrapper\" mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#else\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#endif\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 $ withUTFString 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 $ withUTFString 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":"b3fe54f2a2b7becd63c41e60971bfc70b4eb9d73","subject":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty","message":"glib: S.G.Properties: add readAttrFromBoxedOpaqueProperty\n","repos":"gtk2hs\/gtksourceview,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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\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 newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"16100aa918a83efa6fd18684256c4d45a130b24f","subject":"Add a little wait time to replMain so it doesn't hog the CPU.","message":"Add a little wait time to replMain so it doesn't hog the CPU.\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_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","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))\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":"8b8edf82f36cf306a279c4f85b37fa1f61b0b993","subject":"remove ErrorCode use from Event","message":"remove ErrorCode use from Event\n","repos":"IFCA\/opencl,Delan90\/opencl,Delan90\/opencl,IFCA\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Event.chs","new_file":"src\/System\/GPU\/OpenCL\/Event.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.Event( \n -- * Types\n CLEvent, CLCommandType(..), CLProfilingInfo(..), CLCommandExecutionStatus(..),\n -- * Functions\n clWaitForEvents, clRetainEvent, clReleaseEvent, clGetEventCommandQueue, \n clGetEventCommandType, clGetEventReferenceCount, \n clGetEventCommandExecutionStatus, clGetEventProfilingInfo\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport System.GPU.OpenCL.Types( \n CLEvent, CLint, CLuint, CLulong, CLEventInfo_, CLProfilingInfo_, CLError(..),\n CLCommandQueue, CLCommandType(..), CLCommandType_, \n CLCommandExecutionStatus(..), CLProfilingInfo(..), getCommandExecutionStatus, \n getCLValue, getEnumCL, wrapCheckSuccess, wrapGetInfo )\n\n#include \n\n-- -----------------------------------------------------------------------------\nforeign import ccall \"clWaitForEvents\" raw_clWaitForEvents :: \n CLuint -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clGetEventInfo\" raw_clGetEventInfo :: \n CLEvent -> CLEventInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clRetainEvent\" raw_clRetainEvent :: \n CLEvent -> IO CLint \nforeign import ccall \"clReleaseEvent\" raw_clReleaseEvent :: \n CLEvent -> IO CLint \nforeign import ccall \"clGetEventProfilingInfo\" raw_clGetEventProfilingInfo :: \n CLEvent -> CLProfilingInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n-- | Waits on the host thread for commands identified by event objects in \n-- event_list to complete. A command is considered complete if its execution \n-- status is 'CL_COMPLETE' or a negative value.\n-- Returns 'True' if the function was executed successfully. It returns 'False'\n-- if the list of events is empty, or if events specified in event_list do not \n-- belong to the same context, or if event objects specified in event_list are \n-- not valid event objects.\nclWaitForEvents :: [CLEvent] -> IO Bool\nclWaitForEvents [] = return False\nclWaitForEvents xs = allocaArray nevents $ \\pevents -> do\n pokeArray pevents xs\n wrapCheckSuccess $ raw_clWaitForEvents (fromIntegral nevents) pevents\n where\n nevents = length xs\n \n-- | Increments the event reference count.\n-- The OpenCL commands that return an event perform an implicit retain.\n-- Returns 'True' if the function is executed successfully. It returns 'False' \n-- if event is not a valid event object.\nclRetainEvent :: CLEvent -> IO Bool\nclRetainEvent ev = wrapCheckSuccess $ raw_clRetainEvent ev\n\n-- | Decrements the event reference count.\n-- Decrements the event reference count. The event object is deleted once the \n-- reference count becomes zero, the specific command identified by this event \n-- has completed (or terminated) and there are no commands in the command-queues \n-- of a context that require a wait for this event to complete.\n-- Returns 'True' if the function is executed successfully. It returns 'False' \n-- if event is not a valid event object.\nclReleaseEvent :: CLEvent -> IO Bool\nclReleaseEvent ev = wrapCheckSuccess $ raw_clReleaseEvent ev\n\n#c\nenum CLEventInfo {\n cL_EVENT_COMMAND_QUEUE=CL_EVENT_COMMAND_QUEUE,\n cL_EVENT_COMMAND_TYPE=CL_EVENT_COMMAND_TYPE,\n cL_EVENT_COMMAND_EXECUTION_STATUS=CL_EVENT_COMMAND_EXECUTION_STATUS,\n cL_EVENT_REFERENCE_COUNT=CL_EVENT_REFERENCE_COUNT\n };\n#endc\n{#enum CLEventInfo {upcaseFirstLetter} #}\n\n\n-- | Return the command-queue associated with event.\nclGetEventCommandQueue :: CLEvent -> IO (Either CLError CLCommandQueue)\nclGetEventCommandQueue ev = wrapGetInfo (\\(dat :: Ptr CLCommandQueue) \n -> raw_clGetEventInfo ev infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_EVENT_COMMAND_QUEUE\n size = fromIntegral $ sizeOf (nullPtr::CLCommandQueue)\n \n-- | Return the command associated with event.\nclGetEventCommandType :: CLEvent -> IO (Either CLError CLCommandType)\nclGetEventCommandType ev = wrapGetInfo (\\(dat :: Ptr CLCommandType_) \n -> raw_clGetEventInfo ev infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_EVENT_COMMAND_TYPE\n size = fromIntegral $ sizeOf (0::CLCommandType_)\n \n-- | Return the event reference count. The reference count returned should be \n-- considered immediately stale. It is unsuitable for general use in applications. \n-- This feature is provided for identifying memory leaks.\nclGetEventReferenceCount :: CLEvent -> IO (Either CLError CLint)\nclGetEventReferenceCount ev = wrapGetInfo (\\(dat :: Ptr CLint) \n -> raw_clGetEventInfo ev infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_EVENT_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLint)\n\n-- | Return the execution status of the command identified by event.\nclGetEventCommandExecutionStatus :: CLEvent -> IO (Either CLError CLCommandExecutionStatus)\nclGetEventCommandExecutionStatus ev = wrapGetInfo (\\(dat :: Ptr CLint) \n -> raw_clGetEventInfo ev infoid size (castPtr dat)) getCommandExecutionStatus\n where \n infoid = getCLValue CL_EVENT_COMMAND_EXECUTION_STATUS\n size = fromIntegral $ sizeOf (0::CLint)\n \n{-| Returns profiling information for the command associated with event if \nprofiling is enabled. The unsigned 64-bit values returned can be used to measure \nthe time in nano-seconds consumed by OpenCL commands.\n\nOpenCL devices are required to correctly track time across changes in device \nfrequency and power states. The 'CL_DEVICE_PROFILING_TIMER_RESOLUTION' specifies \nthe resolution of the timer i.e. the number of nanoseconds elapsed before the \ntimer is incremented.\n\nEvent objects can be used to capture profiling information that measure \nexecution time of a command. Profiling of OpenCL commands can be enabled either \nby using a command-queue created with 'CL_QUEUE_PROFILING_ENABLE' flag set in \nproperties argument to clCreateCommandQueue or by setting the \n'CL_QUEUE_PROFILING_ENABLE' flag in properties argument to \n'clSetCommandQueueProperty'.\n\n'clGetEventProfilingInfo' returns the valueif the function is executed \nsuccessfully and the profiling information has been recorded, and returns \n'Nothing' if the 'CL_QUEUE_PROFILING_ENABLE' flag is not set for the \ncommand-queue and if the profiling information is currently not available \n(because the command identified by event has not completed), or if event is a \nnot a valid event object.\n-} \nclGetEventProfilingInfo :: CLEvent -> CLProfilingInfo -> IO (Either CLError CLulong)\nclGetEventProfilingInfo ev prof = wrapGetInfo (\\(dat :: Ptr CLulong) \n -> raw_clGetEventProfilingInfo ev infoid size (castPtr dat)) id\n where \n infoid = getCLValue prof\n size = fromIntegral $ sizeOf (0::CLulong)\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.Event( \n -- * Types\n CLEvent, CLCommandType(..), CLProfilingInfo(..), CLCommandExecutionStatus(..),\n -- * Functions\n clWaitForEvents, clRetainEvent, clReleaseEvent, clGetEventCommandQueue, \n clGetEventCommandType, clGetEventReferenceCount, \n clGetEventCommandExecutionStatus, clGetEventProfilingInfo\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport System.GPU.OpenCL.Types( \n CLEvent, CLint, CLuint, CLulong, CLEventInfo_, CLProfilingInfo_, ErrorCode(..),\n CLCommandQueue, CLCommandType(..), CLCommandType_, CLCommandExecutionStatus(..), \n CLProfilingInfo(..), clSuccess, getCommandType, getCommandExecutionStatus, \n getCLValue )\n\n#include \n\n-- -----------------------------------------------------------------------------\nforeign import ccall \"clWaitForEvents\" raw_clWaitForEvents :: \n CLuint -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clGetEventInfo\" raw_clGetEventInfo :: \n CLEvent -> CLEventInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clRetainEvent\" raw_clRetainEvent :: \n CLEvent -> IO CLint \nforeign import ccall \"clReleaseEvent\" raw_clReleaseEvent :: \n CLEvent -> IO CLint \nforeign import ccall \"clGetEventProfilingInfo\" raw_clGetEventProfilingInfo :: \n CLEvent -> CLProfilingInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n-- | Waits on the host thread for commands identified by event objects in \n-- event_list to complete. A command is considered complete if its execution \n-- status is 'CL_COMPLETE' or a negative value.\n-- Returns 'True' if the function was executed successfully. It returns 'False'\n-- if the list of events is empty, or if events specified in event_list do not \n-- belong to the same context, or if event objects specified in event_list are \n-- not valid event objects.\nclWaitForEvents :: [CLEvent] -> IO Bool\nclWaitForEvents [] = return False\nclWaitForEvents xs = allocaArray nevents $ \\pevents -> do\n pokeArray pevents xs\n errcode <- fmap ErrorCode $ raw_clWaitForEvents (fromIntegral nevents) pevents\n return (errcode==clSuccess) \n where\n nevents = length xs\n \n-- | Increments the event reference count.\n-- The OpenCL commands that return an event perform an implicit retain.\n-- Returns 'True' if the function is executed successfully. It returns 'False' \n-- if event is not a valid event object.\nclRetainEvent :: CLEvent -> IO Bool\nclRetainEvent ev = raw_clRetainEvent ev\n >>= return . (==clSuccess) . ErrorCode\n\n-- | Decrements the event reference count.\n-- Decrements the event reference count. The event object is deleted once the \n-- reference count becomes zero, the specific command identified by this event \n-- has completed (or terminated) and there are no commands in the command-queues \n-- of a context that require a wait for this event to complete.\n-- Returns 'True' if the function is executed successfully. It returns 'False' \n-- if event is not a valid event object.\nclReleaseEvent :: CLEvent -> IO Bool\nclReleaseEvent ev = raw_clReleaseEvent ev\n >>= return . (==clSuccess) . ErrorCode\n\n#c\nenum CLEventInfo {\n cL_EVENT_COMMAND_QUEUE=CL_EVENT_COMMAND_QUEUE,\n cL_EVENT_COMMAND_TYPE=CL_EVENT_COMMAND_TYPE,\n cL_EVENT_COMMAND_EXECUTION_STATUS=CL_EVENT_COMMAND_EXECUTION_STATUS,\n cL_EVENT_REFERENCE_COUNT=CL_EVENT_REFERENCE_COUNT\n };\n#endc\n{#enum CLEventInfo {upcaseFirstLetter} #}\n\n\n-- | Return the command-queue associated with event.\nclGetEventCommandQueue :: CLEvent -> IO (Maybe CLCommandQueue)\nclGetEventCommandQueue ev = alloca $ \\(dat :: Ptr CLCommandQueue) -> do\n errcode <- fmap ErrorCode $ raw_clGetEventInfo ev infoid size (castPtr dat) nullPtr\n if errcode == clSuccess\n then fmap Just $ peek dat\n else return Nothing\n where \n infoid = getCLValue CL_EVENT_COMMAND_QUEUE\n size = fromIntegral $ sizeOf (nullPtr::CLCommandQueue)\n\n-- | Return the command associated with event.\nclGetEventCommandType :: CLEvent -> IO (Maybe CLCommandType)\nclGetEventCommandType ev = alloca $ \\(dat :: Ptr CLCommandType_) -> do\n errcode <- fmap ErrorCode $ raw_clGetEventInfo ev infoid size (castPtr dat) nullPtr\n if errcode == clSuccess\n then fmap getCommandType $ peek dat\n else return Nothing\n where \n infoid = getCLValue CL_EVENT_COMMAND_TYPE\n size = fromIntegral $ sizeOf (0::CLCommandType_)\n\n-- | Return the event reference count. The reference count returned should be \n-- considered immediately stale. It is unsuitable for general use in applications. \n-- This feature is provided for identifying memory leaks.\nclGetEventReferenceCount :: CLEvent -> IO (Maybe CLint)\nclGetEventReferenceCount ev = alloca $ \\(dat :: Ptr CLint) -> do\n errcode <- fmap ErrorCode $ raw_clGetEventInfo ev infoid size (castPtr dat) nullPtr\n if errcode == clSuccess\n then fmap Just $ peek dat\n else return Nothing\n where \n infoid = getCLValue CL_EVENT_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLint)\n\n-- | Return the execution status of the command identified by event.\nclGetEventCommandExecutionStatus :: CLEvent -> IO (Maybe CLCommandExecutionStatus)\nclGetEventCommandExecutionStatus ev = alloca $ \\(dat :: Ptr CLint) -> do\n errcode <- fmap ErrorCode $ raw_clGetEventInfo ev infoid size (castPtr dat) nullPtr\n if errcode == clSuccess\n then fmap (getCommandExecutionStatus) $ peek dat\n else return Nothing\n where \n infoid = getCLValue CL_EVENT_COMMAND_EXECUTION_STATUS\n size = fromIntegral $ sizeOf (0::CLint)\n \n{-| Returns profiling information for the command associated with event if \nprofiling is enabled. The unsigned 64-bit values returned can be used to measure \nthe time in nano-seconds consumed by OpenCL commands.\n\nOpenCL devices are required to correctly track time across changes in device \nfrequency and power states. The 'CL_DEVICE_PROFILING_TIMER_RESOLUTION' specifies \nthe resolution of the timer i.e. the number of nanoseconds elapsed before the \ntimer is incremented.\n\nEvent objects can be used to capture profiling information that measure \nexecution time of a command. Profiling of OpenCL commands can be enabled either \nby using a command-queue created with 'CL_QUEUE_PROFILING_ENABLE' flag set in \nproperties argument to clCreateCommandQueue or by setting the \n'CL_QUEUE_PROFILING_ENABLE' flag in properties argument to \n'clSetCommandQueueProperty'.\n\n'clGetEventProfilingInfo' returns the valueif the function is executed \nsuccessfully and the profiling information has been recorded, and returns \n'Nothing' if the 'CL_QUEUE_PROFILING_ENABLE' flag is not set for the \ncommand-queue and if the profiling information is currently not available \n(because the command identified by event has not completed), or if event is a \nnot a valid event object.\n-} \nclGetEventProfilingInfo :: CLEvent -> CLProfilingInfo -> IO (Maybe CLulong)\nclGetEventProfilingInfo ev prof = alloca $ \\(dat :: Ptr CLulong) -> do\n errcode <- fmap ErrorCode $ raw_clGetEventProfilingInfo ev infoid size (castPtr dat) nullPtr\n if errcode == clSuccess\n then fmap Just $ peek dat\n else return Nothing\n where \n size = fromIntegral $ sizeOf (0::CLulong)\n infoid = getCLValue prof\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"65d9fc1f42b4810fa60620dad81c278135deb142","subject":"fix for cuda-5.0","message":"fix for cuda-5.0\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module.chs","new_file":"Foreign\/CUDA\/Driver\/Module.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n#if CUDA_VERSION >= 5050\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\n#endif\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo)\n | Verbose -- ^ verbose log messages\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, 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, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n unpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"60bef3f3f2a0d651af4596864771c9d80b57aa26","subject":"Fix #4: Export applicationGetUseQuartsAccelerators from GUI.Application","message":"Fix #4: Export applicationGetUseQuartsAccelerators from GUI.Application\n","repos":"gtk2hs\/gtk-mac-integration,gtk2hs\/gtk-mac-integration","old_file":"Graphics\/UI\/Gtk\/OSX\/Application.chs","new_file":"Graphics\/UI\/Gtk\/OSX\/Application.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.OSX.Application (\n Application,\n ApplicationClass,\n castToApplication,\n gTypeApplication,\n toApplication,\n\n applicationNew,\n applicationReady,\n applicationSetUseQuartsAccelerators,\n applicationGetUseQuartsAccelerators,\n applicationSetMenuBar,\n applicationSyncMenuBar,\n applicationInsertAppMenuItem,\n applicationSetWindowMenu,\n applicationSetHelpMenu,\n GtkosxApplicationAttentionType(..),\n applicationSetDockMenu,\n applicationSetDockIconPixbuf,\n applicationSetDockIconResource,\n AttentionRequestID(..),\n applicationAttentionRequest,\n applicationCancelAttentionRequest,\n applicationGetBundlePath,\n applicationGetResourcePath,\n applicationGetExecutablePath,\n applicationGetBundleId,\n applicationGetBundleInfo,\n didBecomeActive,\n willResignActive,\n blockTermination,\n willTerminate,\n openFile\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject (objectNew, makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.OSX.Types#}\n{#import Graphics.UI.Gtk.OSX.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\napplicationNew :: IO Application\napplicationNew = makeNewGObject mkApplication $ liftM castPtr $\n objectNew gTypeApplication []\n\n-- |\n--\napplicationReady :: ApplicationClass self => self -> IO ()\napplicationReady self =\n {#call unsafe gtkosx_application_ready#} (toApplication self)\n\n-- |\n--\napplicationSetUseQuartsAccelerators :: ApplicationClass self => self -> Bool -> IO ()\napplicationSetUseQuartsAccelerators self b =\n {#call unsafe gtkosx_application_set_use_quartz_accelerators#} (toApplication self) (fromBool b)\n\n-- |\n--\napplicationGetUseQuartsAccelerators :: ApplicationClass self => self -> IO Bool\napplicationGetUseQuartsAccelerators self = liftM toBool $\n {#call unsafe gtkosx_application_use_quartz_accelerators#} (toApplication self)\n\n-- |\n--\napplicationSetMenuBar :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetMenuBar self menu =\n {#call unsafe gtkosx_application_set_menu_bar#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSyncMenuBar :: ApplicationClass self => self -> IO ()\napplicationSyncMenuBar self =\n {#call unsafe gtkosx_application_sync_menubar#} (toApplication self)\n\n-- |\n--\napplicationInsertAppMenuItem :: (ApplicationClass self, WidgetClass menu_item) => self -> menu_item -> Int -> IO ()\napplicationInsertAppMenuItem self menu_item index =\n {#call unsafe gtkosx_application_insert_app_menu_item#} (toApplication self) (toWidget menu_item) (fromIntegral index)\n\n-- |\n--\napplicationSetWindowMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetWindowMenu self menuItem =\n {#call unsafe gtkosx_application_set_window_menu#} (toApplication self) (toMenuItem menuItem)\n\n-- |\n--\napplicationSetHelpMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetHelpMenu self menuItem =\n {#call unsafe gtkosx_application_set_help_menu#} (toApplication self) (toMenuItem menuItem)\n\n{#enum GtkosxApplicationAttentionType {underscoreToCase} deriving (Eq,Show)#}\n\n-- |\n--\napplicationSetDockMenu :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetDockMenu self menu =\n {#call unsafe gtkosx_application_set_dock_menu#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSetDockIconPixbuf :: (ApplicationClass self, PixbufClass pixbuf) => self -> Maybe pixbuf -> IO ()\napplicationSetDockIconPixbuf self mbPixbuf =\n {#call unsafe gtkosx_application_set_dock_icon_pixbuf#} (toApplication self)\n (maybe (Pixbuf nullForeignPtr) toPixbuf mbPixbuf)\n\n-- |\n--\napplicationSetDockIconResource :: (ApplicationClass self, GlibString string)\n => self -> string -> string -> string -> IO ()\napplicationSetDockIconResource self name rType subdir =\n withUTFString name $ \\namePtr ->\n withUTFString rType $ \\typePtr ->\n withUTFString subdir $ \\subdirPtr ->\n {#call unsafe gtkosx_application_set_dock_icon_resource#} (toApplication self) namePtr typePtr subdirPtr\n\nnewtype AttentionRequestID = AttentionRequestID CInt\n\n-- |\n--\napplicationAttentionRequest :: ApplicationClass self => self -> GtkosxApplicationAttentionType -> IO AttentionRequestID\napplicationAttentionRequest self rType = liftM AttentionRequestID $\n {#call unsafe gtkosx_application_attention_request#} (toApplication self) (fromIntegral $ fromEnum rType)\n\n-- |\n--\napplicationCancelAttentionRequest :: ApplicationClass self => self -> AttentionRequestID -> IO ()\napplicationCancelAttentionRequest self (AttentionRequestID id) =\n {#call unsafe gtkosx_application_cancel_attention_request#} (toApplication self) id\n\n-- |\n--\napplicationGetBundlePath :: GlibString string => IO string\napplicationGetBundlePath =\n {#call unsafe gtkosx_application_get_bundle_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetResourcePath :: GlibString string => IO string\napplicationGetResourcePath =\n {#call unsafe gtkosx_application_get_resource_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetExecutablePath :: GlibString string => IO string\napplicationGetExecutablePath =\n {#call unsafe gtkosx_application_get_executable_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleId :: GlibString string => IO string\napplicationGetBundleId =\n {#call unsafe gtkosx_application_get_bundle_id#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleInfo :: GlibString string => string -> IO string\napplicationGetBundleInfo key =\n withUTFString key $ \\keyPtr ->\n {#call unsafe gtkosx_application_get_bundle_info#} keyPtr >>= peekUTFString\n\n-- |\n--\ndidBecomeActive :: ApplicationClass self => Signal self (IO ())\ndidBecomeActive = Signal (connect_NONE__NONE \"NSApplicationDidBecomeActive\")\n\n-- |\n--\nwillResignActive :: ApplicationClass self => Signal self (IO ())\nwillResignActive = Signal (connect_NONE__NONE \"NSApplicationWillResignActive\")\n\n-- |\n--\nblockTermination :: ApplicationClass self => Signal self (IO Bool)\nblockTermination = Signal (connect_NONE__BOOL \"NSApplicationBlockTermination\")\n\n-- |\n--\nwillTerminate :: ApplicationClass self => Signal self (IO ())\nwillTerminate = Signal (connect_NONE__NONE \"NSApplicationWillTerminate\")\n\n-- |\n--\nopenFile :: (ApplicationClass self, GlibString string) => Signal self (string -> IO ())\nopenFile = Signal (connect_GLIBSTRING__NONE \"NSApplicationOpenFile\")\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.OSX.Application (\n Application,\n ApplicationClass,\n castToApplication,\n gTypeApplication,\n toApplication,\n\n applicationNew,\n applicationReady,\n applicationSetUseQuartsAccelerators,\n applicationSetMenuBar,\n applicationSyncMenuBar,\n applicationInsertAppMenuItem,\n applicationSetWindowMenu,\n applicationSetHelpMenu,\n GtkosxApplicationAttentionType(..),\n applicationSetDockMenu,\n applicationSetDockIconPixbuf,\n applicationSetDockIconResource,\n AttentionRequestID(..),\n applicationAttentionRequest,\n applicationCancelAttentionRequest,\n applicationGetBundlePath,\n applicationGetResourcePath,\n applicationGetExecutablePath,\n applicationGetBundleId,\n applicationGetBundleInfo,\n didBecomeActive,\n willResignActive,\n blockTermination,\n willTerminate,\n openFile\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject (objectNew, makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.OSX.Types#}\n{#import Graphics.UI.Gtk.OSX.Signals#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\napplicationNew :: IO Application\napplicationNew = makeNewGObject mkApplication $ liftM castPtr $\n objectNew gTypeApplication []\n\n-- |\n--\napplicationReady :: ApplicationClass self => self -> IO ()\napplicationReady self =\n {#call unsafe gtkosx_application_ready#} (toApplication self)\n\n-- |\n--\napplicationSetUseQuartsAccelerators :: ApplicationClass self => self -> Bool -> IO ()\napplicationSetUseQuartsAccelerators self b =\n {#call unsafe gtkosx_application_set_use_quartz_accelerators#} (toApplication self) (fromBool b)\n\n-- |\n--\napplicationGetUseQuartsAccelerators :: ApplicationClass self => self -> IO Bool\napplicationGetUseQuartsAccelerators self = liftM toBool $\n {#call unsafe gtkosx_application_use_quartz_accelerators#} (toApplication self)\n\n-- |\n--\napplicationSetMenuBar :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetMenuBar self menu =\n {#call unsafe gtkosx_application_set_menu_bar#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSyncMenuBar :: ApplicationClass self => self -> IO ()\napplicationSyncMenuBar self =\n {#call unsafe gtkosx_application_sync_menubar#} (toApplication self)\n\n-- |\n--\napplicationInsertAppMenuItem :: (ApplicationClass self, WidgetClass menu_item) => self -> menu_item -> Int -> IO ()\napplicationInsertAppMenuItem self menu_item index =\n {#call unsafe gtkosx_application_insert_app_menu_item#} (toApplication self) (toWidget menu_item) (fromIntegral index)\n\n-- |\n--\napplicationSetWindowMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetWindowMenu self menuItem =\n {#call unsafe gtkosx_application_set_window_menu#} (toApplication self) (toMenuItem menuItem)\n\n-- |\n--\napplicationSetHelpMenu :: (ApplicationClass self, MenuItemClass menuItem)\n => self -> menuItem -> IO ()\napplicationSetHelpMenu self menuItem =\n {#call unsafe gtkosx_application_set_help_menu#} (toApplication self) (toMenuItem menuItem)\n\n{#enum GtkosxApplicationAttentionType {underscoreToCase} deriving (Eq,Show)#}\n\n-- |\n--\napplicationSetDockMenu :: (ApplicationClass self, MenuShellClass menu) => self -> menu -> IO ()\napplicationSetDockMenu self menu =\n {#call unsafe gtkosx_application_set_dock_menu#} (toApplication self) (toMenuShell menu)\n\n-- |\n--\napplicationSetDockIconPixbuf :: (ApplicationClass self, PixbufClass pixbuf) => self -> Maybe pixbuf -> IO ()\napplicationSetDockIconPixbuf self mbPixbuf =\n {#call unsafe gtkosx_application_set_dock_icon_pixbuf#} (toApplication self)\n (maybe (Pixbuf nullForeignPtr) toPixbuf mbPixbuf)\n\n-- |\n--\napplicationSetDockIconResource :: (ApplicationClass self, GlibString string)\n => self -> string -> string -> string -> IO ()\napplicationSetDockIconResource self name rType subdir =\n withUTFString name $ \\namePtr ->\n withUTFString rType $ \\typePtr ->\n withUTFString subdir $ \\subdirPtr ->\n {#call unsafe gtkosx_application_set_dock_icon_resource#} (toApplication self) namePtr typePtr subdirPtr\n\nnewtype AttentionRequestID = AttentionRequestID CInt\n\n-- |\n--\napplicationAttentionRequest :: ApplicationClass self => self -> GtkosxApplicationAttentionType -> IO AttentionRequestID\napplicationAttentionRequest self rType = liftM AttentionRequestID $\n {#call unsafe gtkosx_application_attention_request#} (toApplication self) (fromIntegral $ fromEnum rType)\n\n-- |\n--\napplicationCancelAttentionRequest :: ApplicationClass self => self -> AttentionRequestID -> IO ()\napplicationCancelAttentionRequest self (AttentionRequestID id) =\n {#call unsafe gtkosx_application_cancel_attention_request#} (toApplication self) id\n\n-- |\n--\napplicationGetBundlePath :: GlibString string => IO string\napplicationGetBundlePath =\n {#call unsafe gtkosx_application_get_bundle_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetResourcePath :: GlibString string => IO string\napplicationGetResourcePath =\n {#call unsafe gtkosx_application_get_resource_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetExecutablePath :: GlibString string => IO string\napplicationGetExecutablePath =\n {#call unsafe gtkosx_application_get_executable_path#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleId :: GlibString string => IO string\napplicationGetBundleId =\n {#call unsafe gtkosx_application_get_bundle_id#} >>= peekUTFString\n\n-- |\n--\napplicationGetBundleInfo :: GlibString string => string -> IO string\napplicationGetBundleInfo key =\n withUTFString key $ \\keyPtr ->\n {#call unsafe gtkosx_application_get_bundle_info#} keyPtr >>= peekUTFString\n\n-- |\n--\ndidBecomeActive :: ApplicationClass self => Signal self (IO ())\ndidBecomeActive = Signal (connect_NONE__NONE \"NSApplicationDidBecomeActive\")\n\n-- |\n--\nwillResignActive :: ApplicationClass self => Signal self (IO ())\nwillResignActive = Signal (connect_NONE__NONE \"NSApplicationWillResignActive\")\n\n-- |\n--\nblockTermination :: ApplicationClass self => Signal self (IO Bool)\nblockTermination = Signal (connect_NONE__BOOL \"NSApplicationBlockTermination\")\n\n-- |\n--\nwillTerminate :: ApplicationClass self => Signal self (IO ())\nwillTerminate = Signal (connect_NONE__NONE \"NSApplicationWillTerminate\")\n\n-- |\n--\nopenFile :: (ApplicationClass self, GlibString string) => Signal self (string -> IO ())\nopenFile = Signal (connect_GLIBSTRING__NONE \"NSApplicationOpenFile\")\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"28f237bde4146845017835ca80bd738f53a1125d","subject":"Start unmarshalling","message":"Start unmarshalling\n","repos":"travitch\/llvm-analysis,wangxiayang\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/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 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","old_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}\nmodule Data.LLVM.Private.Unmarshal where\n\n#include \"c++\/marshal.h\"\n\nimport Foreign.C\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Ptr\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\n{#fun marshalLLVM { `String' } -> `ModulePtr' id #}\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n{#fun cmoduleErrMsg as ^ { id `ModulePtr' } -> `String' #}\n{#fun cmoduleDataLayout as ^ { id `ModulePtr' } -> `String' #}\n{#fun cmoduleIdentifier as ^ { id `ModulePtr' } -> `String' #}\n{#fun cmoduleTargetTriple as ^ { id `ModulePtr' } -> `String' #}\n{#fun cmoduleInlineAsm as ^ { id `ModulePtr' } -> `String' #}\n{#fun cmoduleIsLittleEndian as ^ { id `ModulePtr' } -> `Int' #}\n{#fun cmodulePointerSize as ^ { id `ModulePtr' } -> `Int' #}\n{#fun cmoduleIsError as ^ { id `ModulePtr' } -> `Int' #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"534b7220ba57d07f55bb30d32140f89fa496708d","subject":"Added support for a NULL local_work_size parameter to let the OpenCL implementation determine the global work-item breakdown.","message":"Added support for a NULL local_work_size parameter to let the OpenCL implementation determine the global work-item breakdown.\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/opencl","old_file":"src\/System\/GPU\/OpenCL\/CommandQueue.chs","new_file":"src\/System\/GPU\/OpenCL\/CommandQueue.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 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 CLCommandQueue, CLDeviceID, CLContext, CLCommandQueueProperty(..), \n CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef MACOSX\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (map fromIntegral lws) $ \\plws -> do\n clEnqueue (raw_clEnqueueNDRangeKernel cq krn num nullPtr pgws plws) events\n where\n num = fromIntegral $ length gws\n withMaybeArray [] = ($ nullPtr)\n withMaybeArray xs = withArray xs\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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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":"{- 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 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 CLCommandQueue, CLDeviceID, CLContext, CLCommandQueueProperty(..), \n CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef MACOSX\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO 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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"aff1b97073d4260d5fb92999c939327160c1dd55","subject":"Remove a change for ghc 7.4 - don't need it yet","message":"Remove a change for ghc 7.4 - don't need it yet\n","repos":"travitch\/llvm-data-interop,travitch\/llvm-data-interop","old_file":"src\/Data\/LLVM\/Internal\/Interop.chs","new_file":"src\/Data\/LLVM\/Internal\/Interop.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes, OverloadedStrings #-}\nmodule Data.LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems, unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\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\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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaFileFilename :: InternString m => MetaPtr -> m ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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\nclass MonadIO m => InternString m where\n internString :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes, OverloadedStrings #-}\nmodule Data.LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems )\nimport Data.Array.Unsafe ( unsafeForeignPtrToStorableArray )\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\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\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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaFileFilename :: InternString m => MetaPtr -> m ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m 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 :: InternString m => MetaPtr -> m 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\nclass MonadIO m => InternString m where\n internString :: ByteString -> m ByteString\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 :: InternString m => (a -> IO CString) -> a -> m ByteString\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\n internString str\n {-\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7f2cb97dfc809e61d75bcd1e1b80391cc8290be2","subject":"Added threadsafer foreign pointers.","message":"Added threadsafer foreign pointers.\n","repos":"aleator\/CV,TomMD\/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 #-}\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\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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8) \n getPixel (fromIntegral -> x, fromIntegral -> y) image \n = unsafePerformIO $ do \n withGenImage image $ \\img -> do\n r <- {#call wrapGet8U2DC#} img y x 0\n g <- {#call wrapGet8U2DC#} img y x 1\n b <- {#call wrapGet8U2DC#} img y x 2\n return (fromIntegral r,fromIntegral g, fromIntegral 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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue img fun = do \n result <- cloneImage img\n r <- fun result\n return r\n\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\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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 #-}\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.ForeignPtr\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\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\nforeign 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 releaseImage 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 releaseImage 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\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 IntSized a where\n getSize :: a -> (Int,Int)\n\ninstance IntSized BareImage where\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 IntSized (Image c d) where\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 :: (Integral i) => (i,i) -> a -> P a\n\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n getPixel (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n getPixel (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\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8) \n getPixel (fromIntegral -> x, fromIntegral -> y) image \n = unsafePerformIO $ do \n withGenImage image $ \\img -> do\n r <- {#call wrapGet8U2DC#} img y x 0\n g <- {#call wrapGet8U2DC#} img y x 1\n b <- {#call wrapGet8U2DC#} img y x 2\n return (fromIntegral r,fromIntegral g, fromIntegral 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 :: (IntSized a) => a -> Int\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 img fun = do \n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue img fun = do \n result <- cloneImage img\n r <- fun result\n return r\n\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\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img\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-- Manipulating image pixels\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac 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":"2f9dcb2a6d3764a5e656af1fb9f37753e83b0cb0","subject":"cache configuration for runtime api","message":"cache configuration for runtime api\n\nIgnore-this: 69f19a80c38a1dc55f918e3ff3ad8de2\n\ndarcs-hash:20100619052249-dcabc-31f82ef1682b19d1beb9e889330d77846d3f0d5a.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Exec.chs","new_file":"Foreign\/CUDA\/Runtime\/Exec.chs","new_contents":"{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Exec\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for C-for-CUDA runtime interface\n--\n--------------------------------------------------------------------------------\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\nmodule Foreign.CUDA.Runtime.Exec\n (\n FunAttributes(..), FunParam(..),\n#if CUDART_VERSION >= 3000\n CacheConfig(..),\n#endif\n attributes, setConfig, setParams,\n#if CUDART_VERSION >= 3000\n setCacheConfig,\n#endif\n launch\n )\n where\n\n-- Friends\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#c\ntypedef struct cudaFuncAttributes cudaFuncAttributes;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n--\n-- Function Attributes\n--\n{# pointer *cudaFuncAttributes as ^ foreign -> FunAttributes nocode #}\n\ndata FunAttributes = FunAttributes\n {\n constSizeBytes :: Int64,\n localSizeBytes :: Int64,\n sharedSizeBytes :: Int64,\n maxKernelThreadsPerBlock :: Int,\t-- ^ maximum block size that can be successively launched (based on register usage)\n numRegs :: Int -- ^ number of registers required for each thread\n }\n deriving (Show)\n\ninstance Storable FunAttributes where\n sizeOf _ = {# sizeof cudaFuncAttributes #}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n cs <- cIntConv `fmap` {#get cudaFuncAttributes.constSizeBytes#} p\n ls <- cIntConv `fmap` {#get cudaFuncAttributes.localSizeBytes#} p\n ss <- cIntConv `fmap` {#get cudaFuncAttributes.sharedSizeBytes#} p\n tb <- cIntConv `fmap` {#get cudaFuncAttributes.maxThreadsPerBlock#} p\n nr <- cIntConv `fmap` {#get cudaFuncAttributes.numRegs#} p\n\n return FunAttributes\n {\n constSizeBytes = cs,\n localSizeBytes = ls,\n sharedSizeBytes = ss,\n maxKernelThreadsPerBlock = tb,\n numRegs = nr\n }\n\n#if CUDART_VERSION >= 3000\n-- |\n-- Cache configuration preference\n--\n{# enum cudaFuncCache as CacheConfig\n { }\n with prefix=\"cudaFuncCachePrefer\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters. Doubles will be converted to an internal float\n-- representation on devices that do not support doubles natively.\n--\ndata FunParam where\n IArg :: Int -> FunParam\n FArg :: Float -> FunParam\n DArg :: Double -> FunParam\n VArg :: Storable a => a -> FunParam\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Obtain the attributes of the named @__global__@ device function. This\n-- itemises the requirements to successfully launch the given kernel.\n--\nattributes :: String -> IO FunAttributes\nattributes fn = resultIfOk =<< cudaFuncGetAttributes fn\n\n{# fun unsafe cudaFuncGetAttributes\n { alloca- `FunAttributes' peek*\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the grid and block dimensions for a device call. Used in conjunction\n-- with 'setParams', this pushes data onto the execution stack that will be\n-- popped when a function is 'launch'ed.\n--\nsetConfig :: (Int,Int)\t\t-- ^ grid dimensions\n\t -> (Int,Int,Int)\t-- ^ block dimensions\n\t -> Int64\t\t-- ^ shared memory per block (bytes)\n\t -> Maybe Stream\t-- ^ associated processing stream\n\t -> IO ()\nsetConfig (gx,gy) (bx,by,bz) sharedMem mst =\n nothingIfOk =<< case mst of\n Nothing -> cudaConfigureCallSimple gx gy bx by bz sharedMem (Stream 0)\n Just st -> cudaConfigureCallSimple gx gy bx by bz sharedMem st\n\n--\n-- The FFI does not support passing deferenced structures to C functions, as\n-- this is highly platform\/compiler dependent. Wrap our own function stub\n-- accepting plain integers.\n--\n{# fun unsafe cudaConfigureCallSimple\n {\t `Int', `Int'\n , `Int', `Int', `Int'\n , cIntConv `Int64'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the argument parameters that will be passed to the next kernel\n-- invocation. This is used in conjunction with 'setConfig' to control kernel\n-- execution.\nsetParams :: [FunParam] -> IO ()\nsetParams = foldM_ k 0\n where\n k offset arg = do\n let s = size arg\n set arg s offset >>= nothingIfOk\n return (offset + s)\n\n size (IArg _) = sizeOf (undefined :: Int)\n size (FArg _) = sizeOf (undefined :: Float)\n size (DArg _) = sizeOf (undefined :: Double)\n size (VArg a) = sizeOf a\n\n set (IArg v) s o = cudaSetupArgument v s o\n set (FArg v) s o = cudaSetupArgument v s o\n set (VArg v) s o = cudaSetupArgument v s o\n set (DArg v) s o =\n cudaSetDoubleForDevice v >>= resultIfOk >>= \\d ->\n cudaSetupArgument d s o\n\n\n{# fun unsafe cudaSetupArgument\n `Storable a' =>\n { with'* `a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n\n{# fun unsafe cudaSetDoubleForDevice\n { with'* `Double' peek'* } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n peek' = peek . castPtr\n\n\n#if CUDART_VERSION >= 3000\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--\nsetCacheConfig :: String -> CacheConfig -> IO ()\nsetCacheConfig fn pref = nothingIfOk =<< cudaFuncSetCacheConfig fn pref\n\n{# fun unsafe cudaFuncSetCacheConfig\n { withCString* `String'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Invoke the named kernel on the device, which must have been declared\n-- @__global__@. This must be preceded by a call to 'setConfig' and (if\n-- appropriate) 'setParams'.\n--\nlaunch :: String -> IO ()\nlaunch fn = nothingIfOk =<< cudaLaunch fn\n\n{# fun unsafe cudaLaunch\n { withCString* `String' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE GADTs #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Exec\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for C-for-CUDA runtime interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Exec\n (\n FunAttributes(..), FunParam(..),\n attributes, setConfig, setParams, launch\n )\n where\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#c\ntypedef struct cudaFuncAttributes cudaFuncAttributes;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n--\n-- Function Attributes\n--\n{# pointer *cudaFuncAttributes as ^ foreign -> FunAttributes nocode #}\n\ndata FunAttributes = FunAttributes\n {\n constSizeBytes :: Int64,\n localSizeBytes :: Int64,\n sharedSizeBytes :: Int64,\n maxKernelThreadsPerBlock :: Int,\t-- ^ maximum block size that can be successively launched (based on register usage)\n numRegs :: Int -- ^ number of registers required for each thread\n }\n deriving (Show)\n\ninstance Storable FunAttributes where\n sizeOf _ = {# sizeof cudaFuncAttributes #}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n cs <- cIntConv `fmap` {#get cudaFuncAttributes.constSizeBytes#} p\n ls <- cIntConv `fmap` {#get cudaFuncAttributes.localSizeBytes#} p\n ss <- cIntConv `fmap` {#get cudaFuncAttributes.sharedSizeBytes#} p\n tb <- cIntConv `fmap` {#get cudaFuncAttributes.maxThreadsPerBlock#} p\n nr <- cIntConv `fmap` {#get cudaFuncAttributes.numRegs#} p\n\n return FunAttributes\n {\n constSizeBytes = cs,\n localSizeBytes = ls,\n sharedSizeBytes = ss,\n maxKernelThreadsPerBlock = tb,\n numRegs = nr\n }\n\n-- |\n-- Kernel function parameters. Doubles will be converted to an internal float\n-- representation on devices that do not support doubles natively.\n--\ndata FunParam where\n IArg :: Int -> FunParam\n FArg :: Float -> FunParam\n DArg :: Double -> FunParam\n VArg :: Storable a => a -> FunParam\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Obtain the attributes of the named @__global__@ device function. This\n-- itemises the requirements to successfully launch the given kernel.\n--\nattributes :: String -> IO FunAttributes\nattributes fn = resultIfOk =<< cudaFuncGetAttributes fn\n\n{# fun unsafe cudaFuncGetAttributes\n { alloca- `FunAttributes' peek*\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the grid and block dimensions for a device call. Used in conjunction\n-- with 'setParams', this pushes data onto the execution stack that will be\n-- popped when a function is 'launch'ed.\n--\nsetConfig :: (Int,Int)\t\t-- ^ grid dimensions\n\t -> (Int,Int,Int)\t-- ^ block dimensions\n\t -> Int64\t\t-- ^ shared memory per block (bytes)\n\t -> Maybe Stream\t-- ^ associated processing stream\n\t -> IO ()\nsetConfig (gx,gy) (bx,by,bz) sharedMem mst =\n nothingIfOk =<< case mst of\n Nothing -> cudaConfigureCallSimple gx gy bx by bz sharedMem (Stream 0)\n Just st -> cudaConfigureCallSimple gx gy bx by bz sharedMem st\n\n--\n-- The FFI does not support passing deferenced structures to C functions, as\n-- this is highly platform\/compiler dependent. Wrap our own function stub\n-- accepting plain integers.\n--\n{# fun unsafe cudaConfigureCallSimple\n {\t `Int', `Int'\n , `Int', `Int', `Int'\n , cIntConv `Int64'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the argument parameters that will be passed to the next kernel\n-- invocation. This is used in conjunction with 'setConfig' to control kernel\n-- execution.\nsetParams :: [FunParam] -> IO ()\nsetParams = foldM_ k 0\n where\n k offset arg = do\n let s = size arg\n set arg s offset >>= nothingIfOk\n return (offset + s)\n\n size (IArg _) = sizeOf (undefined :: Int)\n size (FArg _) = sizeOf (undefined :: Float)\n size (DArg _) = sizeOf (undefined :: Double)\n size (VArg a) = sizeOf a\n\n set (IArg v) s o = cudaSetupArgument v s o\n set (FArg v) s o = cudaSetupArgument v s o\n set (VArg v) s o = cudaSetupArgument v s o\n set (DArg v) s o =\n cudaSetDoubleForDevice v >>= resultIfOk >>= \\d ->\n cudaSetupArgument d s o\n\n\n{# fun unsafe cudaSetupArgument\n `Storable a' =>\n { with'* `a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n\n{# fun unsafe cudaSetDoubleForDevice\n { with'* `Double' peek'* } -> `Status' cToEnum #}\n where\n with' v a = with v $ \\p -> a (castPtr p)\n peek' = peek . castPtr\n\n\n-- |\n-- Invoke the named kernel on the device, which must have been declared\n-- @__global__@. This must be preceded by a call to 'setConfig' and (if\n-- appropriate) 'setParams'.\n--\nlaunch :: String -> IO ()\nlaunch fn = nothingIfOk =<< cudaLaunch fn\n\n{# fun unsafe cudaLaunch\n { withCString* `String' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"83abf8e792a5607421582f841a3f1511ae03bf15","subject":"support for {s,d}asum","message":"support for {s,d}asum\n","repos":"alpmestan\/hs-cublas","old_file":"Foreign\/CUDA\/BLAS\/Level1.chs","new_file":"Foreign\/CUDA\/BLAS\/Level1.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.BLAS.Level1 \n ( \n -- * Dot products\n sdot\n , ddot\n\n -- * Absolute sum of elements\n , sasum\n , dasum\n\n -- * Scalar multiplication and vector addition\n , saxpy\n , daxpy\n\n -- * Norm2 of vectors\n , snrm2\n , dnrm2\n\n -- * Scaling\n , sscal\n , dscal\n\n -- * Raw bindings\n , cublasSdot\n , cublasDdot\n , cublasSasum\n , cublasDasum\n , cublasSaxpy\n , cublasDaxpy\n , cublasSnrm2\n , cublasDnrm2\n , cublasSscal\n , cublasDscal\n ) where\n\nimport Foreign.CUDA.BLAS.Internal.C2HS\nimport Foreign.CUDA.BLAS.Error\nimport Foreign.CUDA.BLAS.Helper\n\n-- from the 'cuda' package\nimport Foreign.CUDA.Ptr\n\nimport Foreign\nimport Foreign.C\nimport Foreign.Storable\n\n#include \n{# context lib=\"cublas\" #}\n\n{# fun unsafe cublasSdot_v2 as cublasSdot\n { useHandle `Handle' \n , `Int'\n , useDev `DevicePtr Float'\n , `Int'\n , useDev `DevicePtr Float'\n , `Int'\n , useDev `DevicePtr Float' } -> `Status' cToEnum #}\n\n\n{# fun unsafe cublasDdot_v2 as cublasDdot \n { useHandle `Handle' \n , `Int'\n , useDev `DevicePtr Double'\n , `Int'\n , useDev `DevicePtr Double'\n , `Int'\n , useDev `DevicePtr Double' } -> `Status' cToEnum #}\n\nuseDev = useDevicePtr . castDevPtr\n\n-- | CUBLAS dot product for 'Float's\nsdot :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the two input vectors\n -> DevicePtr Float -> Int -- ^ first input vector and its stride\n -> DevicePtr Float -> Int -- ^ second input vector and its stride\n -> DevicePtr Float -- ^ 0-dimensional output vector\n -> IO ()\nsdot h n v1 stride1 v2 stride2 oPtr =\n nothingIfOk =<< cublasSdot h n v1 stride1 v2 stride2 oPtr\n\n-- | CUBLAS dot product for 'Double's\nddot :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the two input vectors\n -> DevicePtr Double -> Int -- ^ first input vector and its stride\n -> DevicePtr Double -> Int -- ^ second input vector and its stride\n -> DevicePtr Double -- ^ 0-dimensional output vector\n -> IO ()\nddot h n v1 stride1 v2 stride2 oPtr =\n nothingIfOk =<< cublasDdot h n v1 stride1 v2 stride2 oPtr\n\n{# fun unsafe cublasSasum_v2 as cublasSasum\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float' \n , `Int'\n , useDev `DevicePtr Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDasum_v2 as cublasDasum\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Double' \n , `Int'\n , useDev `DevicePtr Double' } -> `Status' cToEnum #}\n\n-- | Absolute sum of vector elements for 'Float's\nsasum :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the input vector\n -> DevicePtr Float -> Int -- ^ first input vector and its stride\n -> DevicePtr Float -- ^ 0-dim output vector\n -> IO ()\nsasum h n v stride outPtr = nothingIfOk =<< cublasSasum h n v stride outPtr\n\n-- | Absolute sum of vector elements for 'Double's\ndasum :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the input vector\n -> DevicePtr Double -> Int -- ^ input vector and its stride\n -> DevicePtr Double -- ^ 0-dim output vector\n -> IO ()\ndasum h n v stride outPtr = nothingIfOk =<< cublasDasum h n v stride outPtr\n\n{# fun unsafe cublasSaxpy_v2 as cublasSaxpy \n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float'\n , useDev `DevicePtr Float' \n , `Int'\n , useDev `DevicePtr Float' \n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDaxpy_v2 as cublasDaxpy\n { useHandle `Handle' \n , `Int'\n , useDev `DevicePtr Double'\n , useDev `DevicePtr Double' \n , `Int'\n , useDev `DevicePtr Double' \n , `Int' } -> `Status' cToEnum #}\n\n-- | Vector scaling and addition all at once, for 'Float's\nsaxpy :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the vector\n -> DevicePtr Float -- ^ Scalar \/alpha\/, by which we scale the first vector\n -> DevicePtr Float -- ^ first vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Float -- ^ second vector, \/y\/, which gets overwritten by the result of \/alpha*x + y\/\n -> Int -- ^ stride for \/y\/\n -> IO ()\nsaxpy h n alpha x strX y strY = nothingIfOk =<< cublasSaxpy h n alpha x strX y strY\n\n-- | Vector scaling and addition all at once, for 'Double's\ndaxpy :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the vector\n -> DevicePtr Double -- ^ Scalar \/alpha\/, by which we scale the first vector\n -> DevicePtr Double -- ^ first vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Double -- ^ second vector, \/y\/, which gets overwritten by the result of \/alpha.x + y\/\n -> Int -- ^ stride for \/y\/\n -> IO ()\ndaxpy h n alpha x strX y strY = nothingIfOk =<< cublasDaxpy h n alpha x strX y strY\n\n{# fun unsafe cublasSnrm2_v2 as cublasSnrm2\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float'\n , `Int'\n , useDev `DevicePtr Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDnrm2_v2 as cublasDnrm2\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Double'\n , `Int'\n , useDev `DevicePtr Double' } -> `Status' cToEnum #}\n\n-- | Norm2 of a vector, for 'Float' elements\nsnrm2 :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of element in \/x\/\n -> DevicePtr Float -- ^ vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Float -- ^ output scalar, equal to the norm2 of \/x\/\n -> IO ()\nsnrm2 h n x strX out = nothingIfOk =<< cublasSnrm2 h n x strX out\n\n-- | Norm2 of a vector, for 'Double' elements\ndnrm2 :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of element in \/x\/\n -> DevicePtr Double -- ^ vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Double -- ^ output scalar, equal to the norm2 of \/x\/\n -> IO ()\ndnrm2 h n x strX out = nothingIfOk =<< cublasDnrm2 h n x strX out\n\n{# fun unsafe cublasSscal_v2 as cublasSscal \n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float'\n , useDev `DevicePtr Float'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDscal_v2 as cublasDscal \n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Double'\n , useDev `DevicePtr Double'\n , `Int' } -> `Status' cToEnum #}\n\n-- | Scales a vector in-place, for 'Float's\nsscal :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of elements in \/x\/\n -> DevicePtr Float -- ^ scalar \/alpha\/ by which we scale \/x\/\n -> DevicePtr Float -- ^ vector, \/x\/, which gets overwritten by the result of \/alpha.x\/\n -> Int -- ^ stride for \/x\/\n -> IO ()\nsscal h n alpha x strX = nothingIfOk =<< cublasSscal h n alpha x strX\n\n-- | Scales a vector in-place, for 'Double's\ndscal :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of elements in \/x\/\n -> DevicePtr Double -- ^ scalar \/alpha\/ by which we scale \/x\/\n -> DevicePtr Double -- ^ vector, \/x\/, which gets overwritten by the result of \/alpha.x\/\n -> Int -- ^ stride for \/x\/\n -> IO ()\ndscal h n alpha x strX = nothingIfOk =<< cublasDscal h n alpha x strX","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.BLAS.Level1 \n ( \n -- * Dot products\n sdot\n , ddot\n\n -- * Absolute sum of elements\n , sasum\n , dasum\n\n -- * Scalar multiplication and vector addition\n , saxpy\n , daxpy\n\n -- * Norm2 of vectors\n , snrm2\n , dnrm2\n\n -- * Scaling\n , sscal\n , dscal\n\n -- * Raw bindings\n , cublasSdot\n , cublasDdot\n , cublasSasum\n , cublasDasum\n , cublasSaxpy\n , cublasDaxpy\n , cublasSnrm2\n , cublasDnrm2\n , cublasSscal\n , cublasDscal\n ) where\n\nimport Foreign.CUDA.BLAS.Internal.C2HS\nimport Foreign.CUDA.BLAS.Error\nimport Foreign.CUDA.BLAS.Helper\n\n-- from the 'cuda' package\nimport Foreign.CUDA.Ptr\n\nimport Foreign\nimport Foreign.C\nimport Foreign.Storable\n\n#include \n{# context lib=\"cublas\" #}\n\n{# fun unsafe cublasSdot_v2 as cublasSdot\n { useHandle `Handle' \n , `Int'\n , useDev `DevicePtr Float'\n , `Int'\n , useDev `DevicePtr Float'\n , `Int'\n , useDev `DevicePtr Float' } -> `Status' cToEnum #}\n\n\n{# fun unsafe cublasDdot_v2 as cublasDdot \n { useHandle `Handle' \n , `Int'\n , useDev `DevicePtr Double'\n , `Int'\n , useDev `DevicePtr Double'\n , `Int'\n , useDev `DevicePtr Double' } -> `Status' cToEnum #}\n\nuseDev = useDevicePtr . castDevPtr\n\n-- | CUBLAS dot product for 'Float's\nsdot :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the two input vectors\n -> DevicePtr Float -> Int -- ^ first input vector and its stride\n -> DevicePtr Float -> Int -- ^ second input vector and its stride\n -> DevicePtr Float -- ^ 0-dimensional output vector\n -> IO ()\nsdot h n v1 stride1 v2 stride2 oPtr =\n nothingIfOk =<< cublasSdot h n v1 stride1 v2 stride2 oPtr\n\n-- | CUBLAS dot product for 'Double's\nddot :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the two input vectors\n -> DevicePtr Double -> Int -- ^ first input vector and its stride\n -> DevicePtr Double -> Int -- ^ second input vector and its stride\n -> DevicePtr Double -- ^ 0-dimensional output vector\n -> IO ()\nddot h n v1 stride1 v2 stride2 oPtr =\n nothingIfOk =<< cublasDdot h n v1 stride1 v2 stride2 oPtr\n\n{# fun unsafe cublasSasum_v2 as cublasSasum\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float' \n , `Int'\n , useDev `DevicePtr Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDasum_v2 as cublasDasum\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Double' \n , `Int'\n , useDev `DevicePtr Double' } -> `Status' cToEnum #}\n\n-- | Absolute sum of vector element for 'Float's\nsasum :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the input vector\n -> DevicePtr Float -> Int -- ^ first input vector and its stride\n -> DevicePtr Float -- ^ 0-dim output vector\n -> IO ()\nsasum h n v stride outPtr = nothingIfOk =<< cublasSasum h n v stride outPtr\n\n-- | Absolute sum of vector element for 'Double's\ndasum :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the input vector\n -> DevicePtr Double -> Int -- ^ first input vector and its stride\n -> DevicePtr Double -- ^ 0-dim output vector\n -> IO ()\ndasum h n v stride outPtr = nothingIfOk =<< cublasDasum h n v stride outPtr\n\n{# fun unsafe cublasSaxpy_v2 as cublasSaxpy \n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float'\n , useDev `DevicePtr Float' \n , `Int'\n , useDev `DevicePtr Float' \n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDaxpy_v2 as cublasDaxpy\n { useHandle `Handle' \n , `Int'\n , useDev `DevicePtr Double'\n , useDev `DevicePtr Double' \n , `Int'\n , useDev `DevicePtr Double' \n , `Int' } -> `Status' cToEnum #}\n\n-- | Vector scaling and addition all at once, for 'Float's\nsaxpy :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the vector\n -> DevicePtr Float -- ^ Scalar \/alpha\/, by which we scale the first vector\n -> DevicePtr Float -- ^ first vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Float -- ^ second vector, \/y\/, which gets overwritten by the result of \/alpha*x + y\/\n -> Int -- ^ stride for \/y\/\n -> IO ()\nsaxpy h n alpha x strX y strY = nothingIfOk =<< cublasSaxpy h n alpha x strX y strY\n\n-- | Vector scaling and addition all at once, for 'Double's\ndaxpy :: Handle -- ^ CUBLAS context\n -> Int -- ^ Number of elements in the vector\n -> DevicePtr Double -- ^ Scalar \/alpha\/, by which we scale the first vector\n -> DevicePtr Double -- ^ first vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Double -- ^ second vector, \/y\/, which gets overwritten by the result of \/alpha.x + y\/\n -> Int -- ^ stride for \/y\/\n -> IO ()\ndaxpy h n alpha x strX y strY = nothingIfOk =<< cublasDaxpy h n alpha x strX y strY\n\n{# fun unsafe cublasSnrm2_v2 as cublasSnrm2\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float'\n , `Int'\n , useDev `DevicePtr Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDnrm2_v2 as cublasDnrm2\n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Double'\n , `Int'\n , useDev `DevicePtr Double' } -> `Status' cToEnum #}\n\n-- | Norm2 of a vector, for 'Float' elements\nsnrm2 :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of element in \/x\/\n -> DevicePtr Float -- ^ vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Float -- ^ output scalar, equal to the norm2 of \/x\/\n -> IO ()\nsnrm2 h n x strX out = nothingIfOk =<< cublasSnrm2 h n x strX out\n\n-- | Norm2 of a vector, for 'Double' elements\ndnrm2 :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of element in \/x\/\n -> DevicePtr Double -- ^ vector, \/x\/\n -> Int -- ^ stride for \/x\/\n -> DevicePtr Double -- ^ output scalar, equal to the norm2 of \/x\/\n -> IO ()\ndnrm2 h n x strX out = nothingIfOk =<< cublasDnrm2 h n x strX out\n\n{# fun unsafe cublasSscal_v2 as cublasSscal \n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Float'\n , useDev `DevicePtr Float'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cublasDscal_v2 as cublasDscal \n { useHandle `Handle'\n , `Int'\n , useDev `DevicePtr Double'\n , useDev `DevicePtr Double'\n , `Int' } -> `Status' cToEnum #}\n\n-- | Scales a vector in-place, for 'Float's\nsscal :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of elements in \/x\/\n -> DevicePtr Float -- ^ scalar \/alpha\/ by which we scale \/x\/\n -> DevicePtr Float -- ^ vector, \/x\/, which gets overwritten by the result of \/alpha.x\/\n -> Int -- ^ stride for \/x\/\n -> IO ()\nsscal h n alpha x strX = nothingIfOk =<< cublasSscal h n alpha x strX\n\n-- | Scales a vector in-place, for 'Double's\ndscal :: Handle -- ^ CUBLAS context\n -> Int -- ^ number of elements in \/x\/\n -> DevicePtr Double -- ^ scalar \/alpha\/ by which we scale \/x\/\n -> DevicePtr Double -- ^ vector, \/x\/, which gets overwritten by the result of \/alpha.x\/\n -> Int -- ^ stride for \/x\/\n -> IO ()\ndscal h n alpha x strX = nothingIfOk =<< cublasDscal h n alpha x strX","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9cb579859b8ae897f61e8adb96a78513dd3eda47","subject":"Comm entries reordered in haddock for better readability","message":"Comm entries reordered in haddock for better readability\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 -- ** 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\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":"bd5296e0dfd3be21c2b08885859a6a1e8685b556","subject":"Tidy-up marshalling interface","message":"Tidy-up marshalling interface\n\nIgnore-this: d2b9fb1206f4a304a9d69c6cc3f4ab65\n- Have function names make it explicit that the focus is operating over\n collections of data (Array and List)\n- Add several convenience functions, for temporary allocation of arrays and\n marshalling data between Haskell lists and device arrays\n\ndarcs-hash:20091221101434-dcabc-3992b11e7794a676fb45533fb224798c51925ef0.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/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,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n\n -- * Combined Allocation and Marshalling\n newListArray, withListArray,\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-- 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 = bracket (newListArray xs) free\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 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d9092639a67b6163c23bf51dc96235a7f8c7c5a3","subject":"update with new combined alloca+memset","message":"update with new combined alloca+memset\n\nIgnore-this: f4560d7d75e1c6aac94be13acb58e6f8\n\ndarcs-hash:20090911082427-9241b-b8681ed812f5a0c36b5e602cb6807241f43ff0dd.gz\n","repos":"tmcdonell\/hfx,tmcdonell\/hfx,tmcdonell\/hfx","old_file":"src\/IonSeries.chs","new_file":"src\/IonSeries.chs","new_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : IonSeries\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Functions to work with a series of ions, and generate theoretical spectra\n-- suitable for matching against experimental results with the sequest\n-- cross-correlation algorithm.\n--\n--------------------------------------------------------------------------------\n\nmodule IonSeries\n (\n XCorrSpecThry(..),\n buildThrySpecXCorr\n )\n where\n\n#include \"kernels\/kernels.h\"\n\nimport Config\nimport Protein\n\nimport C2HS\nimport Foreign.CUDA (DevicePtr, withDevicePtr)\nimport qualified Foreign.CUDA as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Data structures\n--------------------------------------------------------------------------------\n\n--\n-- The mz\/intensity spectrum array for the theoretical spectrum. Keep this as a\n-- sparse array, as there are so few elements compared to the experimental data.\n--\n-- XXX: Changed to a dense array on the device, to facilitate eventual dot\n-- product operation (and because my cuda-fu is weak...)\n--\ndata XCorrSpecThry = XCorrSpecThry\n (Int,Int)\n (CUDA.DevicePtr Int)\n\n\n--------------------------------------------------------------------------------\n-- Theoretical Spectrum\n--------------------------------------------------------------------------------\n\n--\n-- Generate the theoretical spectral representation of a peptide from its\n-- character code sequence, and do something useful with it. The device memory\n-- is deallocated once the action completes.\n--\nbuildThrySpecXCorr :: ConfigParams\n -> (Int,Int) -- ^ bounds of the output array\n -> Int -- ^ precursor charge state\n -> Peptide -- ^ peptide to build spectrum for\n -> (XCorrSpecThry -> IO b) -- ^ action to perform\n -> IO b\nbuildThrySpecXCorr _cp (m,n) chrg pep action =\n CUDA.allocaBytesMemset bytes 0 $ \\spec -> do\n CUDA.withArrayLen (bIonLadder pep) $ \\l b_ions -> do\n CUDA.withArray (yIonLadder pep) $ \\y_ions -> do\n addIons chrg b_ions y_ions spec l len >> do\n\n action (XCorrSpecThry (m,n) spec)\n\n where\n len = n - m + 1\n bytes = fromIntegral len * fromIntegral (sizeOf (undefined::Int))\n\n\n{# fun unsafe addIons\n { cIntConv `Int' ,\n withDevicePtr* `DevicePtr Float' ,\n withDevicePtr* `DevicePtr Float' ,\n withDevicePtr* `DevicePtr Int' ,\n cIntConv `Int' ,\n cIntConv `Int' } -> `()' #}\n\n#if 0\nbuildThrySpecXCorr :: ConfigParams -> Int -> Int -> Peptide -> IO XCorrSpecThry\nbuildThrySpecXCorr _cp len_spec charge peptide = do\n spec <- CUDA.forceEither `fmap` CUDA.malloc bytes\n rv <- CUDA.memset spec bytes 0\n\n case rv of\n Just e -> error e\n Nothing -> CUDA.withArrayLen (bIonLadder peptide) $ \\len_ions b_ions -> do\n CUDA.withArray (yIonLadder peptide) $ \\y_ions -> do\n addIons charge b_ions y_ions spec len_ions len_spec\n\n return $ XCorrSpecThry (0,len_spec) spec\n\n where\n bytes = fromIntegral (len_spec * sizeOf (undefined::Int))\n#endif\n#if 0\n--\n-- Sequential version\n--\nbuildThrySpecXCorr :: ConfigParams -> Float -> Peptide -> XCorrSpecThry\nbuildThrySpecXCorr _cp charge peptide =\n concatMap addIons $ [1 .. (max 1 (charge-1))]\n where\n addIons c = concatMap (addIonsAB c) b_ions ++ concatMap (addIonsY c) y_ions\n b_ions = bIonLadder peptide\n y_ions = yIonLadder peptide\n\n--\n-- Convert mass to mass\/charge ratio\n--\nionMZ :: Float -> Float -> Float\nionMZ m c = (m + massH*c) \/ c\n\n\n--\n-- Add a spectral peak for each fragment location, as well as the peaks\n-- corresponding to neutral losses of H2O and NH3.\n--\n-- The factors that contribute to the collision induced dissociation process\n-- used in tandem-MS experiments are not completely understood, so accurate\n-- prediction of fragment ion abundances are not possible. Magnitude components\n-- are assigned based on empirical knowledge.\n--\naddIonsAB, addIonsY :: Float -> Float -> [(Float, Float)]\naddIonsAB charge mass = addIonsA : addIonsB\n where\n addIonsA = let m = ionMZ (mass - massCO) charge in (m, 10)\n addIonsB = let m = ionMZ mass charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massH2O\/charge, 10),\n (m - massNH3\/charge, 10)\n ]\n\naddIonsY charge mass =\n let m = ionMZ (mass + massH2O) charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massNH3\/charge, 10)\n ]\n#endif\n\n","old_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : IonSeries\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Functions to work with a series of ions, and generate theoretical spectra\n-- suitable for matching against experimental results with the sequest\n-- cross-correlation algorithm.\n--\n--------------------------------------------------------------------------------\n\nmodule IonSeries where\n\n#include \"kernels\/kernels.h\"\n\nimport Config\nimport Protein\n\nimport C2HS\nimport qualified Foreign.CUDA as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Data structures\n--------------------------------------------------------------------------------\n\n--\n-- The mz\/intensity spectrum array for the theoretical spectrum. Keep this as a\n-- sparse array, as there are so few elements compared to the experimental data.\n--\n-- XXX: Changed to a dense array on the device, to facilitate eventual dot\n-- product operation (and because my cuda-fu is weak...)\n--\ndata XCorrSpecThry = XCorrSpecThry\n (Int,Int)\n (CUDA.DevicePtr Int)\n\n\n--------------------------------------------------------------------------------\n-- Theoretical Spectrum\n--------------------------------------------------------------------------------\n\n--\n-- Generate the theoretical spectral representation of a peptide from its\n-- character code sequence, and do something useful with it. The device memory\n-- is deallocated once the action completes.\n--\nbuildThrySpecXCorr :: ConfigParams\n -> (Int,Int) -- ^ bounds of the output array\n -> Int -- ^ precursor charge state\n -> Peptide -- ^ peptide to build spectrum for\n -> (XCorrSpecThry -> IO b) -- ^ action to perform\n -> IO b\nbuildThrySpecXCorr _cp (m,n) chrg pep fun =\n CUDA.allocaBytes bytes $ \\spec ->\n CUDA.memset spec bytes 0 >>= \\rv -> case rv of\n Just e -> error e\n Nothing -> CUDA.withArrayLen (bIonLadder pep) $ \\n b_ions -> do\n CUDA.withArray (yIonLadder pep) $ \\y_ions -> do\n addIons chrg b_ions y_ions spec n len >> do\n\n fun (XCorrSpecThry (m,n) spec)\n where\n len = n - m + 1\n bytes = fromIntegral len * fromIntegral (sizeOf (undefined::Int))\n\n\n#if 0\nbuildThrySpecXCorr :: ConfigParams -> Int -> Int -> Peptide -> IO XCorrSpecThry\nbuildThrySpecXCorr _cp len_spec charge peptide = do\n spec <- CUDA.forceEither `fmap` CUDA.malloc bytes\n rv <- CUDA.memset spec bytes 0\n\n case rv of\n Just e -> error e\n Nothing -> CUDA.withArrayLen (bIonLadder peptide) $ \\len_ions b_ions -> do\n CUDA.withArray (yIonLadder peptide) $ \\y_ions -> do\n addIons charge b_ions y_ions spec len_ions len_spec\n\n return $ XCorrSpecThry (0,len_spec) spec\n\n where\n bytes = fromIntegral (len_spec * sizeOf (undefined::Int))\n#endif\n\n\n{# fun unsafe addIons\n { cIntConv `Int' ,\n withDevicePtr* `CUDA.DevicePtr Float' ,\n withDevicePtr* `CUDA.DevicePtr Float' ,\n withDevicePtr* `CUDA.DevicePtr Int' ,\n cIntConv `Int' ,\n cIntConv `Int' } -> `()' #}\n where\n withDevicePtr = CUDA.withDevicePtr\n\n\n#if 0\n--\n-- Sequential version\n--\nbuildThrySpecXCorr :: ConfigParams -> Float -> Peptide -> XCorrSpecThry\nbuildThrySpecXCorr _cp charge peptide =\n concatMap addIons $ [1 .. (max 1 (charge-1))]\n where\n addIons c = concatMap (addIonsAB c) b_ions ++ concatMap (addIonsY c) y_ions\n b_ions = bIonLadder peptide\n y_ions = yIonLadder peptide\n\n--\n-- Convert mass to mass\/charge ratio\n--\nionMZ :: Float -> Float -> Float\nionMZ m c = (m + massH*c) \/ c\n\n\n--\n-- Add a spectral peak for each fragment location, as well as the peaks\n-- corresponding to neutral losses of H2O and NH3.\n--\n-- The factors that contribute to the collision induced dissociation process\n-- used in tandem-MS experiments are not completely understood, so accurate\n-- prediction of fragment ion abundances are not possible. Magnitude components\n-- are assigned based on empirical knowledge.\n--\naddIonsAB, addIonsY :: Float -> Float -> [(Float, Float)]\naddIonsAB charge mass = addIonsA : addIonsB\n where\n addIonsA = let m = ionMZ (mass - massCO) charge in (m, 10)\n addIonsB = let m = ionMZ mass charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massH2O\/charge, 10),\n (m - massNH3\/charge, 10)\n ]\n\naddIonsY charge mass =\n let m = ionMZ (mass + massH2O) charge in\n [\n (m,50), (m+1,25), (m-1,25),\n (m - massNH3\/charge, 10)\n ]\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"517f476b875def74d3802d373f504fa93356e4fb","subject":"INLINE pragma only useful inside WIN32 block","message":"INLINE pragma only useful inside WIN32 block\n\nMove the INLINE pragma inside the WIN32 block. For other platforms we just have a plain foreign C import, so the INLINE pragma is not useful (I don't think).\n\nMoreover, GHC-HEAD complains about this.\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module\/Base.chs","new_file":"Foreign\/CUDA\/Driver\/Module\/Base.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module.Base\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Module loading for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module.Base (\n\n -- * Module Management\n Module(..),\n JITOption(..), JITTarget(..), JITResult(..), JITFallback(..), JITInputType(..),\n JITOptionInternal(..),\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload,\n\n -- Internal\n jitOptionUnpack, jitTargetOfCompute,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\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\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\n\n-- |\n-- Just-in-time compilation and linking 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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ the compiled module\n }\n deriving (Show)\n\n\n-- |\n-- Online compilation target architecture\n--\n{# enum CUjit_target as JITTarget\n { underscoreToCase }\n with prefix=\"CU_TARGET\" deriving (Eq, Show) #}\n\n-- |\n-- Online compilation fallback strategy\n--\n{# enum CUjit_fallback as JITFallback\n { underscoreToCase\n , CU_PREFER_PTX as PreferPTX }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n-- |\n-- Device code formats that can be used for online linking\n--\n{# enum CUjitInputType as JITInputType\n { underscoreToCase\n , CU_JIT_INPUT_PTX as PTX }\n with prefix=\"CU_JIT_INPUT\" deriving (Eq, Show) #}\n\n{# enum CUjit_option as JITOptionInternal\n { }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\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--\n-- \n--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n let logSize = 2048\n\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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))\n ]\n ++\n map jitOptionUnpack options\n\n withArrayLen (map cFromEnum opt) $ \\i p_opts -> do\n withArray (map unsafeCoerce val) $ \\ p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img i p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context.\n--\n-- \n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n\n{-# INLINE jitOptionUnpack #-}\njitOptionUnpack :: JITOption -> (JITOptionInternal, Int)\njitOptionUnpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\njitOptionUnpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\njitOptionUnpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\njitOptionUnpack (Target x) = (JIT_TARGET, fromEnum (jitTargetOfCompute x))\njitOptionUnpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\njitOptionUnpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\njitOptionUnpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\njitOptionUnpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n#else\njitOptionUnpack GenerateDebugInfo = requireSDK 'GenerateDebugInfo 5.5\njitOptionUnpack GenerateLineInfo = requireSDK 'GenerateLineInfo 5.5\njitOptionUnpack Verbose = requireSDK 'Verbose 5.5\n#endif\n\n\n{-# INLINE jitTargetOfCompute #-}\njitTargetOfCompute :: Compute -> JITTarget\njitTargetOfCompute (Compute 1 0) = Compute10\njitTargetOfCompute (Compute 1 1) = Compute11\njitTargetOfCompute (Compute 1 2) = Compute12\njitTargetOfCompute (Compute 1 3) = Compute13\njitTargetOfCompute (Compute 2 0) = Compute20\njitTargetOfCompute (Compute 2 1) = Compute21\njitTargetOfCompute (Compute 3 0) = Compute30\njitTargetOfCompute (Compute 3 5) = Compute35\n#if CUDA_VERSION >= 6000\njitTargetOfCompute (Compute 3 2) = Compute32\njitTargetOfCompute (Compute 5 0) = Compute50\n#endif\n#if CUDA_VERSION >= 6050\njitTargetOfCompute (Compute 3 7) = Compute37\n#endif\n#if CUDA_VERSION >= 7000\njitTargetOfCompute (Compute 5 2) = Compute52\n#endif\njitTargetOfCompute compute = error (\"Unknown JIT Target for Compute \" ++ show compute)\n\n\n#if defined(WIN32)\n{-# INLINE c_strnlen' #-}\nc_strnlen' :: CString -> CSize -> IO CSize\nc_strnlen' str size = do\n str' <- peekCStringLen (str, fromIntegral size)\n return $ stringLen 0 str'\n where\n stringLen acc [] = acc\n stringLen acc ('\\0':_) = acc\n stringLen acc (_:xs) = stringLen (acc+1) xs\n#else\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n#endif\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module.Base\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Module loading for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module.Base (\n\n -- * Module Management\n Module(..),\n JITOption(..), JITTarget(..), JITResult(..), JITFallback(..), JITInputType(..),\n JITOptionInternal(..),\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload,\n\n -- Internal\n jitOptionUnpack, jitTargetOfCompute,\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\nimport Foreign.CUDA.Driver.Error\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\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\n\n-- |\n-- Just-in-time compilation and linking 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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ the compiled module\n }\n deriving (Show)\n\n\n-- |\n-- Online compilation target architecture\n--\n{# enum CUjit_target as JITTarget\n { underscoreToCase }\n with prefix=\"CU_TARGET\" deriving (Eq, Show) #}\n\n-- |\n-- Online compilation fallback strategy\n--\n{# enum CUjit_fallback as JITFallback\n { underscoreToCase\n , CU_PREFER_PTX as PreferPTX }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n-- |\n-- Device code formats that can be used for online linking\n--\n{# enum CUjitInputType as JITInputType\n { underscoreToCase\n , CU_JIT_INPUT_PTX as PTX }\n with prefix=\"CU_JIT_INPUT\" deriving (Eq, Show) #}\n\n{# enum CUjit_option as JITOptionInternal\n { }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\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--\n-- \n--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n-- \n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n let logSize = 2048\n\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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))\n ]\n ++\n map jitOptionUnpack options\n\n withArrayLen (map cFromEnum opt) $ \\i p_opts -> do\n withArray (map unsafeCoerce val) $ \\ p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img i p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context.\n--\n-- \n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n\n{-# INLINE jitOptionUnpack #-}\njitOptionUnpack :: JITOption -> (JITOptionInternal, Int)\njitOptionUnpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\njitOptionUnpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\njitOptionUnpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\njitOptionUnpack (Target x) = (JIT_TARGET, fromEnum (jitTargetOfCompute x))\njitOptionUnpack (FallbackStrategy x) = (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\njitOptionUnpack GenerateDebugInfo = (JIT_GENERATE_DEBUG_INFO, fromEnum True)\njitOptionUnpack GenerateLineInfo = (JIT_GENERATE_LINE_INFO, fromEnum True)\njitOptionUnpack Verbose = (JIT_LOG_VERBOSE, fromEnum True)\n#else\njitOptionUnpack GenerateDebugInfo = requireSDK 'GenerateDebugInfo 5.5\njitOptionUnpack GenerateLineInfo = requireSDK 'GenerateLineInfo 5.5\njitOptionUnpack Verbose = requireSDK 'Verbose 5.5\n#endif\n\n\n{-# INLINE jitTargetOfCompute #-}\njitTargetOfCompute :: Compute -> JITTarget\njitTargetOfCompute (Compute 1 0) = Compute10\njitTargetOfCompute (Compute 1 1) = Compute11\njitTargetOfCompute (Compute 1 2) = Compute12\njitTargetOfCompute (Compute 1 3) = Compute13\njitTargetOfCompute (Compute 2 0) = Compute20\njitTargetOfCompute (Compute 2 1) = Compute21\njitTargetOfCompute (Compute 3 0) = Compute30\njitTargetOfCompute (Compute 3 5) = Compute35\n#if CUDA_VERSION >= 6000\njitTargetOfCompute (Compute 3 2) = Compute32\njitTargetOfCompute (Compute 5 0) = Compute50\n#endif\n#if CUDA_VERSION >= 6050\njitTargetOfCompute (Compute 3 7) = Compute37\n#endif\n#if CUDA_VERSION >= 7000\njitTargetOfCompute (Compute 5 2) = Compute52\n#endif\njitTargetOfCompute compute = error (\"Unknown JIT Target for Compute \" ++ show compute)\n\n\n{-# INLINE c_strnlen' #-}\n#if defined(WIN32)\nc_strnlen' :: CString -> CSize -> IO CSize\nc_strnlen' str size = do\n str' <- peekCStringLen (str, fromIntegral size)\n return $ stringLen 0 str'\n where\n stringLen acc [] = acc\n stringLen acc ('\\0':_) = acc\n stringLen acc (_:xs) = stringLen (acc+1) xs\n#else\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n#endif\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e5093ffef5d03b12d1a08e9cfd418105e18bc424","subject":"Fix return type of 'modal' and 'grab'.","message":"Fix return type of 'modal' and 'grab'.\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 WidgetBase))\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 WindowBase))\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 WindowBase))\nnextWindow currWindow = withRef currWindow (\\ptr -> nextWindow' ptr >>= toMaybeRef)\n\n{# fun Fl_modal as modal' { } -> `Ptr ()' #}\nmodal :: IO (Maybe (Ref WindowBase))\nmodal = modal' >>= toMaybeRef\n\n{# fun Fl_grab as grab' { } -> `Ptr ()' #}\ngrab :: IO (Maybe (Ref WindowBase))\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 WidgetBase))\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 WidgetBase))\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 WidgetBase))\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 WindowBase] -> Maybe (Ref WindowBase) -> IO [Ref WindowBase]\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 WidgetBase))\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 WindowBase))\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 WindowBase))\nnextWindow currWindow = withRef currWindow (\\ptr -> nextWindow' ptr >>= toMaybeRef)\n\n{# fun Fl_modal as modal' { } -> `Ptr ()' #}\nmodal :: IO (Maybe (Ref WidgetBase))\nmodal = modal' >>= toMaybeRef\n\n{# fun Fl_grab as grab' { } -> `Ptr ()' #}\ngrab :: IO (Maybe (Ref WidgetBase))\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 WidgetBase))\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 WidgetBase))\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 WidgetBase))\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 WindowBase] -> Maybe (Ref WindowBase) -> IO [Ref WindowBase]\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":"5317f9709515c39e9e19eeb032221803f6a1e210","subject":"gstreamer: M.S.G.Core.Types code cleanups","message":"gstreamer: M.S.G.Core.Types code cleanups","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"8e62c88d5de110836f6503d2e15195d09149fbbb","subject":"Last few blobs and refactor","message":"Last few blobs and refactor\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\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\ncreateBlobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\ncreateBlobFromFile (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\ncreateBlobFromBuffer :: ObjID -> Repository -> CPtr -> Int -> IO (Maybe GitError)\ncreateBlobFromBuffer (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 -> 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\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-- 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 -> IO Int\nrawBlobSize (Blob b) = return . fromIntegral =<< {#call git_blob_rawsize#} b\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7646f8283a5dd9c5e9037b0aa463d401f979b41f","subject":"More robustness against NULL pointers","message":"More robustness against NULL pointers\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 ( 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","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 when (sp == nullPtr) (error \"Null ptr in string\")\n str <- liftIO $ BS.packCString sp\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":"f3b319f66ac962c464ddc15b8fce7bd08e64f929","subject":"Add property functions for Char type","message":"Add property functions for Char type\n","repos":"gtk2hs\/gtksourceview,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 objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\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\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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 writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"935dcc32d85c52194c13833a659013707b98a7d0","subject":"[project @ 2004-05-20 16:53:58 by duncan_coutts]","message":"[project @ 2004-05-20 16:53:58 by duncan_coutts]\n\nhaddock fix\n\ndarcs-hash:20040520165358-d6ff7-5511141498b62881d733123dc6f8709fb59004db.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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":"1ca7fd71fadd0047331adbe887160affe9d93cfc","subject":"fix inverted logic","message":"fix inverted logic\n\nIgnore-this: 4ca3c12d089f93cdfc1ee6a0edcfb080\n\ndarcs-hash:20090718052751-115f9-38e6e60b3616328e61605459bc3548e6a6c1cd3a.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Utils.chs","new_file":"Foreign\/CUDA\/Utils.chs","new_contents":"{-\n - Utilities\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Utils\n (\n getErrorString, resultIfOk, nothingIfOk\n )\n where\n\nimport Foreign.CUDA.Types\n\nimport Foreign.CUDA.Internal.C2HS\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Error Handling\n--------------------------------------------------------------------------------\n\n--\n-- Return the descriptive string associated with a particular error code.\n-- Logically, this must a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n{# fun pure unsafe GetErrorString as ^\n { cFromEnum `Result' } -> `String' #}\n\n\nresultIfOk :: (Result, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (getErrorString status)\n\nnothingIfOk :: Result -> Maybe String\nnothingIfOk = nothingIf (== Success) getErrorString\n\n","old_contents":"{-\n - Utilities\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Utils\n (\n getErrorString, resultIfOk, nothingIfOk\n )\n where\n\nimport Foreign.CUDA.Types\n\nimport Foreign.CUDA.Internal.C2HS\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n\n--------------------------------------------------------------------------------\n-- Error Handling\n--------------------------------------------------------------------------------\n\n--\n-- Return the descriptive string associated with a particular error code.\n-- Logically, this must a pure function, returning a pointer to a statically\n-- defined string constant.\n--\n{# fun pure unsafe GetErrorString as ^\n { cFromEnum `Result' } -> `String' #}\n\n\nresultIfOk :: (Result, a) -> Either String a\nresultIfOk (status,result) =\n case status of\n Success -> Right result\n _ -> Left (getErrorString status)\n\nnothingIfOk :: Result -> Maybe String\nnothingIfOk = nothingIf (\/= Success) getErrorString\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c3341174130d92d3ec014d3579188d30da091945","subject":"remove warning","message":"remove warning\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 ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Band s t b' -> IO (Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Band s t b' -> IO (Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = reader band >>= mask\n where\n mask\n | hasFlag MaskPerDataset = useMaskBand\n | hasFlag MaskNoData = useNoData\n | hasFlag MaskAllValid = useAsIs\n | otherwise = useMaskBand\n hasFlag f = fromEnumC f .&. c_getMaskFlags band == fromEnumC f\n useAsIs = return . St.map Value\n useNoData vs = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand vs = do\n ms <- c_getMaskBand band >>= reader :: IO (Vector Word8)\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n len <- bandBlockLen band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n checkType b\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , isGDALException\n , Geotransform (..)\n , DriverOptions\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n\n , setQuietErrorHandler\n\n , registerAllDrivers\n , destroyDriverManager\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , unsafeLazyReadBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n -- Internal Util\n , throwIfError\n , unsafeWithDataset\n , unsafeWithBand\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception ( bracket, throw, Exception(..), SomeException\n , evaluate)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, foldM)\nimport Control.Monad.Trans.Resource (ResourceT, runResourceT, register)\nimport Control.Monad.IO.Class (MonadIO(..))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector)\nimport qualified Data.Vector.Storable as St\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: Word8)\n alignment _ = alignment (undefined :: a)\n\n {-# INLINE peek #-}\n peek p = do\n let p1 = (castPtr p::Ptr Word8) `plusPtr` 1\n t <- peek (castPtr p::Ptr Word8)\n if t\/=0\n then fmap Value (peekElemOff (castPtr p1 :: Ptr a) 0)\n else return NoData\n\n {-# INLINE poke #-}\n poke p x = case x of\n NoData -> poke (castPtr p :: Ptr Word8) 0\n Value a -> do\n poke (castPtr p :: Ptr Word8) 1\n let p1 = (castPtr p :: Ptr Word8) `plusPtr` 1\n pokeElemOff (castPtr p1) 0 a\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype GDAL s a = GDAL (ResourceT IO a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n registerAllDrivers\n runResourceT (a >>= liftIO . evaluate . force)\n\n\ndata GDALException = Unknown !Error !String\n | InvalidType\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize\n | DriverLoadError\n | NullDatasetHandle\n | InvalidBand !Int\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 $ Unknown e' msg\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a = Dataset (Ptr (Dataset s t a))\n\nunsafeWithDataset\n :: Dataset s t a -> (Ptr (Dataset s t a) -> GDAL s b) -> GDAL s b\nunsafeWithDataset (Dataset p) f = f p\n\nunsafeWithDatasetIO\n :: Dataset s t a -> (Ptr (Dataset s t a) -> IO b) -> GDAL s b\nunsafeWithDatasetIO ds f = unsafeWithDataset ds (liftIO . f)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s (t::DatasetMode) a) = Band (Ptr (Band s t a))\n\nunsafeWithBand\n :: Band s t a -> (Ptr (Band s t a) -> GDAL s b) -> GDAL s b\nunsafeWithBand (Band p) f = f p\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $ do\n driver@(DriverH ptr) <- c_driverByName (show s)\n if ptr==nullPtr\n then throw DriverLoadError\n else return driver\n\ntype DriverOptions = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> DriverOptions\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\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\n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n liftIO (withCString p $ \\p' -> open_ p' (fromEnumC m)) >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n if datatype (Proxy :: Proxy a) == dt\n then return ()\n else liftIO (throw InvalidType)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> DriverOptions\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path dataset strict options progressFun = do\n d <- driverByName driver\n ptr <- unsafeWithDatasetIO dataset $ \\ds -> do\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n c_createCopy d p ds s o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> DriverOptions\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $\n if p==nullPtr\n then liftIO $ throw NullDatasetHandle\n else do _ <- register (c_closeDataset p)\n return $ Dataset p\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> DriverOptions -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = flip unsafeWithDatasetIO flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> GDAL s (Int, Int)\ndatasetSize ds = unsafeWithDatasetIO ds $ \\dPtr -> do\n x <- getDatasetXSize_ dPtr\n y <- getDatasetYSize_ dPtr\n return (fromIntegral x, fromIntegral y)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> IO CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection = flip unsafeWithDatasetIO (\\d -> getProjection_ d >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = unsafeWithDatasetIO d $ \\d' ->\n throwIfError \"setDatasetProjection: could not set projection\" $\n withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset s t a -> GDAL s Geotransform\ndatasetGeotransform d = unsafeWithDatasetIO d $ \\dPtr ->\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 s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = unsafeWithDatasetIO ds $ \\dPtr ->\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\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> GDAL s Int\ndatasetBandCount = flip unsafeWithDatasetIO (fmap fromIntegral . bandCount_)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> IO CInt\n\ngetBand :: Dataset s t a -> Int -> GDAL s (Band s t a)\ngetBand ds band = unsafeWithDatasetIO ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw (InvalidBand band)\n else return rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO ((Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> GDAL s (Int,Int)\nbandBlockSize band = liftIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> GDAL s Int\nbandBlockLen = fmap (uncurry (*)) . bandBlockSize\n\nbandSize :: (Band s a t) -> GDAL s (Int, Int)\nbandSize band = liftIO $ do\n x <- getBandXSize_ band\n y <- getBandYSize_ band\n return (fromIntegral x, fromIntegral y)\n\nbandBlockCount :: Band s t a -> GDAL s (Int, Int)\nbandBlockCount b = do\n (nx,ny) <- bandSize b\n (bx,by) <- bandBlockSize b\n return ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s t a) -> IO CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s t a) -> IO CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue b = liftIO $ alloca $ \\p -> do\n value <- liftM fromNodata $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n\nc_bandNodataValue :: (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v = liftIO $ throwIfError \"could not set nodata\" $\n setNodata_ b (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\n-- | Unsafe lazy IO version of readBand.\n-- *must* make sure vectors are evaluated inside the GDAL monad and in the\n-- same thread that called 'runGDAL0\nunsafeLazyReadBand :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nunsafeLazyReadBand band xoff yoff sx sy bx by = liftIO $\n unsafeInterleaveIO $ readBandIO band xoff yoff sx sy bx by\n{-# INLINE unsafeLazyReadBand #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Band s t b' -> IO (Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\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 throwIfError \"could not read band\" $\n rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Band s t b' -> IO (Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = reader band >>= mask\n where\n mask\n | hasFlag MaskPerDataset = useMaskBand\n | hasFlag MaskNoData = useNoData\n | hasFlag MaskAllValid = useAsIs\n | otherwise = useMaskBand\n hasFlag f = fromEnumC f .&. c_getMaskFlags band == fromEnumC f\n useAsIs = return . St.map Value\n useNoData vs = do\n mNodata <- c_bandNodataValue band\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand vs = do\n mask <- c_getMaskBand band\n ms <- reader mask :: IO (Vector Word8)\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by uvec = do\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue band)\n liftIO $ do\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\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 (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n len <- bandBlockLen band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock b x y uvec = do\n checkType b\n nElems <- bandBlockLen b\n bNodata <- liftIO $ fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n liftIO $ do\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw InvalidBlockSize\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand s a) -> CInt -> CInt -> Ptr () -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: (Band s t a) -> IO (Band s t Word8)\n\n#c\nenum MaskFlag {\n MaskAllValid = GMF_ALL_VALID,\n MaskPerDataset = GMF_PER_DATASET,\n MaskAlpha = GMF_ALPHA,\n MaskNoData = GMF_NODATA\n};\n#endc\n\n{# enum MaskFlag {} deriving (Eq, Bounded, Show) #}\n\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: (Band s t a) -> CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7ba0bac5afb6af535977fab00ff875e87bb8cdda","subject":"expose unValue","message":"expose unValue\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 TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveGeneric #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , gdalForkIO\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , ErrorType (..)\n , isGDALException\n , Geotransform (..)\n , OptionList\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , unValue\n , isNoData\n , registerAllDrivers\n , destroyDriverManager\n , setQuietErrorHandler\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , throwIfError\n , throwIfError_\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n , withOptionList\n , newDerivedDatasetHandle\n , toOptionListPtr\n , fromOptionListPtr\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Concurrent (ThreadId, runInBoundThread, rtsSupportsBoundThreads)\nimport Control.Concurrent.MVar (MVar, newMVar, takeMVar, putMVar, newEmptyMVar)\nimport Control.Exception ( bracket, Exception(..), SomeException\n , evaluate, throw)\nimport Data.IORef (newIORef, readIORef, writeIORef)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, liftM2, foldM, forM, when)\nimport Control.Monad.Trans.Resource (\n ResourceT, runResourceT, register, resourceForkIO)\nimport Control.Monad.Catch (MonadThrow(..), MonadCatch, MonadMask, finally)\nimport Control.Monad.IO.Class (MonadIO(..))\nimport Control.Monad.Reader (ReaderT, runReaderT, ask)\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport GHC.Generics (Generic)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq,Generic) #}\n\n\nnewtype GDAL s a = GDAL (ResourceT (ReaderT (MVar [MVar ()]) IO) a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\nderiving instance MonadThrow (GDAL s)\nderiving instance MonadCatch (GDAL s)\nderiving instance MonadMask (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n children <- newMVar []\n runReaderT (runResourceT (finally (a >>= liftIO . evaluate . force)\n (liftIO (waitForChildren children))))\n children\n\n where\n waitForChildren children = do\n cs <- takeMVar children\n case cs of\n [] -> return ()\n m:ms -> do\n putMVar children ms\n _ <- takeMVar m\n waitForChildren children\n\ngdalForkIO :: GDAL s () -> GDAL s ThreadId\ngdalForkIO (GDAL a) = GDAL $ do\n children <- ask\n mvar <- liftIO $ do\n childs <- takeMVar children\n mvar <- newEmptyMVar\n putMVar children (mvar:childs)\n return mvar\n resourceForkIO (finally a (liftIO (putMVar mvar ())))\n\n\ndata GDALException = GDALException !ErrorType !Int !String\n | InvalidType !Datatype\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize !Int\n deriving (Show, Generic, Typeable)\n\ninstance NFData ErrorType\ninstance NFData Datatype\ninstance NFData GDALException\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq,Show,Generic) #}\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 setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO (FunPtr ErrorHandler)\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nforeign import ccall \"cpl_error.h CPLPushErrorHandler\"\n c_pushErrorHandler :: FunPtr ErrorHandler -> IO ()\n\nforeign import ccall \"cpl_error.h CPLPopErrorHandler\"\n c_popErrorHandler :: IO ()\n\nforeign import ccall safe \"wrapper\"\n mkErrorHandler :: ErrorHandler -> IO (FunPtr ErrorHandler)\n\nthrowIfError_ :: String -> IO a -> IO ()\nthrowIfError_ prefix act = throwIfError prefix act >> return ()\n\nthrowIfError :: String -> IO a -> IO a\nthrowIfError prefix act = do\n ref <- newIORef Nothing\n handler <- mkErrorHandler $ \\err errno cmsg -> do\n msg <- peekCString cmsg\n writeIORef ref $ Just $\n GDALException (toEnumC err) (fromIntegral errno) (prefix ++ \": \" ++ msg)\n ret <- runBounded $\n bracket (c_pushErrorHandler handler) (const c_popErrorHandler) (const act)\n readIORef ref >>= maybe (return ret) throw\n where\n runBounded \n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset (Mutex, Ptr (Dataset s t a))\n\nunDataset :: Dataset s t a -> Ptr (Dataset s t a)\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t a -> (Ptr (Dataset s t a) -> 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 GDALRasterBandH as Band newtype nocode#}\n\nnewtype (Band s (t::DatasetMode) a)\n = Band (Mutex, Ptr (Band s t a))\n\nunBand :: Band s t a -> Ptr (Band s t a)\nunBand (Band (_,p)) = p\n\nwithLockedBandPtr\n :: Band s t a -> (Ptr (Band s t a) -> 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 GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $\n throwIfError \"driverByName\" (c_driverByName (show s))\n\ntype OptionList = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> OptionList\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\n\nwithOptionList :: OptionList -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionListPtr opts) freeOptionList\n where freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ntoOptionListPtr :: OptionList -> IO (Ptr CString)\ntoOptionListPtr = foldM folder nullPtr\n where\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n\nfromOptionListPtr :: Ptr CString -> IO OptionList\nfromOptionListPtr ptr = do\n n <- {#call unsafe CSLCount as ^#} ptr\n forM [0..n-1] $ \\ix -> do\n s <- {#call unsafe CSLGetField as ^#} ptr ix >>= peekCString\n return $ break (\/='=') s\n \n \n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n (liftIO $ withCString p $ \\p' -> throwIfError \"open\" (open_ p' (fromEnumC m)))\n >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n let rt = datatype (Proxy :: Proxy a)\n if rt == dt\n then return ()\n else throwM (InvalidType rt)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> OptionList\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n withLockedDatasetPtr ds $ \\dsPtr ->\n c_createCopy d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> OptionList\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $ do\n _ <- register (safeCloseDataset p)\n m <- liftIO newMutex\n return $ Dataset (m,p)\n\nnewDerivedDatasetHandle\n :: Dataset s t a -> Ptr (Dataset s t b) -> GDAL s (Dataset s t b)\nnewDerivedDatasetHandle (Dataset (m,_)) p = GDAL $ do\n _ <- register (safeCloseDataset p)\n return $ Dataset (m,p)\n\nsafeCloseDataset :: Ptr (Dataset s t a) -> IO ()\nsafeCloseDataset p = do\n count <- c_dereferenceDataset p\n when (count < 1) $ (c_referenceDataset p >> c_closeDataset p)\n\nforeign import ccall \"gdal.h GDALReferenceDataset\"\n c_referenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALDereferenceDataset\"\n c_dereferenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> OptionList -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = let d = unDataset ds\n in (fromIntegral (getDatasetXSize_ d), fromIntegral (getDatasetYSize_ d)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ (unDataset d) >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError_ \"setDatasetProjection\" $\n withLockedDatasetPtr d $ withCString p . setProjection' \n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\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 a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ alloca $ \\p -> do\n throwIfError_ \"datasetGeotransform\" (getGeoTransform (unDataset d) p)\n peek (castPtr p)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n throwIfError_ \"setDatasetGeotransform\" $\n withLockedDatasetPtr ds $ \\dsPtr ->\n alloca $ \\p -> (poke p gt >> setGeoTransform dsPtr (castPtr p))\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_ . unDataset\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band (Dataset (m,dp)) = liftIO $ do\n p <- throwIfError \"getBand\" (c_getRasterBand dp (fromIntegral band))\n return (Band (m,p))\n\nforeign import ccall safe \"gdal.h GDALGetRasterBand\" c_getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO (Ptr (Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_ . unBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: Ptr (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ (unBand band) xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: Ptr (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ (unBand band))\n , fromIntegral (getBandYSize_ (unBand band)))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: Ptr (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: Ptr (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue = fmap (fmap fromNodata) . liftIO . c_bandNodataValue . unBand\n\nc_bandNodataValue :: Ptr (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: Ptr (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError_ \"setBandNodataValue\" $\n setNodata_ (unBand b) (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: Ptr (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError_ \"fillBand\" $\n fillRaster_ (unBand b) (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: Ptr (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\nreadBandPure band xoff yoff sx sy bx by = unsafePerformIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"readBandIO\" $ do\n e <- adviseRead_\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 rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- c_getMaskFlags bPtr\n reader bPtr >>= fmap V_Value . 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 <- c_bandNodataValue bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- c_getMaskBand 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by (V_Value uvec) = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\n else withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"writeBand\" $\n rasterIO_\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\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr ()\n -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError_ \"readBandBlock\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: Ptr (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc band = liftIO $ do\n mNodata <- c_bandNodataValue (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n withLockedBandPtr band $ \\b ->\n throwIfError_ \"ifoldlM'\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount band\n (sx,sy) = bandBlockSize band\n (bx,by) = bandSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band x y (V_Value uvec) = do\n checkType band\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n nElems = bandBlockLen band\n if nElems \/= len\n then throw (InvalidBlockSize len)\n else withForeignPtr fp $ \\ptr ->\n throwIfError_ \"writeBandBlock\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: Ptr (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: Ptr (Band s t a) -> IO (Ptr (Band s t Word8))\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\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: Ptr (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n--\n-- Value\n--\n\ndata Value a = Value {unValue :: !a} | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ntype FlagType = Word8\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: FlagType)\n alignment _ = alignment (undefined :: a)\n peek p = let pm = castPtr p :: Ptr FlagType\n pv = pm `plusPtr` sizeOf (undefined :: FlagType)\n in do t <- peek pm\n if t\/=0\n then fmap Value (peek (castPtr pv))\n else return NoData\n poke p x = let pm = castPtr p :: Ptr FlagType\n pv = pm `plusPtr` sizeOf (undefined :: FlagType)\n in case x of\n NoData -> poke pm 0\n Value a -> poke pm 1 >> poke (castPtr pv) a\n {-# INLINE sizeOf #-}\n {-# INLINE alignment #-}\n {-# INLINE peek #-}\n {-# INLINE poke #-}\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype instance U.Vector (Value a) = V_Value (St.Vector (Value a))\nnewtype instance U.MVector s (Value a) = MV_Value (St.MVector s (Value a))\ninstance Storable a => U.Unbox (Value a)\n\ninstance Storable a => M.MVector U.MVector (Value a) where\n basicLength (MV_Value v ) = M.basicLength v\n basicUnsafeSlice m n (MV_Value v) = MV_Value (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_Value v) (MV_Value u) = M.basicOverlaps v u\n basicUnsafeNew = liftM MV_Value . M.basicUnsafeNew\n basicUnsafeRead (MV_Value v) i = M.basicUnsafeRead v i\n basicUnsafeWrite (MV_Value v) i x = M.basicUnsafeWrite v i x\n basicInitialize (MV_Value v) = M.basicInitialize v\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n {-# INLINE basicInitialize #-}\n\ninstance Storable a => G.Vector U.Vector (Value a) where\n basicUnsafeFreeze (MV_Value v) = liftM V_Value (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Value v) = liftM MV_Value (G.basicUnsafeThaw v)\n basicLength ( V_Value v) = G.basicLength v\n basicUnsafeSlice m n (V_Value v) = V_Value (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_Value v) i = G.basicUnsafeIndexM v i\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveGeneric #-}\n\nmodule OSGeo.GDAL.Internal (\n GDAL\n , runGDAL\n , gdalForkIO\n , GDALType\n , Datatype (..)\n , GDALException (..)\n , ErrorType (..)\n , isGDALException\n , Geotransform (..)\n , OptionList\n , Driver (..)\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Value (..)\n , fromValue\n , isNoData\n , registerAllDrivers\n , destroyDriverManager\n , setQuietErrorHandler\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 , bandDatatype\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n -- Internal Util\n , throwIfError\n , throwIfError_\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n , withOptionList\n , newDerivedDatasetHandle\n , toOptionListPtr\n , fromOptionListPtr\n) where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Concurrent (ThreadId, runInBoundThread, rtsSupportsBoundThreads)\nimport Control.Concurrent.MVar (MVar, newMVar, takeMVar, putMVar, newEmptyMVar)\nimport Control.Exception ( bracket, Exception(..), SomeException\n , evaluate, throw)\nimport Data.IORef (newIORef, readIORef, writeIORef)\nimport Control.DeepSeq (NFData, force)\nimport Control.Monad (liftM, liftM2, foldM, forM, when)\nimport Control.Monad.Trans.Resource (\n ResourceT, runResourceT, register, resourceForkIO)\nimport Control.Monad.Catch (MonadThrow(..), MonadCatch, MonadMask, finally)\nimport Control.Monad.IO.Class (MonadIO(..))\nimport Control.Monad.Reader (ReaderT, runReaderT, ask)\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(..))\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.Generic.Mutable as M\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Unboxed.Base as U\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr, plusPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport GHC.Generics (Generic)\n\nimport OSGeo.Util\n\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n\nclass (Storable 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 toNodata :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromNodata :: CDouble -> a\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq,Generic) #}\n\n\nnewtype GDAL s a = GDAL (ResourceT (ReaderT (MVar [MVar ()]) IO) a)\n\nderiving instance Functor (GDAL s)\nderiving instance Applicative (GDAL s)\nderiving instance Monad (GDAL s)\nderiving instance MonadIO (GDAL s)\nderiving instance MonadThrow (GDAL s)\nderiving instance MonadCatch (GDAL s)\nderiving instance MonadMask (GDAL s)\n\nrunGDAL :: NFData a => (forall s. GDAL s a) -> IO a\nrunGDAL (GDAL a) = do\n children <- newMVar []\n runReaderT (runResourceT (finally (a >>= liftIO . evaluate . force)\n (liftIO (waitForChildren children))))\n children\n\n where\n waitForChildren children = do\n cs <- takeMVar children\n case cs of\n [] -> return ()\n m:ms -> do\n putMVar children ms\n _ <- takeMVar m\n waitForChildren children\n\ngdalForkIO :: GDAL s () -> GDAL s ThreadId\ngdalForkIO (GDAL a) = GDAL $ do\n children <- ask\n mvar <- liftIO $ do\n childs <- takeMVar children\n mvar <- newEmptyMVar\n putMVar children (mvar:childs)\n return mvar\n resourceForkIO (finally a (liftIO (putMVar mvar ())))\n\n\ndata GDALException = GDALException !ErrorType !Int !String\n | InvalidType !Datatype\n | InvalidRasterSize !Int !Int\n | InvalidBlockSize !Int\n deriving (Show, Generic, Typeable)\n\ninstance NFData ErrorType\ninstance NFData Datatype\ninstance NFData GDALException\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as ErrorType {upcaseFirstLetter} deriving (Eq,Show,Generic) #}\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 setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO (FunPtr ErrorHandler)\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nforeign import ccall \"cpl_error.h CPLPushErrorHandler\"\n c_pushErrorHandler :: FunPtr ErrorHandler -> IO ()\n\nforeign import ccall \"cpl_error.h CPLPopErrorHandler\"\n c_popErrorHandler :: IO ()\n\nforeign import ccall safe \"wrapper\"\n mkErrorHandler :: ErrorHandler -> IO (FunPtr ErrorHandler)\n\nthrowIfError_ :: String -> IO a -> IO ()\nthrowIfError_ prefix act = throwIfError prefix act >> return ()\n\nthrowIfError :: String -> IO a -> IO a\nthrowIfError prefix act = do\n ref <- newIORef Nothing\n handler <- mkErrorHandler $ \\err errno cmsg -> do\n msg <- peekCString cmsg\n writeIORef ref $ Just $\n GDALException (toEnumC err) (fromIntegral errno) (prefix ++ \": \" ++ msg)\n ret <- runBounded $\n bracket (c_pushErrorHandler handler) (const c_popErrorHandler) (const act)\n readIORef ref >>= maybe (return ret) throw\n where\n runBounded \n | rtsSupportsBoundThreads = runInBoundThread\n | otherwise = id\n\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\n\ndata DatasetMode = ReadOnly | ReadWrite\n\ntype ReadOnly = 'ReadOnly\ntype ReadWrite = 'ReadWrite\n\nnewtype Dataset s (t::DatasetMode) a\n = Dataset (Mutex, Ptr (Dataset s t a))\n\nunDataset :: Dataset s t a -> Ptr (Dataset s t a)\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t a -> (Ptr (Dataset s t a) -> 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 GDALRasterBandH as Band newtype nocode#}\n\nnewtype (Band s (t::DatasetMode) a)\n = Band (Mutex, Ptr (Band s t a))\n\nunBand :: Band s t a -> Ptr (Band s t a)\nunBand (Band (_,p)) = p\n\nwithLockedBandPtr\n :: Band s t a -> (Ptr (Band s t a) -> 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 GDALDriverH as DriverH newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `DriverH' id #}\n\ndriverByName :: Driver -> GDAL s DriverH\ndriverByName s = GDAL $ liftIO $\n throwIfError \"driverByName\" (c_driverByName (show s))\n\ntype OptionList = [(String,String)]\n\ncreate\n :: forall s a. GDALType a\n => Driver -> String -> Int -> Int -> Int -> OptionList\n -> GDAL s (Dataset s ReadWrite a)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC $ datatype (Proxy :: Proxy a)\n withOptionList options $ \\opts ->\n c_create d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\n\nwithOptionList :: OptionList -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionListPtr opts) freeOptionList\n where freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ntoOptionListPtr :: OptionList -> IO (Ptr CString)\ntoOptionListPtr = foldM folder nullPtr\n where\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n\nfromOptionListPtr :: Ptr CString -> IO OptionList\nfromOptionListPtr ptr = do\n n <- {#call unsafe CSLCount as ^#} ptr\n forM [0..n-1] $ \\ix -> do\n s <- {#call unsafe CSLGetField as ^#} ptr ix >>= peekCString\n return $ break (\/='=') s\n \n \n\nforeign import ccall safe \"gdal.h GDALCreate\" c_create\n :: DriverH\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset s a))\n\nopenReadOnly :: FilePath -> GDAL s (RODataset s a)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: GDALType a => FilePath -> GDAL s (RWDataset s a)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t a)\nopenWithMode m p =\n (liftIO $ withCString p $ \\p' -> throwIfError \"open\" (open_ p' (fromEnumC m)))\n >>= newDatasetHandle\n\ncheckType\n :: forall s t a. GDALType a\n => Band s t a -> GDAL s ()\ncheckType b = do\n dt <- bandDatatype b\n let rt = datatype (Proxy :: Proxy a)\n if rt == dt\n then return ()\n else throwM (InvalidType rt)\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset s t a))\n\n\ncreateCopy' :: GDALType a\n => Driver -> String -> (Dataset s t a) -> Bool -> OptionList\n -> ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy' driver path ds strict options progressFun = do\n d <- driverByName driver\n ptr <- liftIO $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n withLockedDatasetPtr ds $ \\dsPtr ->\n c_createCopy d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n newDatasetHandle ptr\n\ncreateCopy :: GDALType a\n => Driver -> FilePath -> (Dataset s t a) -> Bool -> OptionList\n -> GDAL s (RWDataset s a)\ncreateCopy driver path dataset strict options = do\n createCopy' driver path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" c_createCopy\n :: DriverH\n -> Ptr CChar\n -> Ptr (Dataset s t a)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset s a))\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 s t a) -> GDAL s (Dataset s t a)\nnewDatasetHandle p = GDAL $ do\n _ <- register (safeCloseDataset p)\n m <- liftIO newMutex\n return $ Dataset (m,p)\n\nnewDerivedDatasetHandle\n :: Dataset s t a -> Ptr (Dataset s t b) -> GDAL s (Dataset s t b)\nnewDerivedDatasetHandle (Dataset (m,_)) p = GDAL $ do\n _ <- register (safeCloseDataset p)\n return $ Dataset (m,p)\n\nsafeCloseDataset :: Ptr (Dataset s t a) -> IO ()\nsafeCloseDataset p = do\n count <- c_dereferenceDataset p\n when (count < 1) $ (c_referenceDataset p >> c_closeDataset p)\n\nforeign import ccall \"gdal.h GDALReferenceDataset\"\n c_referenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALDereferenceDataset\"\n c_dereferenceDataset :: Ptr (Dataset s t a) -> IO CInt\n\nforeign import ccall \"gdal.h GDALClose\"\n c_closeDataset :: Ptr (Dataset s t a) -> IO ()\n\ncreateMem\n :: GDALType a\n => Int -> Int -> Int -> OptionList -> GDAL s (Dataset s ReadWrite a)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s a. RWDataset s a -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr c_flushCache\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" c_flushCache\n :: Ptr (Dataset s t a) -> IO ()\n\ndatasetSize :: Dataset s t a -> (Int, Int)\ndatasetSize ds\n = let d = unDataset ds\n in (fromIntegral (getDatasetXSize_ d), fromIntegral (getDatasetYSize_ d)) \n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset s t a) -> CInt\n\ndatasetProjection :: Dataset s t a -> GDAL s String\ndatasetProjection d = liftIO (getProjection_ (unDataset d) >>= peekCString)\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset s t a) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset s a) -> String -> GDAL s ()\nsetDatasetProjection d p = liftIO $\n throwIfError_ \"setDatasetProjection\" $\n withLockedDatasetPtr d $ withCString p . setProjection' \n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset s t a) -> Ptr CChar -> IO CInt\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 a -> GDAL s Geotransform\ndatasetGeotransform d = liftIO $ alloca $ \\p -> do\n throwIfError_ \"datasetGeotransform\" (getGeoTransform (unDataset d) p)\n peek (castPtr p)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset s a) -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n throwIfError_ \"setDatasetGeotransform\" $\n withLockedDatasetPtr ds $ \\dsPtr ->\n alloca $ \\p -> (poke p gt >> setGeoTransform dsPtr (castPtr p))\n\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset s t a) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset s t a -> Int\ndatasetBandCount = fromIntegral . bandCount_ . unDataset\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset s t a) -> CInt\n\ngetBand :: Int -> Dataset s t a -> GDAL s (Band s t a)\ngetBand band (Dataset (m,dp)) = liftIO $ do\n p <- throwIfError \"getBand\" (c_getRasterBand dp (fromIntegral band))\n return (Band (m,p))\n\nforeign import ccall safe \"gdal.h GDALGetRasterBand\" c_getRasterBand\n :: Ptr (Dataset s t a) -> CInt -> IO (Ptr (Band s t a))\n\n\nbandDatatype :: (Band s t a) -> GDAL s Datatype\nbandDatatype = fmap toEnumC . liftIO . getDatatype_ . unBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: Ptr (Band s a t) -> IO CInt\n\n\nbandBlockSize :: (Band s t a) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n getBlockSize_ (unBand band) xPtr yPtr\n liftM2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: Ptr (Band s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s t a) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band = ( fromIntegral (getBandXSize_ (unBand band))\n , fromIntegral (getBandYSize_ (unBand band)))\n\nbandBlockCount :: Band s t a -> (Int, Int)\nbandBlockCount b\n = ( ceiling (fromIntegral nx \/ fromIntegral bx :: Double)\n , ceiling (fromIntegral ny \/ fromIntegral by :: Double))\n where (nx,ny) = bandSize b\n (bx,by) = bandBlockSize b\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: Ptr (Band s t a) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: Ptr (Band s t a) -> CInt\n\n\nbandNodataValue :: GDALType a => (Band s t a) -> GDAL s (Maybe a)\nbandNodataValue = fmap (fmap fromNodata) . liftIO . c_bandNodataValue . unBand\n\nc_bandNodataValue :: Ptr (Band s t a) -> IO (Maybe CDouble)\nc_bandNodataValue b = alloca $ \\p -> do\n value <- getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE c_bandNodataValue #-}\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: Ptr (Band s t a) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: GDALType a => (RWBand s a) -> a -> GDAL s ()\nsetBandNodataValue b v\n = liftIO $ throwIfError_ \"setBandNodataValue\" $\n setNodata_ (unBand b) (toNodata v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: Ptr (RWBand s t) -> CDouble -> IO CInt\n\nfillBand :: (RWBand s a) -> Double -> Double -> GDAL s ()\nfillBand b r i = liftIO $ throwIfError_ \"fillBand\" $\n fillRaster_ (unBand b) (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: Ptr (RWBand s t) -> CDouble -> CDouble -> IO CInt\n\n\nreadBand :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> GDAL s (Vector (Value a))\nreadBand band xoff yoff sx sy bx by = liftIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s b a. GDALType a\n => (ROBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\nreadBandPure band xoff yoff sx sy bx by = unsafePerformIO $\n readBandIO band xoff yoff sx sy bx by\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t b a. GDALType a\n => (Band s t b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector (Value a))\nreadBandIO band xoff yoff sx sy bx by = readMasked band read_\n where\n read_ :: forall b' a'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a')\n read_ b = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (Proxy :: Proxy a'))\n withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"readBandIO\" $ do\n e <- adviseRead_\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 rasterIO_\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 return $ St.unsafeFromForeignPtr0 fp (bx * by)\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t b\n -> (forall a' b'. GDALType a' => Ptr (Band s t b') -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- c_getMaskFlags bPtr\n reader bPtr >>= fmap V_Value . 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 <- c_bandNodataValue bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- c_getMaskBand 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\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\nwriteBand :: forall s b a. GDALType a\n => (RWBand s b)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band xoff yoff sx sy bx by (V_Value uvec) = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n if nElems \/= len\n then throw $ InvalidRasterSize bx by\n else withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"writeBand\" $\n rasterIO_\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\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: Ptr (Band s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr ()\n -> CInt -> CInt -> CInt -> CInt -> CInt -> IO CInt\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t a -> Int -> Int -> GDAL s (Vector (Value a))\nreadBandBlock band x y = do\n checkType band\n liftIO $ readMasked band $ \\b -> do\n f <- mallocForeignPtrArray len\n withForeignPtr f $ \\ptr ->\n throwIfError_ \"readBandBlock\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ St.unsafeFromForeignPtr0 f len\n where len = bandBlockLen band\n{-# INLINE readBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: Ptr (Band s t a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t a -> 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 -> Int -> Int -> Value a -> b) -> b -> Band s t a -> GDAL s b\nifoldl' f = ifoldlM' (\\acc x y -> return . f acc x y)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> Int -> Int -> Value a -> IO b) -> b -> Band s t a -> GDAL s b\nifoldlM' f initialAcc band = liftIO $ do\n mNodata <- c_bandNodataValue (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toNodata v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n withLockedBandPtr band $ \\b ->\n throwIfError_ \"ifoldlM'\" $\n readBlock_ b (fromIntegral iB) (fromIntegral jB) 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 x y . toValue =<< peekElemOff ptr (j*sx+i)\n where x = iB*sx+i\n y = 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 mx = bx `mod` sx\n my = by `mod` sy\n (nx,ny) = bandBlockCount band\n (sx,sy) = bandBlockSize band\n (bx,by) = bandSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> Int -> Int -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band x y (V_Value uvec) = do\n checkType band\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromNodata) (c_bandNodataValue b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) uvec\n nElems = bandBlockLen band\n if nElems \/= len\n then throw (InvalidBlockSize len)\n else withForeignPtr fp $ \\ptr ->\n throwIfError_ \"writeBandBlock\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y) ptr\n{-# INLINE writeBandBlock #-}\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: Ptr (RWBand s a) -> CInt -> CInt -> Ptr a -> IO CInt\n\nforeign import ccall safe \"gdal.h GDALGetMaskBand\" c_getMaskBand\n :: Ptr (Band s t a) -> IO (Ptr (Band s t Word8))\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\nforeign import ccall unsafe \"gdal.h GDALGetMaskFlags\" c_getMaskFlags\n :: Ptr (Band s t a) -> IO CInt\n\n\ninstance GDALType Word8 where\n datatype _ = GDT_Byte\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word16 where\n datatype _ = GDT_UInt16\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Word32 where\n datatype _ = GDT_UInt32\n nodata = maxBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int16 where\n datatype _ = GDT_Int16\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Int32 where\n datatype _ = GDT_Int32\n nodata = minBound\n toNodata = fromIntegral\n fromNodata = truncate\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Float where\n datatype _ = GDT_Float32\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType Double where\n datatype _ = GDT_Float64\n nodata = 0\/0\n toNodata = realToFrac\n fromNodata = realToFrac\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int16) where\n datatype _ = GDT_CInt16\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Int32) where\n datatype _ = GDT_CInt32\n nodata = nodata :+ nodata\n toNodata = fromIntegral . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Float) where\n datatype _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\ninstance GDALType (Complex Double) where\n datatype _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toNodata = realToFrac . realPart\n fromNodata d = fromNodata d :+ fromNodata d\n {-# INLINE toNodata #-}\n {-# INLINE fromNodata #-}\n\n--\n-- Value\n--\n\ndata Value a = Value !a | NoData deriving (Eq, Show)\n\ninstance Functor Value where\n fmap _ NoData = NoData\n fmap f (Value a) = Value (f a)\n\ninstance Applicative Value where\n pure = Value\n\n Value f <*> m = fmap f m\n NoData <*> _m = NoData\n\n Value _m1 *> m2 = m2\n NoData *> _m2 = NoData\n\ninstance Monad Value where\n (Value x) >>= k = k x\n NoData >>= _ = NoData\n\n (>>) = (*>)\n\n return = Value\n fail _ = NoData\n\ntype FlagType = Word8\n\ninstance Storable a => Storable (Value a) where\n sizeOf _ = sizeOf (undefined :: a) + sizeOf (undefined :: FlagType)\n alignment _ = alignment (undefined :: a)\n peek p = let pm = castPtr p :: Ptr FlagType\n pv = pm `plusPtr` sizeOf (undefined :: FlagType)\n in do t <- peek pm\n if t\/=0\n then fmap Value (peek (castPtr pv))\n else return NoData\n poke p x = let pm = castPtr p :: Ptr FlagType\n pv = pm `plusPtr` sizeOf (undefined :: FlagType)\n in case x of\n NoData -> poke pm 0\n Value a -> poke pm 1 >> poke (castPtr pv) a\n {-# INLINE sizeOf #-}\n {-# INLINE alignment #-}\n {-# INLINE peek #-}\n {-# INLINE poke #-}\n\nisNoData :: Value a -> Bool\nisNoData NoData = True\nisNoData _ = False\n{-# INLINE isNoData #-}\n\nfromValue :: a -> Value a -> a\nfromValue v NoData = v\nfromValue _ (Value v) = v\n{-# INLINE fromValue #-}\n\nnewtype instance U.Vector (Value a) = V_Value (St.Vector (Value a))\nnewtype instance U.MVector s (Value a) = MV_Value (St.MVector s (Value a))\ninstance Storable a => U.Unbox (Value a)\n\ninstance Storable a => M.MVector U.MVector (Value a) where\n basicLength (MV_Value v ) = M.basicLength v\n basicUnsafeSlice m n (MV_Value v) = MV_Value (M.basicUnsafeSlice m n v)\n basicOverlaps (MV_Value v) (MV_Value u) = M.basicOverlaps v u\n basicUnsafeNew = liftM MV_Value . M.basicUnsafeNew\n basicUnsafeRead (MV_Value v) i = M.basicUnsafeRead v i\n basicUnsafeWrite (MV_Value v) i x = M.basicUnsafeWrite v i x\n basicInitialize (MV_Value v) = M.basicInitialize v\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicOverlaps #-}\n {-# INLINE basicUnsafeNew #-}\n {-# INLINE basicUnsafeRead #-}\n {-# INLINE basicUnsafeWrite #-}\n {-# INLINE basicInitialize #-}\n\ninstance Storable a => G.Vector U.Vector (Value a) where\n basicUnsafeFreeze (MV_Value v) = liftM V_Value (G.basicUnsafeFreeze v)\n basicUnsafeThaw ( V_Value v) = liftM MV_Value (G.basicUnsafeThaw v)\n basicLength ( V_Value v) = G.basicLength v\n basicUnsafeSlice m n (V_Value v) = V_Value (G.basicUnsafeSlice m n v)\n basicUnsafeIndexM (V_Value v) i = G.basicUnsafeIndexM v i\n {-# INLINE basicUnsafeFreeze #-}\n {-# INLINE basicUnsafeThaw #-}\n {-# INLINE basicLength #-}\n {-# INLINE basicUnsafeSlice #-}\n {-# INLINE basicUnsafeIndexM #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"1011a447ef87fb097cc3483ac3ddc1d40fa6609f","subject":"Added clCreateFromGLBuffer.","message":"Added clCreateFromGLBuffer.\n","repos":"IFCA\/opencl,Delan90\/opencl,Delan90\/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, clCreateFromGLBuffer,\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 \"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 :: CLContext -> [CLMemFlag] -> CLuint -> IO CLMem\nclCreateFromGLBuffer ctx xs glObj = wrapPError $ \\perr -> do\n raw_clCreateFromGLBuffer ctx flags glObj perr\n where 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 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"30ece2b8b3422f1ba64dd4eccd03c628e7d1dbc8","subject":"Document the Cairo.SVG module.","message":"Document the Cairo.SVG module.\n\ndarcs-hash:20060111180610-b4c10-33ce19030ee43ff6dacdfc5ffa09db180a9f5d1a.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 (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":"2c76c934a23933276e216f21035158c3bd6a1622","subject":"Export the Save class.","message":"Export the Save class.\n","repos":"BeautifulDestinations\/CV,aleator\/CV,aleator\/CV,TomMD\/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, emptyCopy'\n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\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, 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\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\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 = 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 -> 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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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 -> 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\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\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\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\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\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\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 D8) where\n type SP (Image RGB D8) = (D8,D8,D8)\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 :: 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 (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 Complex D32) where\n type SP (Image Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ 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) = 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 return r\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 #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, create\n, empty\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\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, 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\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\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 = 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 -> 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\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 :: (Int,Int) -> Image GrayScale D8 -> D8\nsafeGetPixel (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = getPixel (x',y') i\n | otherwise = 0\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\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 -> 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\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\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\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\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\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\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 D8) where\n type SP (Image RGB D8) = (D8,D8,D8)\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 :: 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 (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 Complex D32) where\n type SP (Image Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ 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) = 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 return r\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":"6ecc0447561563d27a60d5d926adb6d31a45b9b1","subject":"cleanup","message":"cleanup\n","repos":"albertov\/pg_schedule","old_file":"PGSchedule.chs","new_file":"PGSchedule.chs","new_contents":"module PGSchedule () where\n\nimport Data.Time\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Foreign.Marshal.Alloc (free)\nimport Foreign.Marshal.Array (newArray)\nimport Data.ByteString.Unsafe (unsafePackCString)\nimport qualified Data.Text.Encoding as T\nimport Sigym4.Dimension.CronSchedule\nimport Sigym4.Dimension\n\n#include \"postgres.h\"\n#include \"pgtime.h\"\n#include \"schedule.h\"\n\n{#enum PGScheduleError {} deriving (Eq,Show) #}\n\nnewtype PGTime = PGTime UTCTime deriving Show\n\ninstance Storable PGTime where\n sizeOf _ = {#sizeof pg_tm #}\n alignment _ = {#alignof pg_tm #}\n peek = fmap PGTime . peekUTCTime\n where\n peekUTCTime p =\n UTCTime <$> peekDay p <*> (timeOfDayToTime <$> peekTimeOfDay p)\n peekDay p = do\n y <- (+1900) . fromIntegral <$> {#get pg_tm->tm_year#} p\n m <- (+1) . fromIntegral <$> {#get pg_tm->tm_mon#} p\n d <- fromIntegral <$> {#get pg_tm->tm_mday#} p\n return (fromGregorian y m d)\n peekTimeOfDay p = do\n h <- fromIntegral <$> {#get pg_tm->tm_hour#} p\n m <- fromIntegral <$> {#get pg_tm->tm_min#} p\n s <- fromIntegral <$> {#get pg_tm->tm_sec#} p\n return (TimeOfDay h m s)\n\n poke p (PGTime (UTCTime day time)) = do\n let (TimeOfDay h m s) = timeToTimeOfDay time\n {#set pg_tm->tm_sec#} p (round s)\n {#set pg_tm->tm_min#} p (fromIntegral m)\n {#set pg_tm->tm_hour#} p (fromIntegral h)\n let (y,mth,d) = toGregorian day\n {#set pg_tm->tm_mday#} p (fromIntegral d)\n {#set pg_tm->tm_mon#} p (fromIntegral mth - 1)\n {#set pg_tm->tm_year#} p (fromIntegral y - 1900)\n {#set pg_tm->tm_wday#} p 0\n {#set pg_tm->tm_yday#} p 0\n {#set pg_tm->tm_isdst#} p 0\n {#set pg_tm->tm_gmtoff#} p 0\n {#set pg_tm->tm_zone#} p nullPtr --We won't be able to free anything we allocate here so we dont\n\nreturnStatus :: PGScheduleError -> IO CInt\nreturnStatus = return . fromIntegral . fromEnum\n\npg_schedule_parse :: CString -> IO CInt\npg_schedule_parse s = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n returnStatus $ either (const INVALID_SCHEDULE_FORMAT) (const NO_ERROR) (mkCronSchedule t)\nforeign export ccall pg_schedule_parse :: CString -> IO CInt\n\nwithSchedule :: CString -> (CronSchedule -> IO PGScheduleError) -> IO CInt\nwithSchedule s f = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n case mkCronSchedule t of\n Right sched -> fromIntegral . fromEnum <$> f sched\n Left _ -> do\n -- Should not happen since type is 'schedule' so it has already been parsed\n -- properly by pg_schedule_parse\n returnStatus INVALID_SCHEDULE_FORMAT\n\npg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\npg_schedule_contains s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n poke resPtr (if idelem sched dt then 1 else 0)\n pure NO_ERROR\nforeign export ccall pg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\n\n\npg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_next s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idsucc sched =<< idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_previous s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idpred sched =<< idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_floor s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_ceiling s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\npg_schedule_series s fromPtr toPtr resPtr countPtr = withSchedule s $ \\sched -> do\n PGTime dtFrom <- peek fromPtr\n PGTime dtTo <- peek toPtr\n let series = map PGTime\n . takeWhile (<= dtTo)\n . map unQ\n $ idenumUp sched dtFrom\n poke resPtr =<< newArray series\n poke countPtr (fromIntegral (length series))\n return NO_ERROR\nforeign export ccall pg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\n\npg_schedule_free_series :: Ptr PGTime -> IO ()\npg_schedule_free_series = free\nforeign export ccall pg_schedule_free_series :: Ptr PGTime -> IO ()\n","old_contents":"module PGSchedule () where\n\nimport Data.Time\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Foreign.Marshal.Alloc (free)\nimport Foreign.Marshal.Array (newArray)\nimport Data.ByteString.Unsafe (unsafePackCString)\nimport qualified Data.Text.Encoding as T\nimport Sigym4.Dimension.CronSchedule\nimport Sigym4.Dimension\n\n#include \"postgres.h\"\n#include \"pgtime.h\"\n#include \"schedule.h\"\n\n{#enum PGScheduleError {} deriving (Eq,Show) #}\n\n\nnewtype PGTime = PGTime UTCTime deriving Show\n\n{#pointer * pg_tm as PGTime nocode#}\n\ninstance Storable PGTime where\n sizeOf _ = {#sizeof pg_tm #}\n alignment _ = {#alignof pg_tm #}\n peek = fmap PGTime . peekUTCTime\n where\n peekUTCTime p =\n UTCTime <$> peekDay p <*> (timeOfDayToTime <$> peekTimeOfDay p)\n peekDay p = do\n y <- (+1900) . fromIntegral <$> {#get pg_tm->tm_year#} p\n m <- (+1) . fromIntegral <$> {#get pg_tm->tm_mon#} p\n d <- fromIntegral <$> {#get pg_tm->tm_mday#} p\n return (fromGregorian y m d)\n peekTimeOfDay p = do\n h <- fromIntegral <$> {#get pg_tm->tm_hour#} p\n m <- fromIntegral <$> {#get pg_tm->tm_min#} p\n s <- fromIntegral <$> {#get pg_tm->tm_sec#} p\n return (TimeOfDay h m s)\n\n poke p (PGTime (UTCTime day time)) = do\n let (TimeOfDay h m s) = timeToTimeOfDay time\n {#set pg_tm->tm_sec#} p (round s)\n {#set pg_tm->tm_min#} p (fromIntegral m)\n {#set pg_tm->tm_hour#} p (fromIntegral h)\n let (y,mth,d) = toGregorian day\n {#set pg_tm->tm_mday#} p (fromIntegral d)\n {#set pg_tm->tm_mon#} p (fromIntegral mth - 1)\n {#set pg_tm->tm_year#} p (fromIntegral y - 1900)\n {#set pg_tm->tm_wday#} p 0\n {#set pg_tm->tm_yday#} p 0\n {#set pg_tm->tm_isdst#} p 0\n {#set pg_tm->tm_gmtoff#} p 0\n {#set pg_tm->tm_zone#} p nullPtr --We won't be able to free anything we allocate here so we dont\n\nreturnStatus :: PGScheduleError -> IO CInt\nreturnStatus = return . fromIntegral . fromEnum\n\npg_schedule_parse :: CString -> IO CInt\npg_schedule_parse s = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n returnStatus $ either (const INVALID_SCHEDULE_FORMAT) (const NO_ERROR) (mkCronSchedule t)\nforeign export ccall pg_schedule_parse :: CString -> IO CInt\n\nwithSchedule :: CString -> (CronSchedule -> IO PGScheduleError) -> IO CInt\nwithSchedule s f = do\n t <- T.decodeUtf8 <$> unsafePackCString s\n case mkCronSchedule t of\n Right sched -> fromIntegral . fromEnum <$> f sched\n Left _ -> do\n -- Should not happen since type is 'schedule' so it has already been parsed\n -- properly by pg_schedule_parse\n returnStatus INVALID_SCHEDULE_FORMAT\n\npg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\npg_schedule_contains s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n poke resPtr (if idelem sched dt then 1 else 0)\n pure NO_ERROR\nforeign export ccall pg_schedule_contains :: CString -> Ptr PGTime -> Ptr CInt -> IO CInt\n\n\npg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_next s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idsucc sched =<< idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_next :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_previous s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idpred sched =<< idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_previous :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_floor s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idfloor sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_floor :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\npg_schedule_ceiling s dtPtr resPtr = withSchedule s $ \\sched -> do\n PGTime dt <- peek dtPtr\n let result = idceiling sched dt\n maybe (pure NO_RESULT) (\\n -> poke resPtr (PGTime (unQ n)) >> pure NO_ERROR) result\nforeign export ccall pg_schedule_ceiling :: CString -> Ptr PGTime -> Ptr PGTime -> IO CInt\n\npg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\npg_schedule_series s fromPtr toPtr resPtr countPtr = withSchedule s $ \\sched -> do\n PGTime dtFrom <- peek fromPtr\n PGTime dtTo <- peek toPtr\n let series = map PGTime\n . takeWhile (<= dtTo)\n . map unQ\n $ idenumUp sched dtFrom\n poke resPtr =<< newArray series\n poke countPtr (fromIntegral (length series))\n return NO_ERROR\nforeign export ccall pg_schedule_series :: CString -> Ptr PGTime -> Ptr PGTime -> Ptr (Ptr PGTime) -> Ptr CInt -> IO CInt\n\npg_schedule_free_series :: Ptr PGTime -> IO ()\npg_schedule_free_series = free\nforeign export ccall pg_schedule_free_series :: Ptr PGTime -> IO ()\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"714d88249912748ed0c98fe4c7b34a3a1f3af231","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","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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":"1f350826ecbf545b675bfa455fde273238c8772a","subject":"glade: remove glade\/Glade.chs (not sure why this file is here...)","message":"glade: remove glade\/Glade.chs (not sure why this file is here...)\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"glade\/Glade.chs","new_file":"glade\/Glade.chs","new_contents":"","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to Libglade -*-haskell-*-\n-- for loading XML widget specifications\n--\n-- Author : Manuel M T Chakravarty\n-- Created: 13 March 2002\n--\n-- Copyright (c) 2002 Manuel M T Chakravarty\n-- Modified 2003 by Duncan Coutts (gtk2hs port)\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-- |\n--\n-- Libglade facilitates loading of XML specifications of whole widget trees\n-- that have been interactively designed with the GUI builder Glade. The\n-- present module exports operations for manipulating 'GladeXML' objects.\n--\n-- @glade_xml_signal_autoconnect()@ is not supported. The C variant is not\n-- suitable for Haskell as @-rdynamic@ leads to huge executable and we\n-- usually don't want to connect staticly named functions, but closures.\n--\n-- * @glade_xml_construct()@ is not bound, as it doesn't seem to be useful\n-- in Haskell. As usual, the @signal_connect_data@ variant for\n-- registering signal handlers isn't bound either. Moreover, the\n-- @connect_full@ functions are not bound.\n--\n-- * This binding does not support Libglade functionality that is\n-- exclusively meant for extending Libglade with new widgets. Like new\n-- widgets, such functionality is currently expected to be implemented in\n-- C.\n--\n\nmodule Glade (\n\n -- * Data types\n --\n GladeXMLClass, GladeXML,\n\n -- * Creation operations\n --\n xmlNew, xmlNewWithRootAndDomain,\n\n -- * Obtaining widget handles\n --\n xmlGetWidget, xmlGetWidgetRaw\n\n) where\n\nimport Monad\t(liftM)\nimport FFI\nimport GType\nimport Object (makeNewObject)\nimport GObject (makeNewGObject)\n{#import Hierarchy#}\n{#import GladeType#}\nimport GList\n\n{#context lib=\"glade\" prefix =\"glade\"#}\n\n\n-- | Create a new XML object (and the corresponding\n-- widgets) from the given XML file; corresponds to\n-- 'xmlNewWithRootAndDomain', but without the ability to specify a root\n-- widget or translation domain.\n--\nxmlNew :: FilePath -> IO (Maybe GladeXML)\nxmlNew file =\n withCString file $ \\strPtr1 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 nullPtr nullPtr\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Create a new GladeXML object (and\n-- the corresponding widgets) from the given XML file with an optional\n-- root widget and translation domain.\n--\n-- * If the second argument is not @Nothing@, the interface will only be built\n-- from the widget whose name is given. This feature is useful if you only\n-- want to build say a toolbar or menu from the XML file, but not the window\n-- it is embedded in. Note also that the XML parse tree is cached to speed\n-- up creating another \\'XML\\' object for the same file.\n--\nxmlNewWithRootAndDomain :: FilePath -> Maybe String -> Maybe String -> IO (Maybe GladeXML)\nxmlNewWithRootAndDomain file rootWidgetName domain =\n withCString file $ \\strPtr1 ->\n withMaybeCString rootWidgetName $ \\strPtr2 ->\n withMaybeCString domain $ \\strPtr3 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 strPtr2 strPtr3\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Get the widget that has the given name in\n-- the interface description. If the named widget cannot be found\n-- or is of the wrong type the result is an error.\n--\n-- * the second parameter should be a dynamic cast function that\n-- returns the type of object that you expect, eg castToButton\n--\n-- * the third parameter is the ID of the widget in the glade xml\n-- file, eg \\\"button1\\\".\n--\nxmlGetWidget :: (WidgetClass widget) => GladeXML -> (GObject -> widget) -> String -> IO widget\nxmlGetWidget xml cast name = do\n maybeWidget <- xmlGetWidgetRaw xml name\n return $ case maybeWidget of\n Just widget -> cast (toGObject widget) --the cast will return an error if the object is of the wrong type\n Nothing -> error $ \"glade.xmlGetWidget: no object named \" ++ show name ++ \" in the glade file\"\n\nxmlGetWidgetRaw :: GladeXML -> String -> IO (Maybe Widget)\nxmlGetWidgetRaw xml name =\n withCString name $ \\strPtr1 -> do\n widgetPtr <- {#call unsafe xml_get_widget#} xml strPtr1\n if widgetPtr==nullPtr then return Nothing\n else liftM Just $ makeNewObject mkWidget (return widgetPtr)\n\n-- Auxilliary routines\n-- -------------------\n\n-- Marshall an optional string\n--\nwithMaybeCString :: Maybe String -> (Ptr CChar -> IO a) -> IO a\nwithMaybeCString = maybeWith withCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"bebaff5b3ef089a9475e0d7461144584d46adec9","subject":"gio: don't use Control.Monad.>=> (it's not in ghc-6.6 or earlier)","message":"gio: don't use Control.Monad.>=> (it's not in ghc-6.6 or earlier)\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,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 ) 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":"a371e8f58b4daafc947168e6478c00a3a70dabdb","subject":"gstreamer: add StaticPadTemplate to M.S.G.Core.Types","message":"gstreamer: add StaticPadTemplate to M.S.G.Core.Types","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate(..),\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet =\n {# call static_pad_template_get #} >=> takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"e5e452cde3fbc9c61fadf2ae10de9356b3ba7db5","subject":"Added argc and argv passing in init - code copy from Gtk initGUI","message":"Added argc and argv passing in init - code copy from Gtk initGUI\n","repos":"gtk2hs\/gstreamer","old_file":"Media\/Streaming\/GStreamer\/Core\/Init.chs","new_file":"Media\/Streaming\/GStreamer\/Core\/Init.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-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Init (\n init,\n initCheck,\n deinit,\n version,\n versionString,\n#if GST_CHECK_VERSION(0,10,10)\n segtrapIsEnabled,\n segtrapSetEnabled,\n registryForkIsEnabled,\n registryForkSetEnabled,\n#endif\n#if GST_CHECK_VERSION(0,10,12)\n updateRegistry\n#endif\n ) where\n\nimport Control.Exception ( assert )\nimport Control.Monad ( liftM )\nimport Prelude hiding ( init )\nimport System.Glib.FFI\nimport System.Glib.GError\nimport System.Glib.UTFString ( peekUTFString, withUTFString )\nimport Control.Applicative\nimport System.Environment\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ninit :: IO ()\ninit = do\n allArgs <- (:) <$> getProgName <*> getArgs\n withMany withUTFString allArgs $ \\addrs ->\n withArrayLen addrs $ \\argc argv ->\n with argv $ \\argvp ->\n with argc $ \\argcp -> do\n {# call init #} (castPtr argcp) (castPtr argvp)\n\n\ninitCheck :: IO ()\ninitCheck =\n propagateGError $ \\gErrorPtr ->\n do succeeded <- liftM toBool $\n {# call init_check #} nullPtr nullPtr gErrorPtr\n assert (if succeeded\n then gErrorPtr == nullPtr\n else gErrorPtr \/= nullPtr) $ return ()\n\ndeinit :: IO ()\ndeinit =\n {# call deinit #}\n\nversion :: (Word, Word, Word, Word)\nversion =\n unsafePerformIO $\n alloca $ \\majorPtr ->\n alloca $ \\minorPtr ->\n alloca $ \\microPtr ->\n alloca $ \\nanoPtr ->\n do {# call version #} majorPtr minorPtr microPtr nanoPtr\n major <- peek majorPtr\n minor <- peek minorPtr\n micro <- peek microPtr\n nano <- peek nanoPtr\n return (fromIntegral major,\n fromIntegral minor,\n fromIntegral micro,\n fromIntegral nano)\n\nversionString :: String\nversionString =\n unsafePerformIO $\n {# call version_string #} >>= peekUTFString\n\n#if GST_CHECK_VERSION(0,10,10)\nsegtrapIsEnabled :: IO Bool\nsegtrapIsEnabled =\n liftM toBool {# call segtrap_is_enabled #}\n\nsegtrapSetEnabled :: Bool\n -> IO ()\nsegtrapSetEnabled enabled =\n {# call segtrap_set_enabled #} $ fromBool enabled\n\nregistryForkIsEnabled :: IO Bool\nregistryForkIsEnabled =\n liftM toBool {# call registry_fork_is_enabled #}\n\nregistryForkSetEnabled :: Bool\n -> IO ()\nregistryForkSetEnabled enabled =\n {# call registry_fork_set_enabled #} $ fromBool enabled\n#endif\n\n#if GST_CHECK_VERSION(0,10,12)\nupdateRegistry :: IO Bool\nupdateRegistry =\n liftM toBool {# call update_registry #}\n#endif\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-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Init (\n init,\n initCheck,\n deinit,\n version,\n versionString,\n#if GST_CHECK_VERSION(0,10,10)\n segtrapIsEnabled,\n segtrapSetEnabled,\n registryForkIsEnabled,\n registryForkSetEnabled,\n#endif\n#if GST_CHECK_VERSION(0,10,12)\n updateRegistry\n#endif\n ) where\n\nimport Control.Exception ( assert )\nimport Control.Monad ( liftM )\nimport Prelude hiding ( init )\nimport System.Glib.FFI\nimport System.Glib.GError\nimport System.Glib.UTFString ( peekUTFString )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ninit :: IO ()\ninit =\n {# call init #} nullPtr nullPtr\n\ninitCheck :: IO ()\ninitCheck =\n propagateGError $ \\gErrorPtr ->\n do succeeded <- liftM toBool $\n {# call init_check #} nullPtr nullPtr gErrorPtr\n assert (if succeeded\n then gErrorPtr == nullPtr\n else gErrorPtr \/= nullPtr) $ return ()\n\ndeinit :: IO ()\ndeinit =\n {# call deinit #}\n\nversion :: (Word, Word, Word, Word)\nversion =\n unsafePerformIO $\n alloca $ \\majorPtr ->\n alloca $ \\minorPtr ->\n alloca $ \\microPtr ->\n alloca $ \\nanoPtr ->\n do {# call version #} majorPtr minorPtr microPtr nanoPtr\n major <- peek majorPtr\n minor <- peek minorPtr\n micro <- peek microPtr\n nano <- peek nanoPtr\n return (fromIntegral major,\n fromIntegral minor,\n fromIntegral micro,\n fromIntegral nano)\n\nversionString :: String\nversionString =\n unsafePerformIO $\n {# call version_string #} >>= peekUTFString\n\n#if GST_CHECK_VERSION(0,10,10)\nsegtrapIsEnabled :: IO Bool\nsegtrapIsEnabled =\n liftM toBool {# call segtrap_is_enabled #}\n\nsegtrapSetEnabled :: Bool\n -> IO ()\nsegtrapSetEnabled enabled =\n {# call segtrap_set_enabled #} $ fromBool enabled\n\nregistryForkIsEnabled :: IO Bool\nregistryForkIsEnabled =\n liftM toBool {# call registry_fork_is_enabled #}\n\nregistryForkSetEnabled :: Bool\n -> IO ()\nregistryForkSetEnabled enabled =\n {# call registry_fork_set_enabled #} $ fromBool enabled\n#endif\n\n#if GST_CHECK_VERSION(0,10,12)\nupdateRegistry :: IO Bool\nupdateRegistry =\n liftM toBool {# call update_registry #}\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"eb592925c747b7c4f64290f4a7184d33178b8e67","subject":"Add new coordinate functions to get \"header height\" of treeView. (Deprecated `treeViewWidgetToTreeCoords` and `treeViewTreeToWidgetCoords`)","message":"Add new coordinate functions to get \"header height\" of treeView. (Deprecated `treeViewWidgetToTreeCoords` and `treeViewTreeToWidgetCoords`)\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","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-- | @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","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 treeViewWidgetToTreeCoords,\n treeViewTreeToWidgetCoords,\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 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-- | Convert tree to widget pixel coordinates.\n--\n-- * See module description.\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-- | Convert widget to tree pixel coordinates.\n--\n-- * See module description.\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\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":"6ef59baf73a81022b9ca881d674f137ca0e098a6","subject":"build\/create program functions","message":"build\/create program functions\n","repos":"Delan90\/opencl,IFCA\/opencl,Delan90\/opencl,IFCA\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Program.chs","new_file":"src\/System\/GPU\/OpenCL\/Program.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.Program( \n -- * Types\n CLProgram,\n -- * Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLDeviceID, CLError(..), \n wrapCheckSuccess, wrapPError )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'CL_DEVICE_SINGLE_FP_CONFIG'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'CL_DEVICE_DOUBLE_FP_CONFIG'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'CL_DEVICE_COMPILER_AVAILABLE' specified in the table of OpenCL Device\nQueries for 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\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.Program( \n -- * Types\n CLProgram\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLDeviceID )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CString -> Ptr () -> CSize -> Ptr () -> IO ()\nforeign import ccall \"wrapper\" wrapBuildCallback :: \n BuildCallback -> IO (FunPtr BuildCallback)\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLuint -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"dbf0e56f45b2d08db79bc7a72eece6c01a92854e","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","repos":"vincenthz\/webkit","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":"5a566f8302c21d37ca0034f804e09178a363e1e6","subject":"UncommentGValueCharFunctions","message":"UncommentGValueCharFunctions","repos":"vincenthz\/webkit","old_file":"glib\/System\/Glib\/GValueTypes.chs","new_file":"glib\/System\/Glib\/GValueTypes.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the\n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n valueSetUChar,\n valueGetUChar,\n valueSetChar,\n valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue (fromIntegral value)\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n liftM fromIntegral $ {# call unsafe value_get_uchar #} gvalue\n\n--these belong somewhere else, are in new c2hs's C2HS module\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\n--valueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar :: GValue -> Char -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue (cFromEnum value)\n\n--valueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar :: GValue -> IO Char\nvalueGetChar gvalue =\n liftM cToEnum $ {# call unsafe value_get_char #} gvalue\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValueTypes\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\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 is used by the implementation of properties and by the \n-- 'Graphics.UI.Gtk.TreeList.TreeModel' and\n-- related modules.\n--\nmodule System.Glib.GValueTypes (\n valueSetUInt,\n valueGetUInt,\n valueSetInt,\n valueGetInt,\n valueSetUInt64,\n valueGetUInt64,\n valueSetInt64,\n valueGetInt64,\n-- valueSetUChar,\n-- valueGetUChar,\n-- valueSetChar,\n-- valueGetChar,\n valueSetBool,\n valueGetBool,\n valueSetPointer,\n valueGetPointer,\n valueSetFloat,\n valueGetFloat,\n valueSetDouble,\n valueGetDouble,\n valueSetEnum,\n valueGetEnum,\n valueSetFlags,\n valueGetFlags,\n valueSetString,\n valueGetString,\n valueSetMaybeString,\n valueGetMaybeString,\n valueSetBoxed,\n valueGetBoxed,\n valueSetGObject,\n valueGetGObject,\n valueSetMaybeGObject,\n valueGetMaybeGObject,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString\n{#import System.Glib.GValue#}\t\t(GValue(GValue))\nimport System.Glib.GObject\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nvalueSetUInt :: GValue -> Word -> IO ()\nvalueSetUInt gvalue value =\n {# call unsafe value_set_uint #} gvalue (fromIntegral value)\n\nvalueGetUInt :: GValue -> IO Word\nvalueGetUInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint #} gvalue\n\nvalueSetInt :: GValue -> Int -> IO ()\nvalueSetInt gvalue value =\n {# call unsafe value_set_int #} gvalue (fromIntegral value)\n\nvalueGetInt :: GValue -> IO Int\nvalueGetInt gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int #} gvalue\n\nvalueSetUInt64 :: GValue -> Word64 -> IO ()\nvalueSetUInt64 gvalue value =\n {# call unsafe value_set_uint64 #} gvalue (fromIntegral value)\n\nvalueGetUInt64 :: GValue -> IO Word64\nvalueGetUInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_uint64 #} gvalue\n\nvalueSetInt64 :: GValue -> Int64 -> IO ()\nvalueSetInt64 gvalue value =\n {# call unsafe value_set_int64 #} gvalue (fromIntegral value)\n\nvalueGetInt64 :: GValue -> IO Int64\nvalueGetInt64 gvalue =\n liftM fromIntegral $\n {# call unsafe value_get_int64 #} gvalue\n\n{-\nvalueSetUChar :: GValue -> Word8 -> IO ()\nvalueSetUChar gvalue value =\n {# call unsafe value_set_uchar #} gvalue value\n\nvalueGetUChar :: GValue -> IO Word8\nvalueGetUChar gvalue =\n {# call unsafe value_get_uchar #} gvalue\n\nvalueSetChar :: GValue -> {#type gchar#} -> IO ()\nvalueSetChar gvalue value =\n {# call unsafe value_set_char #} gvalue value\n\nvalueGetChar :: GValue -> IO {#type gchar#}\nvalueGetChar gvalue =\n {# call unsafe value_get_char #} gvalue\n-}\n\nvalueSetBool :: GValue -> Bool -> IO ()\nvalueSetBool gvalue value =\n {# call unsafe value_set_boolean #} gvalue (fromBool value)\n\nvalueGetBool :: GValue -> IO Bool\nvalueGetBool gvalue =\n liftM toBool $\n {# call unsafe value_get_boolean #} gvalue\n\n-- These functions should probably never be used as they are dangerous.\n--\nvalueSetPointer :: GValue -> (Ptr ()) -> IO ()\nvalueSetPointer gvalue value =\n {# call unsafe value_set_pointer #} gvalue value\n\nvalueGetPointer :: GValue -> IO (Ptr ())\nvalueGetPointer gvalue =\n {# call unsafe value_get_pointer #} gvalue\n\nvalueSetFloat :: GValue -> Float -> IO ()\nvalueSetFloat gvalue value =\n {# call unsafe value_set_float #} gvalue (realToFrac value)\n\nvalueGetFloat :: GValue -> IO Float\nvalueGetFloat gvalue =\n liftM realToFrac $\n {# call unsafe value_get_float #} gvalue\n\nvalueSetDouble :: GValue -> Double -> IO ()\nvalueSetDouble gvalue value =\n {# call unsafe value_set_double #} gvalue (realToFrac value)\n\nvalueGetDouble :: GValue -> IO Double\nvalueGetDouble gvalue =\n liftM realToFrac $\n {# call unsafe value_get_double #} gvalue\n\nvalueSetEnum :: Enum enum => GValue -> enum -> IO ()\nvalueSetEnum gvalue value =\n {# call unsafe value_set_enum #} gvalue (fromIntegral $ fromEnum value)\n\nvalueGetEnum :: Enum enum => GValue -> IO enum\nvalueGetEnum gvalue =\n liftM (toEnum . fromIntegral) $\n {# call unsafe value_get_enum #} gvalue\n\nvalueSetFlags :: Flags flag => GValue -> [flag] -> IO ()\nvalueSetFlags gvalue value =\n {# call unsafe value_set_flags #} gvalue (fromIntegral $ fromFlags value)\n\nvalueGetFlags :: Flags flag => GValue -> IO [flag]\nvalueGetFlags gvalue =\n liftM (toFlags . fromIntegral) $\n {# call unsafe value_get_flags #} gvalue\n\nvalueSetString :: GValue -> String -> IO ()\nvalueSetString gvalue str =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueGetString :: GValue -> IO String\nvalueGetString gvalue = do\n strPtr <- {# call unsafe value_get_string #} gvalue\n if strPtr == nullPtr\n then return \"\"\n else peekUTFString strPtr\n\nvalueSetMaybeString :: GValue -> Maybe String -> IO ()\nvalueSetMaybeString gvalue (Just str) =\n withUTFString str $ \\strPtr ->\n {# call unsafe value_set_string #} gvalue strPtr\n\nvalueSetMaybeString gvalue Nothing =\n {# call unsafe value_set_static_string #} gvalue nullPtr\n\nvalueGetMaybeString :: GValue -> IO (Maybe String)\nvalueGetMaybeString gvalue =\n {# call unsafe value_get_string #} gvalue\n >>= maybePeek peekUTFString\n\nvalueSetBoxed :: (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GValue -> boxed -> IO ()\nvalueSetBoxed with gvalue boxed =\n with boxed $ \\boxedPtr -> do\n {# call unsafe g_value_set_boxed #} gvalue (castPtr boxedPtr)\n\nvalueGetBoxed :: (Ptr boxed -> IO boxed) -> GValue -> IO boxed\nvalueGetBoxed peek gvalue =\n {# call unsafe g_value_get_boxed #} gvalue >>= peek . castPtr\n\n-- for some weird reason the API says that gv is a gpointer, not a GObject\n--\nvalueSetGObject :: GObjectClass gobj => GValue -> gobj -> IO ()\nvalueSetGObject gvalue obj =\n withForeignPtr ((unGObject.toGObject) obj) $ \\objPtr ->\n {# call unsafe g_value_set_object #} gvalue (castPtr objPtr)\n\n-- Unsafe because it performs an unchecked downcast. Only for internal use.\n--\nvalueGetGObject :: GObjectClass gobj => GValue -> IO gobj\nvalueGetGObject gvalue =\n liftM unsafeCastGObject $\n makeNewGObject mkGObject $\n throwIfNull \"GValue.valueGetObject: extracting invalid object\" $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n\nvalueSetMaybeGObject :: GObjectClass gobj => GValue -> (Maybe gobj) -> IO ()\nvalueSetMaybeGObject gvalue (Just obj) = valueSetGObject gvalue obj\nvalueSetMaybeGObject gvalue Nothing =\n {# call unsafe g_value_set_object #} gvalue nullPtr\n\nvalueGetMaybeGObject :: GObjectClass gobj => GValue -> IO (Maybe gobj)\nvalueGetMaybeGObject gvalue =\n liftM (liftM unsafeCastGObject) $\n maybeNull (makeNewGObject mkGObject) $\n liftM castPtr $\n {# call unsafe value_get_object #} gvalue\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"8de1019d0b0168cb90f11f4e82f1e7c5fdf45dd1","subject":"Allocate a number of elements of storable type","message":"Allocate a number of elements of storable type\n\nIgnore-this: cfaff0d90d5147d8e29ce74131c3dde9\n- Changes from allocated a specific number of bytes. This matches the behaviour\n of the FFI, rather the standard C-like behaviour.\n\ndarcs-hash:20091216111720-9241b-265acb706d96ccf961713812d16dea463b6c084a.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/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 (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","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. Note that since the amount of pageable\n-- memory is thusly reduced, overall system performance may suffer. This is best\n-- used sparingly to allocate staging areas for data exchange.\n--\nmallocHost :: [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHost flags bytes =\n newHostPtr >>= \\hp -> withHostPtr hp $ \\p ->\n cuMemHostAlloc p bytes 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 suitably aligned for any type, and is not cleared.\n--\nmalloc :: Int -> IO (DevicePtr a)\nmalloc bytes = resultIfOk =<< cuMemAlloc bytes\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":"0a82810a1a466669d8252e9033f7f4c56e9c156a","subject":"some fixme notes","message":"some fixme notes\n\nIgnore-this: ff98e0d71c907cba59a92b153947e11b\n\ndarcs-hash:20100610144843-dcabc-d811e74493d71526b7fc95bba94bb3e899010fca.gz\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 ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(..), AddressMode(..), FilterMode(..), Format,\n create, destroy,\n getPtr, getAddressMode, getFilterMode,\n setPtr, setAddressMode, setFilterMode, setFormat,\n\n -- Internal\n peekTex\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture a = Texture { useTexture :: {# type CUtexref #}}\n\ninstance Storable (Texture a) 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-- |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-- |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-- |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-- |Texture data formats\n--\n{# enum CUarray_format as TextureFormat\n { }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\nclass Format a where\n tag :: a -> Int\n channels :: a -> Int\n channels _ = 1\n\ninstance Format Word where tag _ = fromEnum UNSIGNED_INT32\ninstance Format Word8 where tag _ = fromEnum UNSIGNED_INT8\ninstance Format Word16 where tag _ = fromEnum UNSIGNED_INT16\ninstance Format Word32 where tag _ = fromEnum UNSIGNED_INT32\n\ninstance Format Int where tag _ = fromEnum SIGNED_INT32\ninstance Format Int8 where tag _ = fromEnum SIGNED_INT8\ninstance Format Int16 where tag _ = fromEnum SIGNED_INT16\ninstance Format Int32 where tag _ = fromEnum SIGNED_INT32\n\ninstance Format Float where tag _ = fromEnum FLOAT\ninstance Format Double where\n tag _ = fromEnum SIGNED_INT32\n channels _ = 2\n -- __hiloint2double()\n\n-- FIXME:\n-- * half (16-bit float)\n-- * vector types\n-- * A Int or Word on the GPU is 32-bits, but this may not be the same bitwidth\n-- as Haskell-side computations.\n--\n\n--------------------------------------------------------------------------------\n-- Texture management\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--\ncreate :: Format a => IO (Texture a)\ncreate = do\n tex <- resultIfOk =<< cuTexRefCreate\n setFormat tex\n return tex\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture a' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture a -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture a' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture a -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture a -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture a -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture a' } -> `Status' cToEnum #}\n\n{-\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture a -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture a -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture a -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture a'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture a -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture a'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Format a => Texture a -> IO ()\nsetFormat tex = doSet undefined tex\n where\n doSet :: Format b => b -> Texture b -> IO ()\n doSet fmt _ = nothingIfOk =<< cuTexRefSetFormat tex (tag fmt) (channels fmt)\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO (Texture a)\npeekTex = liftM Texture . peek\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : (c) [2009..2010] 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(..), AddressMode(..), FilterMode(..), Format,\n create, destroy,\n getPtr, getAddressMode, getFilterMode,\n setPtr, setAddressMode, setFilterMode, setFormat,\n\n -- Internal\n peekTex\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.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |A texture reference\n--\nnewtype Texture a = Texture { useTexture :: {# type CUtexref #}}\n\ninstance Storable (Texture a) 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-- |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-- |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-- |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-- |Texture data formats\n--\n{# enum CUarray_format as TextureFormat\n { }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\nclass Format a where\n tag :: a -> Int\n channels :: a -> Int\n channels _ = 1\n\ninstance Format Word where tag _ = fromEnum UNSIGNED_INT32\ninstance Format Word8 where tag _ = fromEnum UNSIGNED_INT8\ninstance Format Word16 where tag _ = fromEnum UNSIGNED_INT16\ninstance Format Word32 where tag _ = fromEnum UNSIGNED_INT32\n\ninstance Format Int where tag _ = fromEnum SIGNED_INT32\ninstance Format Int8 where tag _ = fromEnum SIGNED_INT8\ninstance Format Int16 where tag _ = fromEnum SIGNED_INT16\ninstance Format Int32 where tag _ = fromEnum SIGNED_INT32\n\ninstance Format Float where tag _ = fromEnum FLOAT\ninstance Format Double where\n tag _ = fromEnum SIGNED_INT32\n channels _ = 2\n -- __hiloint2double()\n\n-- FIXME: half (16-bit float) ??\n-- FIXME: vector types ??\n\n--------------------------------------------------------------------------------\n-- Texture management\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--\ncreate :: Format a => IO (Texture a)\ncreate = do\n tex <- resultIfOk =<< cuTexRefCreate\n setFormat tex\n return tex\n\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture a' peekTex* } -> `Status' cToEnum #}\n\n\n-- |Destroy a texture reference\n--\ndestroy :: Texture a -> IO ()\ndestroy tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture a' } -> `Status' cToEnum #}\n\n\n-- |Get the address associated with a texture reference\n--\ngetPtr :: Texture a -> IO (DevicePtr a)\ngetPtr tex = resultIfOk =<< cuTexRefGetAddress tex\n\n{# fun unsafe cuTexRefGetAddress\n { alloca- `DevicePtr a' peekDevPtr*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\ngetAddressMode :: Texture a -> Int -> IO AddressMode\ngetAddressMode tex dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Get the filtering mode used by a texture reference\n--\ngetFilterMode :: Texture a -> IO FilterMode\ngetFilterMode tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture a' } -> `Status' cToEnum #}\n\n{-\n-- |Get the data format and number of channel components of the bound texture\n--\ngetFormat :: Texture a -> IO (Format, Int)\ngetFormat tex = do\n (status,fmt,dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture a' } -> `Status' cToEnum #}\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--\nsetPtr :: Texture a -> DevicePtr a -> Int -> IO ()\nsetPtr tex dptr bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |Specify the addressing mode for the given dimension of a texture reference\n--\nsetAddressMode :: Texture a -> Int -> AddressMode -> IO ()\nsetAddressMode tex dim mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture a'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\nsetFilterMode :: Texture a -> FilterMode -> IO ()\nsetFilterMode tex mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture a'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |Specify the format of the data to be read by the texture reference\n--\nsetFormat :: Format a => Texture a -> IO ()\nsetFormat tex = doSet undefined tex\n where\n doSet :: Format b => b -> Texture b -> IO ()\n doSet fmt _ = nothingIfOk =<< cuTexRefSetFormat tex (tag fmt) (channels fmt)\n\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture a'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekTex :: Ptr {# type CUtexref #} -> IO (Texture a)\npeekTex = liftM Texture . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"38fc20077a035236c91c708c3c85f00d1d75d687","subject":"Replace unimported liftM with (<$>)... oops!","message":"Replace unimported liftM with (<$>)... oops!\n","repos":"Delan90\/opencl,IFCA\/opencl,Delan90\/opencl,IFCA\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Types.chs","new_file":"src\/System\/GPU\/OpenCL\/Types.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 DeriveDataTypeable #-}\nmodule System.GPU.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Applicative( (<$>) )\nimport Control.Exception( Exception(..), throwIO )\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- getEnumCL <$> peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes = bitmaskToFlags [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\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 DeriveDataTypeable #-}\nmodule System.GPU.OpenCL.Types( \n -- * Symple CL Types\n CLbool, CLint, CLuint, CLulong, CLProgram, CLEvent, CLMem, CLPlatformID, \n CLDeviceID, CLContext, CLCommandQueue, CLPlatformInfo_, CLDeviceType_, \n CLDeviceInfo_, CLContextInfo_, CLContextProperty_, CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType_, CLCommandQueueProperty_, \n CLMemFlags_, CLImageFormat_p, CLMemObjectType_, CLMemInfo_, CLImageInfo_,\n CLProgramInfo_, CLBuildStatus_,CLKernel, CLProgramBuildInfo_, CLKernelInfo_,\n CLKernelWorkGroupInfo_, CLDeviceLocalMemType_, CLDeviceMemCacheType_,\n CLSampler, CLFilterMode_, CLSamplerInfo_, CLAddressingMode_,\n -- * High Level Types\n CLError(..), CLDeviceFPConfig(..), CLDeviceMemCacheType(..), \n CLDeviceExecCapability(..), CLDeviceLocalMemType(..), CLDeviceType(..), \n CLCommandQueueProperty(..), CLCommandType(..), CLCommandExecutionStatus(..), \n CLProfilingInfo(..), CLPlatformInfo(..), CLMemFlag(..), CLMemObjectType(..),\n CLBuildStatus(..), CLAddressingMode(..), CLFilterMode(..),\n -- * Functions\n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getCLValue, \n throwCLError, getEnumCL, bitmaskToFlags, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromFlags, bitmaskToCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability, bitmaskToMemFlags )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Typeable( Typeable(..) )\nimport Control.Exception( Exception(..), throwIO )\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#}\ntype CLKernel = {#type cl_kernel#}\ntype CLSampler = {#type cl_sampler#}\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#}\ntype CLProgramInfo_ = {#type cl_program_info#}\ntype CLProgramBuildInfo_ = {#type cl_program_build_info#}\ntype CLBuildStatus_ = {#type cl_build_status#}\ntype CLKernelInfo_ = {#type cl_kernel_info#}\ntype CLKernelWorkGroupInfo_ = {#type cl_kernel_work_group_info#}\ntype CLFilterMode_ = {#type cl_filter_mode#}\ntype CLSamplerInfo_ = {#type cl_sampler_info#}\ntype CLAddressingMode_ = {#type cl_addressing_mode#}\n\n{#pointer *cl_image_format as CLImageFormat_p#}\n\n--type CLImageChannelOrder_ = {#type cl_channel_order#}\n--type CLImageChannelDataType_ = {#type cl_channel_type#}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLError {\n cL_BUILD_PROGRAM_FAILURE=CL_BUILD_PROGRAM_FAILURE,\n cL_COMPILER_NOT_AVAILABLE=CL_COMPILER_NOT_AVAILABLE,\n cL_DEVICE_NOT_AVAILABLE=CL_DEVICE_NOT_AVAILABLE,\n cL_DEVICE_NOT_FOUND=CL_DEVICE_NOT_FOUND,\n cL_IMAGE_FORMAT_MISMATCH=CL_IMAGE_FORMAT_MISMATCH,\n cL_IMAGE_FORMAT_NOT_SUPPORTED=CL_IMAGE_FORMAT_NOT_SUPPORTED,\n cL_INVALID_ARG_INDEX=CL_INVALID_ARG_INDEX,\n cL_INVALID_ARG_SIZE=CL_INVALID_ARG_SIZE,\n cL_INVALID_ARG_VALUE=CL_INVALID_ARG_VALUE,\n cL_INVALID_BINARY=CL_INVALID_BINARY,\n cL_INVALID_BUFFER_SIZE=CL_INVALID_BUFFER_SIZE,\n cL_INVALID_BUILD_OPTIONS=CL_INVALID_BUILD_OPTIONS,\n cL_INVALID_COMMAND_QUEUE=CL_INVALID_COMMAND_QUEUE,\n cL_INVALID_CONTEXT=CL_INVALID_CONTEXT,\n cL_INVALID_DEVICE=CL_INVALID_DEVICE,\n cL_INVALID_DEVICE_TYPE=CL_INVALID_DEVICE_TYPE,\n cL_INVALID_EVENT=CL_INVALID_EVENT,\n cL_INVALID_EVENT_WAIT_LIST=CL_INVALID_EVENT_WAIT_LIST,\n cL_INVALID_GL_OBJECT=CL_INVALID_GL_OBJECT,\n cL_INVALID_GLOBAL_OFFSET=CL_INVALID_GLOBAL_OFFSET,\n cL_INVALID_HOST_PTR=CL_INVALID_HOST_PTR,\n cL_INVALID_IMAGE_FORMAT_DESCRIPTOR=CL_INVALID_IMAGE_FORMAT_DESCRIPTOR,\n cL_INVALID_IMAGE_SIZE=CL_INVALID_IMAGE_SIZE,\n cL_INVALID_KERNEL_NAME=CL_INVALID_KERNEL_NAME,\n cL_INVALID_KERNEL=CL_INVALID_KERNEL,\n cL_INVALID_KERNEL_ARGS=CL_INVALID_KERNEL_ARGS,\n cL_INVALID_KERNEL_DEFINITION=CL_INVALID_KERNEL_DEFINITION,\n cL_INVALID_MEM_OBJECT=CL_INVALID_MEM_OBJECT,\n cL_INVALID_OPERATION=CL_INVALID_OPERATION,\n cL_INVALID_PLATFORM=CL_INVALID_PLATFORM,\n cL_INVALID_PROGRAM=CL_INVALID_PROGRAM,\n cL_INVALID_PROGRAM_EXECUTABLE=CL_INVALID_PROGRAM_EXECUTABLE,\n cL_INVALID_QUEUE_PROPERTIES=CL_INVALID_QUEUE_PROPERTIES,\n cL_INVALID_SAMPLER=CL_INVALID_SAMPLER,\n cL_INVALID_VALUE=CL_INVALID_VALUE,\n cL_INVALID_WORK_DIMENSION=CL_INVALID_WORK_DIMENSION,\n cL_INVALID_WORK_GROUP_SIZE=CL_INVALID_WORK_GROUP_SIZE,\n cL_INVALID_WORK_ITEM_SIZE=CL_INVALID_WORK_ITEM_SIZE,\n cL_MAP_FAILURE=CL_MAP_FAILURE,\n cL_MEM_OBJECT_ALLOCATION_FAILURE=CL_MEM_OBJECT_ALLOCATION_FAILURE,\n cL_MEM_COPY_OVERLAP=CL_MEM_COPY_OVERLAP,\n cL_OUT_OF_HOST_MEMORY=CL_OUT_OF_HOST_MEMORY,\n cL_OUT_OF_RESOURCES=CL_OUT_OF_RESOURCES,\n cL_PROFILING_INFO_NOT_AVAILABLE=CL_PROFILING_INFO_NOT_AVAILABLE,\n cL_SUCCESS=CL_SUCCESS\n };\n#endc\n\n{-| \n * 'CL_BUILD_PROGRAM_FAILURE', Returned if there is a failure to build the\nprogram executable.\n\n * 'CL_COMPILER_NOT_AVAILABLE', Returned if the parameter program is created with\n'clCreateProgramWithSource' and a compiler is not available. For example\n'clDeviceCompilerAvalaible' is set to 'False'.\n\n * 'CL_DEVICE_NOT_AVAILABLE', Returned if the specified device is not currently\navailable.\n\n * 'CL_DEVICE_NOT_FOUND', Returned if no OpenCL devices that match the specified\ndevices were found.\n\n * 'CL_IMAGE_FORMAT_MISMATCH', Returned if the specified source and destination\nimages are not valid image objects.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED', Returned if the specified image format is not\nsupported.\n\n * 'CL_INVALID_ARG_INDEX', Returned if an invalid argument index is specified.\n\n * 'CL_INVALID_ARG_SIZE', Returned if argument size specified (arg_size) does not\nmatch the size of the data type for an argument that is not a memory object, or\nif the argument is a memory object and arg_size != sizeof(cl_mem) or if arg_size\nis zero and the argument is declared with the __local qualifier or if the\nargument is a sampler and arg_size != sizeof(cl_sampler).\n\n * 'CL_INVALID_ARG_VALUE', Returned if the argument value specified is NULL for\nan argument that is not declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_BINARY', Returned if the program binary is not a valid binary for\nthe specified device.\n\n * 'CL_INVALID_BUFFER_SIZE', Returned if the value of the parameter size is 0 or\nis greater than 'clDeviceMaxMemAllocSize' for all devices specified in the\nparameter context.\n\n * 'CL_INVALID_BUILD_OPTIONS', Returned if the specified build options are\ninvalid.\n\n * 'CL_INVALID_COMMAND_QUEUE', Returned if the specified command-queue is not a\nvalid command-queue.\n\n * 'CL_INVALID_CONTEXT', Returned if the specified context is not a valid OpenCL\ncontext, or the context associated with certain parameters are not the same.\n\n * 'CL_INVALID_DEVICE', Returned if the device or devices specified are not\nvalid.\n\n * 'CL_INVALID_DEVICE_TYPE', Returned if device type specified is not valid.\n\n * 'CL_INVALID_EVENT', Returned if the event objects specified are not valid.\n\n * 'CL_INVALID_EVENT_WAIT_LIST', Returned if event_wait_list is NULL and\nnum_events_in_wait_list > 0, or event_wait_list_list is not NULL and\nnum_events_in_wait_list is 0, or specified event objects are not valid events.\n\n * 'CL_INVALID_GL_OBJECT', Returned if obj is not a vaild GL object or is a GL\nobject but does not have an existing data store.\n\n * 'CL_INVALID_GLOBAL_OFFSET', Returned if global_work_offset is not NULL.\n\n * 'CL_INVALID_HOST_PTR', Returned if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR'\nor '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_INVALID_IMAGE_FORMAT_DESCRIPTOR', Returned if the image format specified\nis not valid or is NULL or does not map to a supported OpenCL image format.\n\n * 'CL_INVALID_IMAGE_SIZE', Returned if the specified image width or height are\ninvalid or if the image row pitch and image slice pitch do not follow the rules.\n\n * 'CL_INVALID_KERNEL_NAME', Returned if the specified kernel name is not found\nin program.\n\n * 'CL_INVALID_KERNEL', Returned if the specified kernel is not a valid kernel\nobject.\n\n * 'CL_INVALID_KERNEL_ARGS', Returned if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_KERNEL_DEFINITION', Returned if the function definition for\n__kernel function given by kernel_name such as the number of arguments, the\nargument types are not the same for all devices for which the program executable\nhas been built.\n\n * 'CL_INVALID_MEM_OBJECT', Returned if a parameter is not a valid memory, image,\nor buffer object.\n\n * 'CL_INVALID_OPERATION', Returned if there are no devices in context that\nsupport images. Returned if the build of a program executable for any of the\ndevices specified by a previous call to 'clBuildProgram' for program has not\ncompleted, or if there are kernel objects attached to program. Returned by\n'clEnqueueNativeKernel' if the specified device cannot execute the native\nkernel.\n\n * 'CL_INVALID_PLATFORM', Returned if the specified platform is not a valid\nplatform, or no platform could be selected, or if platform value specified in\nproperties is not a valid platform.\n\n * 'CL_INVALID_PROGRAM', Returned if the specified program is not a valid program\nobject.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE', Returned if there is no successfully built\nexecutable for program, or if there is no device in program. Returned if there\nis no successfully built program executable available for device associated with\ncommand_queue.\n\n * 'CL_INVALID_QUEUE_PROPERTIES', Returned if specified properties are valid but\nare not supported by the device.\n\n * 'CL_INVALID_SAMPLER', Returned if the specified sampler is not a valid sampler\nobject, or for an argument declared to be of type sampler_t when the specified\narg_value is not a valid sampler object.\n\n * 'CL_INVALID_VALUE', Returned if a parameter is not an expected value.\n\n * 'CL_INVALID_WORK_DIMENSION', Returned if work_dim is not a valid value.\n\n * 'CL_INVALID_WORK_GROUP_SIZE', Returned if local_work_size is specified and\nnumber of workitems specified by global_work_size is not evenly divisible by\nsize of work-group given by local_work_size or does not match the work-group\nsize specified for kernel using the __attribute__((reqd_work_group_size(X, Y,\nZ))) qualifier in program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE', Returned if the number of work-items specified in\nany of local_work_size... [0]... local_work_size[work_dim - 1] is greater than\nthe corresponding values specified by 'clDeviceMaxWorkItemSizes'.\n\n * 'CL_MAP_FAILURE', Returned by if there is a failure to map the requested\nregion into the host address space. This error cannot occur for buffer objects\ncreated with 'CLMEM_USE_HOST_PTR' or 'CLMEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE', Returned if there is a failure to allocate\nmemory for data store associated with image or buffer objects specified as\narguments to kernel.\n\n * 'CL_MEM_COPY_OVERLAP', Returned if the source and destination images are the\nsame image (or the source and destination buffers are the same buffer), and the\nsource and destination regions overlap.\n\n * 'CL_OUT_OF_HOST_MEMORY', Returned in the event of a failure to allocate\nresources required by the OpenCL implementation on the host.\n\n * 'CL_OUT_OF_RESOURCES', Returned in the event of a failure to queue the\nexecution instance of kernel on the command-queue because of insufficient\nresources needed to execute the kernel.\n\n * 'CL_PROFILING_INFO_NOT_AVAILABLE', Returned if the 'CL_QUEUE_PROFILING_ENABLE'\nflag is not set for the command-queue and the profiling information is currently\nnot available (because the command identified by event has not completed).\n\n * 'CL_SUCCESS', Indicates that the function executed successfully.\n-}\n{#enum CLError {upcaseFirstLetter} deriving( Show, Eq, Typeable ) #}\n\ninstance Exception CLError\n\nthrowCLError :: CLint -> IO a\nthrowCLError = throwIO . (getEnumCL :: CLint -> CLError)\n\nwrapPError :: (Ptr CLint -> IO a) -> IO a\nwrapPError f = alloca $ \\perr -> do\n v <- f perr\n errcode <- liftM getEnumCL $ peek perr\n if errcode == CL_SUCCESS\n then return v\n else throwIO errcode\n \nwrapCheckSuccess :: IO CLint -> IO Bool\nwrapCheckSuccess f = f >>= return . (==CL_SUCCESS) . getEnumCL\n\nwrapGetInfo :: Storable a \n => (Ptr a -> Ptr CSize -> IO CLint) -> (a -> b) -> IO b\nwrapGetInfo fget fconvert= alloca $ \\dat -> do\n errcode <- fget dat nullPtr\n if errcode == getCLValue CL_SUCCESS\n then fmap fconvert $ peek dat\n else throwCLError errcode\n\nwhenSuccess :: IO CLint -> IO a -> IO a\nwhenSuccess fcheck fval = do\n errcode <- fcheck\n if errcode == getCLValue CL_SUCCESS\n then fval\n else throwCLError errcode\n \n-- -----------------------------------------------------------------------------\n#c\nenum CLPlatformInfo {\n cL_PLATFORM_PROFILE=CL_PLATFORM_PROFILE,\n cL_PLATFORM_VERSION=CL_PLATFORM_VERSION,\n cL_PLATFORM_NAME=CL_PLATFORM_NAME,\n cL_PLATFORM_VENDOR=CL_PLATFORM_VENDOR,\n cL_PLATFORM_EXTENSIONS=CL_PLATFORM_EXTENSIONS\n };\n#endc\n\n{-|\n * 'CL_PLATFORM_PROFILE', OpenCL profile string. Returns the profile name \nsupported by the implementation. The profile name returned can be one of the \nfollowing strings:\n\n [@FULL_PROFILE@] If the implementation supports the OpenCL specification\n(functionality defined as part of the core specification and does not require\nany extensions to be supported).\n\n [@EMBEDDED_PROFILE@] If the implementation supports the OpenCL embedded \nprofile. The embedded profile is defined to be a subset for each version of \nOpenCL.\n\n * 'CL_PLATFORM_VERSION', OpenCL version string. Returns the OpenCL version \nsupported by the implementation. This version string has the following format: \n\/OpenCL major_version.minor_version platform-specific information\/ The \n\/major_version.minor_version\/ value returned will be 1.0.\n \n * 'CL_PLATFORM_NAME', Platform name string.\n \n * 'CL_PLATFORM_VENDOR', Platform vendor string.\n \n * 'CL_PLATFORM_EXTENSIONS', Returns a space-separated list of extension names \n(the extension names themselves do not contain any spaces) supported by the \nplatform. Extensions defined here must be supported by all devices associated \nwith this platform.\n-}\n{#enum CLPlatformInfo {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\n cL_DEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\n cL_DEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\n cL_DEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\n cL_DEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\n cL_DEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CL_DEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host \nprocessor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CL_DEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the \ndevice can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CL_DEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the \nIBM CELL Blade). These devices communicate with the host processor using a \nperipheral interconnect such as PCIe.\n \n * 'CL_DEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CL_DEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandQueueProperty { \n cL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n cL_QUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CL_QUEUE_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 * 'CL_QUEUE_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 {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n cL_FP_DENORM=CL_FP_DENORM, cL_FP_INF_NAN=CL_FP_INF_NAN,\n cL_FP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n cL_FP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n cL_FP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, cL_FP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CL_FP_DENORM', denorms are supported.\n \n * 'CL_FP_INF_NAN', INF and NaNs are supported.\n \n * 'CL_FP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CL_FP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CL_FP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CL_FP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n cL_EXEC_KERNEL=CL_EXEC_KERNEL,\n cL_EXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CL_EXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CL_EXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n cL_NONE=CL_NONE, cL_READ_ONLY_CACHE=CL_READ_ONLY_CACHE,\n cL_READ_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLDeviceLocalMemType {\n cL_LOCAL=CL_LOCAL, cL_GLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLCommandType {\n cL_COMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n cL_COMMAND_TASK=CL_COMMAND_TASK ,\n cL_COMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n cL_COMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n cL_COMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n cL_COMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n cL_COMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n cL_COMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n cL_COMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n cL_COMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n cL_COMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n cL_COMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n cL_COMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n cL_COMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n cL_COMMAND_MARKER=CL_COMMAND_MARKER,\n cL_COMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n cL_COMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLCommandExecutionStatus {\n cL_QUEUED=CL_QUEUED, cL_SUBMITTED=CL_SUBMITTED, cL_RUNNING=CL_RUNNING,\n cL_COMPLETE=CL_COMPLETE, cL_EXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CL_QUEUED', command has been enqueued in the command-queue.\n\n * 'CL_SUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CL_RUNNING', device is currently executing this command.\n \n * 'CL_COMPLETE', the command has completed.\n \n * 'CL_EXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLProfilingInfo {\n cL_PROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n cL_PROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n cL_PROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n cL_PROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CL_PROFILING_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 * 'CL_PROFILING_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 * 'CL_PROFILING_COMMAND_START', 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 * 'CL_PROFILING_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 {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemFlag {\n cL_MEM_READ_WRITE=CL_MEM_READ_WRITE,\n cL_MEM_WRITE_ONLY=CL_MEM_WRITE_ONLY,\n cL_MEM_READ_ONLY=CL_MEM_READ_ONLY,\n cL_MEM_USE_HOST_PTR=CL_MEM_USE_HOST_PTR,\n cL_MEM_ALLOC_HOST_PTR=CL_MEM_ALLOC_HOST_PTR,\n cL_MEM_COPY_HOST_PTR=CL_MEM_COPY_HOST_PTR\n };\n#endc\n{-| \n * 'CL_MEM_READ_WRITE', This flag specifies that the memory object will be\nread and written by a kernel. This is the default.\n\n * 'CL_MEM_WRITE_ONLY', This flags specifies that the memory object will be\nwritten but not read by a kernel. Reading from a buffer or image object created\nwith 'CLMEM_WRITE_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_READ_ONLY', This flag specifies that the memory object is a read-only\nmemory object when used inside a kernel. Writing to a buffer or image object\ncreated with 'CLMEM_READ_ONLY' inside a kernel is undefined.\n\n * 'CL_MEM_USE_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nuse memory referenced by host_ptr as the storage bits for the memory\nobject. OpenCL implementations are allowed to cache the buffer contents pointed\nto by host_ptr in device memory. This cached copy can be used when kernels are\nexecuted on a device. The result of OpenCL commands that operate on multiple\nbuffer objects created with the same host_ptr or overlapping host regions is\nconsidered to be undefined.\n\n * 'CL_MEM_ALLOC_HOST_PTR', This flag specifies that the application wants the\nOpenCL implementation to allocate memory from host accessible\nmemory. 'CL_MEM_ALLOC_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually exclusive.\n\n * 'CL_MEM_COPY_HOST_PTR', This flag is valid only if host_ptr is not NULL. If\nspecified, it indicates that the application wants the OpenCL implementation to\nallocate memory for the memory object and copy the data from memory referenced\nby host_ptr. 'CL_MEM_COPY_HOST_PTR' and 'CL_MEM_USE_HOST_PTR' are mutually\nexclusive. 'CL_MEM_COPY_HOST_PTR' can be used with 'CL_MEM_ALLOC_HOST_PTR' to\ninitialize the contents of the cl_mem object allocated using host-accessible\n(e.g. PCIe) memory. \n-} \n{#enum CLMemFlag {upcaseFirstLetter} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLMemObjectType {\n cL_MEM_OBJECT_BUFFER=CL_MEM_OBJECT_BUFFER,\n cL_MEM_OBJECT_IMAGE2D=CL_MEM_OBJECT_IMAGE2D,\n cL_MEM_OBJECT_IMAGE3D=CL_MEM_OBJECT_IMAGE3D\n };\n#endc\n\n{-| * 'CL_MEM_OBJECT_BUFFER' if memobj is created with 'clCreateBuffer'. \n \n * 'CL_MEM_OBJECT_IMAGE2D' if memobj is created with 'clCreateImage2D' \n\n * 'CL_MEM_OBJECT_IMAGE3D' if memobj is created with 'clCreateImage3D'.\n-}\n{#enum CLMemObjectType {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLBuildStatus {\n cL_BUILD_NONE=CL_BUILD_NONE,\n cL_BUILD_ERROR=CL_BUILD_ERROR,\n cL_BUILD_SUCCESS=CL_BUILD_SUCCESS,\n cL_BUILD_IN_PROGRESS=CL_BUILD_IN_PROGRESS,\n };\n#endc\n\n{-| * 'CL_BUILD_NONE'. The build status returned if no build has been performed\non the specified program object for device.\n\n * 'CL_BUILD_ERROR'. The build status returned if the last call to\n'clBuildProgram' on the specified program object for device generated an error.\n\n * 'CL_BUILD_SUCCESS'. The build status retrned if the last call to\n'clBuildProgram' on the specified program object for device was successful.\n\n * 'CL_BUILD_IN_PROGRESS'. The build status returned if the last call to \n'clBuildProgram' on the specified program object for device has not finished.\n-}\n{#enum CLBuildStatus {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLAddressingMode {\n cL_ADDRESS_REPEAT=CL_ADDRESS_REPEAT,\n cL_ADDRESS_CLAMP_TO_EDGE =CL_ADDRESS_CLAMP_TO_EDGE ,\n cL_ADDRESS_CLAMP=CL_ADDRESS_CLAMP,\n cL_ADDRESS_NONE=CL_ADDRESS_NONE\n };\n#endc\n{#enum CLAddressingMode {upcaseFirstLetter} deriving( Show ) #}\n\n#c\nenum CLFilterMode {\n cL_FILTER_NEAREST=CL_FILTER_NEAREST,\n cL_FILTER_LINEAR=CL_FILTER_LINEAR,\n };\n#endc\n{#enum CLFilterMode {upcaseFirstLetter} deriving( Show ) #}\n\n-- -----------------------------------------------------------------------------\ngetCLValue :: (Enum a, Integral b) => a -> b\ngetCLValue = fromIntegral . fromEnum\n\ngetEnumCL :: (Integral a, Enum b) => a -> b\ngetEnumCL = toEnum . fromIntegral \n\ngetCommandExecutionStatus :: CLint -> CLCommandExecutionStatus\ngetCommandExecutionStatus n \n | n < 0 = CL_EXEC_ERROR\n | otherwise = getEnumCL $ n\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\nbitmaskFromFlags :: (Enum a, Bits b) => [a] -> b\nbitmaskFromFlags = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n\nbitmaskToFlags :: (Enum a, Bits b) => [a] -> b -> [a]\nbitmaskToFlags xs mask = filter (testMask mask . fromIntegral . fromEnum) xs\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes = bitmaskToFlags [CL_DEVICE_TYPE_CPU,CL_DEVICE_TYPE_GPU,CL_DEVICE_TYPE_ACCELERATOR,CL_DEVICE_TYPE_DEFAULT,CL_DEVICE_TYPE_ALL]\n\nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties = bitmaskToFlags (binaryFlags maxBound)\n \nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability = bitmaskToFlags (binaryFlags maxBound)\n\nbitmaskToMemFlags :: CLMemFlags_ -> [CLMemFlag]\nbitmaskToMemFlags = bitmaskToFlags (binaryFlags maxBound)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"aa1aab3fed09ec47c0ea033f576d842254ca00d5","subject":"removed unused objets from gdal. prepare to use mutex on band access","message":"removed unused objets from gdal. prepare to use mutex on band access\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{-# LANGUAGE RankNTypes #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , DriverName\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\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 -- Internal Util\n , throwIfError\n , withDataset\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\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 GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype Dataset a t = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset :: Dataset a t -> ForeignPtr (Dataset a t)\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\n\nwithDataset :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band s a t) = Band (Ptr (Band s a t))\n\nunBand :: Band s a t -> Ptr (Band s a t)\nunBand (Band b) = b\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as 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\ncreate\n :: forall t. HasDatatype t\n => String -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate'\n :: forall t. HasDatatype t\n => 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\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\n :: HasDatatype t\n => Int -> Int -> Int -> DriverOptions -> IO (Dataset ReadWrite 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 -> (forall s. Band s 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 s a t))\n\n\nbandDatatype :: (Band s a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s 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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s a t) -> CInt\n\n\nbandNodataValue :: (Band s 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 s a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s 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 s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s 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 s 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\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 s b a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand' = readBand\n\nreadBand :: forall s a b t. HasDatatype a\n => (Band s 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 s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall s a. HasDatatype a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall s a t. HasDatatype a\n => (RWBand s 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 s 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\n\nreadBandBlock\n :: forall s a t. HasDatatype t\n => Band s a t -> Int -> Int -> IOVector t\nreadBandBlock 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 s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock :: HasDatatype t => RWBand s t -> Int -> Int -> Vector t -> IO ()\nwriteBandBlock 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 s t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\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 s a t v. Typeable v\n => Band s a t -> v -> Bool\nisValidDatatype b v\n = let vt = typeOf v\n in case bandDatatype b of\n GDT_Byte -> vt == typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> vt == typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> vt == typeOf (undefined :: Vector Word32)\n GDT_Int16 -> vt == typeOf (undefined :: Vector Int16)\n GDT_Int32 -> vt == typeOf (undefined :: Vector Int32)\n GDT_Float32 -> vt == typeOf (undefined :: Vector Float)\n GDT_Float64 -> vt == typeOf (undefined :: Vector Double)\n GDT_CInt16 -> vt == typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> vt == typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> vt == typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> vt == typeOf (undefined :: Vector (GComplex Double))\n _ -> False\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{-# LANGUAGE RankNTypes #-}\n\nmodule OSGeo.GDAL.Internal (\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 -- 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 s a t) = Band (Ptr ((Band s a t)))\n\nunBand (Band b) = b\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s 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 destroy 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\ncreate\n :: forall t. HasDatatype t\n => String -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate'\n :: forall t. HasDatatype t\n => 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\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\n :: HasDatatype t\n => Int -> Int -> Int -> DriverOptions -> IO (Dataset ReadWrite 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 -> (forall s. Band s 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 s a t))\n\n\nbandDatatype :: (Band s a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band s a t) -> CInt\n\n\nbandBlockSize :: (Band s 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 s a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band s a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band s a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band s a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band s a t) -> CInt\n\n\nbandNodataValue :: (Band s 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 s a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand s 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 s t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand s 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 s 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\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 s b a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand' = readBand\n\nreadBand :: forall s a b t. HasDatatype a\n => (Band s 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 s a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall s a. HasDatatype a\n => (RWBand s a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall s a t. HasDatatype a\n => (RWBand s 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 s 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\n\nreadBandBlock\n :: forall s a t. HasDatatype t\n => Band s a t -> Int -> Int -> IOVector t\nreadBandBlock 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 s a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nwriteBandBlock :: HasDatatype t => RWBand s t -> Int -> Int -> Vector t -> IO ()\nwriteBandBlock 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 s t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\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 s a t v. Typeable v\n => Band s a t -> v -> Bool\nisValidDatatype b v\n = let vt = typeOf v\n in case bandDatatype b of\n GDT_Byte -> vt == typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> vt == typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> vt == typeOf (undefined :: Vector Word32)\n GDT_Int16 -> vt == typeOf (undefined :: Vector Int16)\n GDT_Int32 -> vt == typeOf (undefined :: Vector Int32)\n GDT_Float32 -> vt == typeOf (undefined :: Vector Float)\n GDT_Float64 -> vt == typeOf (undefined :: Vector Double)\n GDT_CInt16 -> vt == typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> vt == typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> vt == typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> vt == typeOf (undefined :: Vector (GComplex Double))\n _ -> False\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e79b880b78eabec0cea98a9bf4d6c9093ddfc5c3","subject":"Fixed typo.","message":"Fixed typo.","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebDataSource.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content. The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\nwebDataSourceGetData :: WebDataSourceClass self => self\n -> IO (Maybe String)\nwebDataSourceGetData ds = do\n gstr <- {#call webkit_web_data_source_get_data #}\n (toWebDataSource ds)\n readGString gstr\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebDataSource\n-- Author : Andy Stewart\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-- Function `webkit_web_data_source_get_data` haven't binding, \n-- no idea how to handle `GString`\n--\n-- Access to the WebKit Web DataSource\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebDataSource (\n-- * Description\n-- | Data source encapsulates the content of a WebKitWebFrame. A WebKitWebFrame has a main resource and\n-- subresources and the data source provides access to these resources. When a request gets loaded\n-- initially, it is set to a provisional state. The application can request for the request that\n-- initiated the load by asking for the provisional data source and invoking the\n-- 'webDataSourceGetInitialRequest' method of WebKitWebDataSource. This data source may not\n-- have enough data and some methods may return empty values. To get a \"full\" data source with the data\n-- and resources loaded, you need to get the non-provisional data source through WebKitWebFrame's\n-- 'webFrameGetDataSource' method. This data source will have the data after everything was\n-- loaded. Make sure that the data source was finished loading before using any of its methods. You can\n-- do this via 'webDataSourceIsLoading'.\n\n-- * Types\n WebDataSource,\n WebDataSourceClass,\n\n-- * Constructors\n webDataSourceNew,\n\n-- * Methods \n webDataSourceGetData,\n webDataSourceGetEncoding,\n webDataSourceGetInitialRequest,\n webDataSourceGetMainResource,\n webDataSourceGetRequest,\n webDataSourceGetSubresources,\n webDataSourceGetUnreachableUri,\n webDataSourceGetWebFrame,\n webDataSourceIsLoading,\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.GString\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 System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n-- | Creates a new 'WebDataSource' instance. \n-- The URL of the 'WebDataSource' will be set to \"about:blank\".\nwebDataSourceNew :: IO WebDataSource\nwebDataSourceNew = \n wrapNewGObject mkWebDataSource $ {#call web_data_source_new#} \n\n-- | Returns the raw data that represents the the frame's content.The data will be incomplete until the\n-- data has finished loading. Returns 'Nothing' if the web frame hasn't loaded any data. Use\n-- @webkitWebDataSourceIsLoading@ to test if data source is in the process of loading.\nwebDataSourceGetData :: WebDataSourceClass self => self\n -> IO (Maybe String)\nwebDataSourceGetData ds = do\n gstr <- {#call webkit_web_data_source_get_data #}\n (toWebDataSource ds)\n readGString gstr\n\n-- | Returns the text encoding name as set in the 'WebView', or if not, the text encoding of the response.\nwebDataSourceGetEncoding ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetEncoding ds = \n {#call web_data_source_get_encoding#} (toWebDataSource ds) >>= peekCString\n \n-- | Returns a reference to the original request that was used to load the web content. \n-- The NetworkRequest returned by this method is the\n-- request prior to the \"committed\" load state. \n-- See 'webDataSourceGetRequest' for getting the \"committed\" request.\nwebDataSourceGetInitialRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetInitialRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_initial_request#} (toWebDataSource ds)\n\n-- | Returns the main resource of the data_source\nwebDataSourceGetMainResource ::\n WebDataSourceClass self => self\n -> IO WebResource \nwebDataSourceGetMainResource ds =\n makeNewGObject mkWebResource $ {#call web_data_source_get_main_resource#} (toWebDataSource ds)\n \n-- | Returns a NetworkRequest that was used to create this 'WebDataSource'. \n-- The NetworkRequest returned by this method is the request that was \"committed\", \n-- and hence, different from the request you get from the 'webDataSourceGetInitialRequest' method.\nwebDataSourceGetRequest ::\n WebDataSourceClass self => self\n -> IO NetworkRequest\nwebDataSourceGetRequest ds =\n makeNewGObject mkNetworkRequest $ {# call web_data_source_get_request#} (toWebDataSource ds)\n\n-- | Gives you a List of 'WebResource' objects that compose the 'WebView' to which this 'WebDataSource' is attached.\nwebDataSourceGetSubresources ::\n WebDataSourceClass self => self\n -> IO [WebResource] \nwebDataSourceGetSubresources ds = do\n glist <- {#call web_data_source_get_subresources#} (toWebDataSource ds)\n resourcePtr <- fromGList glist\n mapM (makeNewGObject mkWebResource . return) resourcePtr\n\n-- | Return the unreachable URI of data_source. \n-- The 'dataSource' will have an unreachable URL \n-- if it was created using 'WebFrame''s \n-- 'webFrameLoadAlternateHtmlString' method.\nwebDataSourceGetUnreachableUri ::\n WebDataSourceClass self => self\n -> IO String\nwebDataSourceGetUnreachableUri ds =\n {#call web_data_source_get_unreachable_uri#} (toWebDataSource ds) >>= peekCString\n\n-- | Returns the 'WebFrame' that represents this data source\nwebDataSourceGetWebFrame ::\n WebDataSourceClass self => self\n -> IO WebFrame\nwebDataSourceGetWebFrame ds =\n makeNewGObject mkWebFrame $ {#call web_data_source_get_web_frame#} (toWebDataSource ds)\n\n-- | Determines whether the data source is in the process of loading its content.\nwebDataSourceIsLoading ::\n WebDataSourceClass self => self\n -> IO Bool\nwebDataSourceIsLoading ds =\n liftM toBool $ {#call web_data_source_is_loading#} (toWebDataSource ds)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"de6571c012407c219fa406a491bc837ec23bdb93","subject":"Xine.Foreign: move some code around","message":"Xine.Foreign: move some code around\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{-# OPTIONS_GHC -Wwarn #-}\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(..), DemuxStrategy(..), Verbosity(..), MRL, EngineParam(..),\n 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------------------------------------------------------------------------------\n-- Marshalling helpers\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\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-- Foreign interface\n------------------------------------------------------------------------------\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------------------------------------------------------------------------------\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-- | An opaque type, never dereferenced on the Haskell side\n-- XXX: document me\n{#pointer *xine_t as Engine foreign newtype#}\n\npeekEngine = liftM Engine . newForeignPtr_\n{-# INLINE peekEngine #-}\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-- XXX: just a hack. We really want to be able to pass custom structs to\n-- functions. See 'xine_open_audio_driver'.\nnewtype Data = Data (Ptr Data)\n\nwithData f = f nullPtr\n\n-- | An opaque type, never dereferenced on the Haskell side\n-- XXX: document me\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n{-# INLINE peekAudioPort #-}\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-- | An opaque type, never dereferenced on the Haskell side\n-- XXX: document me\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n{-# INLINE peekVideoPort #-}\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-- | An opaque type, never dereferenced on the Haskell side\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\npeekStream = maybeForeignPtr_ Stream\n{-# INLINE peekStream #-}\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-- | 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-- | Stream format detection strategies\n{#enum define DemuxStrategy\n {XINE_DEMUX_DEFAULT_STRATEGY as DemuxDefault,\n XINE_DEMUX_REVERT_STRATEGY as DemuxRevert,\n XINE_DEMUX_CONTENT_STRATEGY as DemuxContent,\n XINE_DEMUX_EXTENSION_STRATEGY as DemuxExtension}#}\n\n-- | Verbosity setting\n{#enum define Verbosity\n {XINE_VERBOSITY_NONE as VerbosityNone,\n XINE_VERBOSITY_LOG as VerbosityLog,\n XINE_VERBOSITY_DEBUG as VerbosityDebug}#}\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-- This is a trick to read the #define'd constant XINE_LANG_MAX\n{#enum define Wrapping\n {XINE_LANG_MAX as LangMax}#}\n\ncXINE_LANG_MAX :: Int\ncXINE_LANG_MAX = fromEnum LangMax\n\n-- Helper to allocate a language buffer\nallocLangBuf = allocaArray0 cXINE_LANG_MAX\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-- | The different kinds of stream information\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-- | Possible values for InfoVideoAFD\n{#enum define AFDValue\n {XINE_VIDEO_AFD_NOT_PRESENT as AFDNotPresent,\n XINE_VIDEO_AFD_RESERVED_0 as AFDReserved0,\n XINE_VIDEO_AFD_RESERVED_1 as AFDReserved1,\n XINE_VIDEO_AFD_BOX_16_9_TOP as AFDBox169Top,\n XINE_VIDEO_AFD_BOX_14_9_TOP as AFDBox149Top,\n XINE_VIDEO_AFD_BOX_GT_16_9_CENTRE as AFDGt169Centre,\n XINE_VIDEO_AFD_RESERVED_5 as AFDReserved5,\n XINE_VIDEO_AFD_RESERVED_6 as AFDReserved6,\n XINE_VIDEO_AFD_RESERVED_7 as AFDReserved7,\n XINE_VIDEO_AFD_SAME_AS_FRAME as AFDSameAsFrame,\n XINE_VIDEO_AFD_4_3_CENTRE as AFD43Centre,\n XINE_VIDEO_AFD_16_9_CENTRE as AFD169Centre,\n XINE_VIDEO_AFD_14_9_CENTRE as AFD149Centre,\n XINE_VIDEO_AFD_RESERVED_12 as AFDReserved12,\n XINE_VIDEO_AFD_4_3_PROTECT_14_9 as AFD43Protect149,\n XINE_VIDEO_AFD_16_9_PROTECT_14_9 as AFD169Protect149,\n XINE_VIDEO_AFD_16_9_PROTECT_4_3 as AFD169Protect43}#}\n\n-- | The different kinds of metadata\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{-# OPTIONS_GHC -Wwarn #-}\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(..), DemuxStrategy(..), Verbosity(..), MRL, EngineParam(..),\n 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-- | 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-- | Stream format detection strategies\n{#enum define DemuxStrategy\n {XINE_DEMUX_DEFAULT_STRATEGY as DemuxDefault,\n XINE_DEMUX_REVERT_STRATEGY as DemuxRevert,\n XINE_DEMUX_CONTENT_STRATEGY as DemuxContent,\n XINE_DEMUX_EXTENSION_STRATEGY as DemuxExtension}#}\n\n-- | Verbosity setting\n{#enum define Verbosity\n {XINE_VERBOSITY_NONE as VerbosityNone,\n XINE_VERBOSITY_LOG as VerbosityLog,\n XINE_VERBOSITY_DEBUG as VerbosityDebug}#}\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-- This is a trick to read the #define'd constant XINE_LANG_MAX\n{#enum define Wrapping\n {XINE_LANG_MAX as LangMax}#}\n\ncXINE_LANG_MAX :: Int\ncXINE_LANG_MAX = fromEnum LangMax\n\n-- Helper to allocate a language buffer\nallocLangBuf = allocaArray0 cXINE_LANG_MAX\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-- | Possible values for InfoVideoAFD\n{#enum define AFDValue\n {XINE_VIDEO_AFD_NOT_PRESENT as AFDNotPresent,\n XINE_VIDEO_AFD_RESERVED_0 as AFDReserved0,\n XINE_VIDEO_AFD_RESERVED_1 as AFDReserved1,\n XINE_VIDEO_AFD_BOX_16_9_TOP as AFDBox169Top,\n XINE_VIDEO_AFD_BOX_14_9_TOP as AFDBox149Top,\n XINE_VIDEO_AFD_BOX_GT_16_9_CENTRE as AFDGt169Centre,\n XINE_VIDEO_AFD_RESERVED_5 as AFDReserved5,\n XINE_VIDEO_AFD_RESERVED_6 as AFDReserved6,\n XINE_VIDEO_AFD_RESERVED_7 as AFDReserved7,\n XINE_VIDEO_AFD_SAME_AS_FRAME as AFDSameAsFrame,\n XINE_VIDEO_AFD_4_3_CENTRE as AFD43Centre,\n XINE_VIDEO_AFD_16_9_CENTRE as AFD169Centre,\n XINE_VIDEO_AFD_14_9_CENTRE as AFD149Centre,\n XINE_VIDEO_AFD_RESERVED_12 as AFDReserved12,\n XINE_VIDEO_AFD_4_3_PROTECT_14_9 as AFD43Protect149,\n XINE_VIDEO_AFD_16_9_PROTECT_14_9 as AFD169Protect149,\n XINE_VIDEO_AFD_16_9_PROTECT_4_3 as AFD169Protect43}#}\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":"39d3f7a8023a24a0205c50081d52aecad691f856","subject":"Try again with nonGNU","message":"Try again with nonGNU\n","repos":"ian-ross\/c2hs-macos-test,ian-ross\/c2hs-macos-test,ian-ross\/c2hs-macos-test","old_file":"issue-82\/Issue82.chs","new_file":"issue-82\/Issue82.chs","new_contents":"module Main where\n\n{# nonGNU #}\n#include \"string.h\"\n\nmain :: IO ()\nmain = putStrLn \"OK\"\n","old_contents":"module Main where\n\n#include \"string.h\"\n\nmain :: IO ()\nmain = putStrLn \"OK\"\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"897efdfa530ffa3f0ed6619dec10f0941fa466b2","subject":"Add flChoice wrapper, without varargs.","message":"Add flChoice wrapper, without varargs.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Ask.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flChoice,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Data.Maybe (fromMaybe, maybe)\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input_with_deflt as flInput' { `CString',`CString' } -> `CString' #}\nflInput :: T.Text -> Maybe T.Text -> IO (Maybe T.Text)\nflInput msg defaultMsg = do\n msgC <- copyTextToCString msg\n let def = fromMaybe T.empty defaultMsg\n defaultC <- copyTextToCString def\n r <- flInput' msgC defaultC\n cStringToMaybeText r\n\n{# fun flc_choice as flChoice' { `CString',`CString',`CString',`CString' } -> `CInt' #}\nflChoice :: T.Text -> T.Text -> Maybe T.Text -> Maybe T.Text -> IO Int\nflChoice msg b0 b1 b2 = do\n msgC <- copyTextToCString msg\n b0C <- copyTextToCString b0\n let stringOrNull t = maybe (return nullPtr) copyTextToCString t\n b1C <- stringOrNull b1\n b2C <- stringOrNull b2\n r <- flChoice' msgC b0C b1C b2C\n return $ fromIntegral r\n\n{# fun flc_password as flPassword' { `CString' } -> `CString' #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- copyTextToCString msg >>= flPassword'\n cStringToMaybeText r\n\n{# fun flc_message as flMessage' { `CString' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage t = copyTextToCString t >>= flMessage'\n\n{# fun flc_alert as flAlert' { `CString' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert t = copyTextToCString t >>= flAlert'\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\nmodule Graphics.UI.FLTK.LowLevel.Ask\n (\n flBeep,\n BeepType(..),\n flMessage,\n flAlert,\n flInput,\n flPassword\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_AskC.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum)\n\nimport qualified Data.Text as T\nimport Data.Maybe (fromMaybe)\nimport Graphics.UI.FLTK.LowLevel.Utils\n\n#c\nenum BeepType {\n BeepDefault = FL_BEEP_DEFAULT,\n BeepMessage = FL_BEEP_MESSAGE,\n BeepError = FL_BEEP_ERROR,\n BeepQuestion = FL_BEEP_QUESTION,\n BeepPassword = FL_BEEP_PASSWORD,\n BeepNotification = FL_BEEP_NOTIFICATION\n};\n#endc\n\n{#enum BeepType {} deriving (Eq, Show, Ord) #}\n\n{# fun flc_beep as flBeep' {} -> `()' #}\n{# fun flc_beep_with_type as flBeepType' { id `CInt' } -> `()' #}\nflBeep :: Maybe BeepType -> IO ()\nflBeep Nothing = flBeep'\nflBeep (Just bt) = flBeepType' (fromIntegral (fromEnum bt))\n\n{# fun flc_input_with_deflt as flInput' { `CString',`CString' } -> `CString' #}\nflInput :: T.Text -> Maybe T.Text -> IO (Maybe T.Text)\nflInput msg defaultMsg = do\n msgC <- copyTextToCString msg\n let def = fromMaybe T.empty defaultMsg\n defaultC <- copyTextToCString def\n r <- flInput' msgC defaultC\n cStringToMaybeText r\n\n{# fun flc_password as flPassword' { `CString' } -> `CString' #}\nflPassword :: T.Text -> IO (Maybe T.Text)\nflPassword msg = do\n r <- copyTextToCString msg >>= flPassword'\n cStringToMaybeText r\n\n{# fun flc_message as flMessage' { `CString' } -> `()' #}\nflMessage :: T.Text -> IO ()\nflMessage t = copyTextToCString t >>= flMessage'\n\n{# fun flc_alert as flAlert' { `CString' } -> `()' #}\nflAlert :: T.Text -> IO ()\nflAlert t = copyTextToCString t >>= flAlert'\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"792c32e5c4ec83568e637c7d0c9208776f0cec8d","subject":"ncursesw: Add bindings for wattr_on and wattr_off","message":"ncursesw: Add bindings for wattr_on and wattr_off\n","repos":"beni55\/vimus,haasn\/vimus,haasn\/vimus,vimus\/vimus,vimus\/vimus,beni55\/vimus","old_file":"ncursesw\/src\/Misc.chs","new_file":"ncursesw\/src\/Misc.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Misc where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Foreign.Storable\nimport Foreign.ForeignPtr\n\nimport Data.Char\nimport Data.List (foldl')\nimport Foreign.Marshal.Utils (fromBool, toBool)\n\nimport Data.Bits\n\nimport qualified Constant\nimport CursesUtil\n\n{# import Type #}\n\n-- import Foreign.Storable\n\n#include \"mycurses.h\"\n\n\n\ncFromBool = fromBool\ncToBool = toBool\n\n------------------------------------------------------------------------\n-- attr\n------------------------------------------------------------------------\n\n-- | Deprecated, use Attribute instead\nnewtype Attr = Attr CInt\n\n(&) :: Attr -> Attr -> Attr\n(Attr a) & (Attr b) = Attr (a .|. b)\n\nfromAttr (Attr a) = a\n\n-- {#fun unsafe attron {fromAttr `Attr'} -> `Status' toStatus*#}\n-- {#fun unsafe attroff {fromAttr `Attr'} -> `Status' toStatus*#}\n\n\n{#enum define Attribute {\n WA_NORMAL as Normal\n, WA_STANDOUT as Standout\n, WA_UNDERLINE as Underline\n, WA_REVERSE as Reverse\n, WA_BLINK as Blink\n, WA_DIM as Dim\n, WA_BOLD as Bold\n, WA_ALTCHARSET as Altcharset\n, WA_INVIS as Invis\n, WA_PROTECT as Protect\n}#}\n-- not yet implemented by ncurses, so we do not define them\n{-\n, WA_HORIZONTAL as Horizontal\n, WA_LEFT as Left\n, WA_LOW as Low\n, WA_RIGHT as Right\n, WA_TOP as Top\n, WA_VERTICAL as Vertical\n-}\n\n\ncombine :: [Attribute] -> CULong\ncombine l = foldl' (.|.) 0 $ map (fromIntegral . fromEnum) l\n\n-- int wcolor_set(WINDOW *win, short color_pair_number, void* opts);\n--\n-- int wstandend(WINDOW *win);\n-- int wstandout(WINDOW *win);\n--\n-- int wattr_get(WINDOW *win, attr_t *attrs, short *pair, void *opts);\n\n-- int wattr_off(WINDOW *win, attr_t attrs, void *opts);\n{#fun unsafe wattr_off as wattr_off_ {id `Window', combine `[Attribute]', id `Ptr ()'} -> `Status' toStatus*#}\nwattr_off win attrs = wattr_off_ win attrs nullPtr\n\n-- int wattr_on(WINDOW *win, attr_t attrs, void *opts);\n{#fun unsafe wattr_on as wattr_on_ {id `Window', combine `[Attribute]', id `Ptr ()'} -> `Status' toStatus*#}\nwattr_on win attrs = wattr_on_ win attrs nullPtr\n\n-- int wattr_set(WINDOW *win, attr_t attrs, short pair, void *opts);\n--\n\n\n-- int wchgat(WINDOW *win, int n, attr_t attr, short color, const void *opts)\n{#fun unsafe wchgat as wchgat_ {id `Window', `Int', combine `[Attribute]', shortFromInt `Int', id `Ptr ()'} -> `Status' toStatus*#}\nwchgat win n attrs color = wchgat_ win n attrs color nullPtr\n\n-- int mvwchgat(WINDOW *win, int y, int x, int n, attr_t attr, short color, const void *opts)\n{#fun unsafe mvwchgat as mvwchgat_ {id `Window', `Int', `Int', `Int', combine `[Attribute]', shortFromInt `Int', id `Ptr ()'} -> `Status' toStatus*#}\n\nmvwchgat win y x n attrs color = mvwchgat_ win y x n attrs color nullPtr\n\n\n------------------------------------------------------------------------\n-- color(3NCURSES)\n------------------------------------------------------------------------\nnewtype Color = Color CShort\n\nfromColor :: Color -> CShort\nfromColor (Color a) = a\n\nblack, red, green, yellow, blue, magenta, cyan, white :: Color\nblack = Color Constant.black\nred = Color Constant.red\ngreen = Color Constant.green\nyellow = Color Constant.yellow\nblue = Color Constant.blue\nmagenta = Color Constant.magenta\ncyan = Color Constant.cyan\nwhite = Color Constant.white\n\n\n-- int start_color(void);\n{#fun unsafe start_color {} -> `Status' toStatus*#}\n\n-- int init_pair(short pair, short f, short b);\n{#fun unsafe init_pair {shortFromInt `Int', fromColor `Color', fromColor `Color'} -> `Status' toStatus*#}\n\n-- int init_color(short color, short r, short g, short b);\n{#fun unsafe init_color {fromColor `Color', shortFromInt `Int', shortFromInt `Int', shortFromInt `Int'} -> `Status' toStatus*#}\n\n-- bool has_colors(void);\n{#fun pure has_colors {} -> `Bool'#}\n\n-- bool can_change_color(void);\n{#fun unsafe can_change_color {} -> `Bool'#}\n\n-- int color_content(short color, short *r, short *g, short *b);\n-- int pair_content(short pair, short *f, short *b);\n\n\nshortFromInt :: Int -> CShort\nshortFromInt = fromIntegral\n\n\n#c\nint color_pair(short n);\n#endc\n{#fun pure color_pair {shortFromInt `Int'} -> `Attr' Attr#}\n\n------------------------------------------------------------------------\n-- default_colors(3NCURSES)\n------------------------------------------------------------------------\n\n-- int use_default_colors(void);\n{#fun unsafe use_default_colors {} -> `Status' toStatus*#}\n\n-- int assume_default_colors(int fg, int bg);\n{#fun unsafe assume_default_colors {fromColor' `Color', fromColor' `Color'} -> `Status' toStatus*#}\n\nfromColor' :: Color -> CInt\nfromColor' = fromIntegral . fromColor\n\n------------------------------------------------------------------------\n-- bkgd(3NCURSES)\n------------------------------------------------------------------------\n\n-- TODO: support setting of background character, not only attribute\n\n{#fun unsafe bkgdset {chtypeFromAttr `Attr'} -> `()'#}\n{#fun unsafe wbkgdset {id `Window', chtypeFromAttr `Attr'} -> `()'#}\n{#fun unsafe bkgd {chtypeFromAttr `Attr'} -> `Status' toStatus*#}\n{#fun unsafe wbkgd {id `Window', chtypeFromAttr `Attr'} -> `Status' toStatus*#}\n\n-- TODO\n-- chtype getbkgd(WINDOW *win);\n\nchtypeFromAttr :: Attr -> CULong\nchtypeFromAttr = fromIntegral . fromAttr\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Misc where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.Marshal.Alloc\nimport Foreign.Storable\nimport Foreign.ForeignPtr\n\nimport Data.Char\nimport Data.List (foldl')\nimport Foreign.Marshal.Utils (fromBool, toBool)\n\nimport Data.Bits\n\nimport qualified Constant\nimport CursesUtil\n\n{# import Type #}\n\n-- import Foreign.Storable\n\n#include \"mycurses.h\"\n\n\n\ncFromBool = fromBool\ncToBool = toBool\n\n------------------------------------------------------------------------\n-- attr\n------------------------------------------------------------------------\n\n-- | Deprecated, use Attribute instead\nnewtype Attr = Attr CInt\n\n(&) :: Attr -> Attr -> Attr\n(Attr a) & (Attr b) = Attr (a .|. b)\n\nfromAttr (Attr a) = a\n\n-- {#fun unsafe attron {fromAttr `Attr'} -> `Status' toStatus*#}\n-- {#fun unsafe attroff {fromAttr `Attr'} -> `Status' toStatus*#}\n\n\n{#enum define Attribute {\n WA_NORMAL as Normal\n, WA_STANDOUT as Standout\n, WA_UNDERLINE as Underline\n, WA_REVERSE as Reverse\n, WA_BLINK as Blink\n, WA_DIM as Dim\n, WA_BOLD as Bold\n, WA_ALTCHARSET as Altcharset\n, WA_INVIS as Invis\n, WA_PROTECT as Protect\n}#}\n-- not yet implemented by ncurses, so we do not define them\n{-\n, WA_HORIZONTAL as Horizontal\n, WA_LEFT as Left\n, WA_LOW as Low\n, WA_RIGHT as Right\n, WA_TOP as Top\n, WA_VERTICAL as Vertical\n-}\n\n\ncombine :: [Attribute] -> CULong\ncombine l = foldl' (.|.) 0 $ map (fromIntegral . fromEnum) l\n\n-- int wcolor_set(WINDOW *win, short color_pair_number, void* opts);\n--\n-- int wstandend(WINDOW *win);\n-- int wstandout(WINDOW *win);\n--\n-- int wattr_get(WINDOW *win, attr_t *attrs, short *pair, void *opts);\n-- int wattr_off(WINDOW *win, attr_t attrs, void *opts);\n-- int wattr_on(WINDOW *win, attr_t attrs, void *opts);\n-- int wattr_set(WINDOW *win, attr_t attrs, short pair, void *opts);\n--\n\n\n-- int wchgat(WINDOW *win, int n, attr_t attr, short color, const void *opts)\n{#fun unsafe wchgat as wchgat_ {id `Window', `Int', combine `[Attribute]', shortFromInt `Int', id `Ptr ()'} -> `Status' toStatus*#}\nwchgat win n attrs color = wchgat_ win n attrs color nullPtr\n\n-- int mvwchgat(WINDOW *win, int y, int x, int n, attr_t attr, short color, const void *opts)\n{#fun unsafe mvwchgat as mvwchgat_ {id `Window', `Int', `Int', `Int', combine `[Attribute]', shortFromInt `Int', id `Ptr ()'} -> `Status' toStatus*#}\n\nmvwchgat win y x n attrs color = mvwchgat_ win y x n attrs color nullPtr\n\n\n------------------------------------------------------------------------\n-- color(3NCURSES)\n------------------------------------------------------------------------\nnewtype Color = Color CShort\n\nfromColor :: Color -> CShort\nfromColor (Color a) = a\n\nblack, red, green, yellow, blue, magenta, cyan, white :: Color\nblack = Color Constant.black\nred = Color Constant.red\ngreen = Color Constant.green\nyellow = Color Constant.yellow\nblue = Color Constant.blue\nmagenta = Color Constant.magenta\ncyan = Color Constant.cyan\nwhite = Color Constant.white\n\n\n-- int start_color(void);\n{#fun unsafe start_color {} -> `Status' toStatus*#}\n\n-- int init_pair(short pair, short f, short b);\n{#fun unsafe init_pair {shortFromInt `Int', fromColor `Color', fromColor `Color'} -> `Status' toStatus*#}\n\n-- int init_color(short color, short r, short g, short b);\n{#fun unsafe init_color {fromColor `Color', shortFromInt `Int', shortFromInt `Int', shortFromInt `Int'} -> `Status' toStatus*#}\n\n-- bool has_colors(void);\n{#fun pure has_colors {} -> `Bool'#}\n\n-- bool can_change_color(void);\n{#fun unsafe can_change_color {} -> `Bool'#}\n\n-- int color_content(short color, short *r, short *g, short *b);\n-- int pair_content(short pair, short *f, short *b);\n\n\nshortFromInt :: Int -> CShort\nshortFromInt = fromIntegral\n\n\n#c\nint color_pair(short n);\n#endc\n{#fun pure color_pair {shortFromInt `Int'} -> `Attr' Attr#}\n\n------------------------------------------------------------------------\n-- default_colors(3NCURSES)\n------------------------------------------------------------------------\n\n-- int use_default_colors(void);\n{#fun unsafe use_default_colors {} -> `Status' toStatus*#}\n\n-- int assume_default_colors(int fg, int bg);\n{#fun unsafe assume_default_colors {fromColor' `Color', fromColor' `Color'} -> `Status' toStatus*#}\n\nfromColor' :: Color -> CInt\nfromColor' = fromIntegral . fromColor\n\n------------------------------------------------------------------------\n-- bkgd(3NCURSES)\n------------------------------------------------------------------------\n\n-- TODO: support setting of background character, not only attribute\n\n{#fun unsafe bkgdset {chtypeFromAttr `Attr'} -> `()'#}\n{#fun unsafe wbkgdset {id `Window', chtypeFromAttr `Attr'} -> `()'#}\n{#fun unsafe bkgd {chtypeFromAttr `Attr'} -> `Status' toStatus*#}\n{#fun unsafe wbkgd {id `Window', chtypeFromAttr `Attr'} -> `Status' toStatus*#}\n\n-- TODO\n-- chtype getbkgd(WINDOW *win);\n\nchtypeFromAttr :: Attr -> CULong\nchtypeFromAttr = fromIntegral . fromAttr\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"95d5f6f8c38bbe34d371356ce670714e11204ed7","subject":"Add function set pixel value on an mutable image.","message":"Add function set pixel value on an mutable image.\n","repos":"BeautifulDestinations\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"","old_contents":"","returncode":0,"stderr":"unknown","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"9455221e5b455385ee269eed91618f5ae107a50e","subject":"Add sourceBufferUndoManager attribute","message":"Add sourceBufferUndoManager attribute\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Description\n-- | The 'SourceBuffer' object is the model for 'SourceView' widgets. It extends the 'TextBuffer'\n-- object by adding features useful to display and edit source code as syntax highlighting and bracket\n-- matching. It also implements support for undo\/redo operations.\n-- \n-- To create a 'SourceBuffer' use 'sourceBufferNew' or\n-- 'sourceBufferNewWithLanguage'. The second form is just a convenience function which allows\n-- you to initially set a 'SourceLanguage'.\n-- \n-- By default highlighting is enabled, but you can disable it with\n-- 'sourceBufferSetHighlightSyntax'.\n\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n sourceBufferUndoManager,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} \n (toSourceBuffer sb) \n (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} \n (toSourceBuffer sb)\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBufferClass buffer => buffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n (toSourceBuffer sb) \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} (toSourceBuffer sb)\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} (toSourceBuffer sb) (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} (toSourceBuffer sb)\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBufferClass buffer => buffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n (toSourceBuffer sb) \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} (toSourceBuffer sb)\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} (toSourceBuffer sb) (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} (toSourceBuffer sb)\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} (toSourceBuffer sb)\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} (toSourceBuffer sb)\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} (toSourceBuffer sb)\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} (toSourceBuffer sb)\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} (toSourceBuffer sb)\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} (toSourceBuffer sb)\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBufferClass buffer => buffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} (toSourceBuffer sb) strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n (toSourceBuffer buffer) \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n (toSourceBuffer buffer)\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBufferClass buffer => buffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} (toSourceBuffer sb) start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: SourceBufferClass buffer => Attr buffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: SourceBufferClass buffer => Attr buffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: SourceBufferClass buffer => Attr buffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- | The buffer undo manager.\nsourceBufferUndoManager :: SourceBufferClass buffer => Attr buffer SourceUndoManager\nsourceBufferUndoManager = newAttrFromObjectProperty \"undo-manager\"\n {# call pure unsafe gtk_source_undo_manager_get_type #}\n\n-- |\n--\nsourceBufferHighlightUpdated :: SourceBufferClass buffer => Signal buffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: SourceBufferClass buffer => Signal buffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n-- * Description\n-- | The 'SourceBuffer' object is the model for 'SourceView' widgets. It extends the 'TextBuffer'\n-- object by adding features useful to display and edit source code as syntax highlighting and bracket\n-- matching. It also implements support for undo\/redo operations.\n-- \n-- To create a 'SourceBuffer' use 'sourceBufferNew' or\n-- 'sourceBufferNewWithLanguage'. The second form is just a convenience function which allows\n-- you to initially set a 'SourceLanguage'.\n-- \n-- By default highlighting is enabled, but you can disable it with\n-- 'sourceBufferSetHighlightSyntax'.\n\n-- * Types\n SourceBuffer,\n SourceBufferClass,\n\n-- * Methods\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferGetSourceMarksAtLine,\n sourceBufferGetSourceMarksAtIter,\n sourceBufferRemoveSourceMarks,\n sourceBufferForwardIterToSourceMark,\n sourceBufferBackwardIterToSourceMark,\n sourceBufferEnsureHighlight,\n\n-- * Attributes\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferMaxUndoLevels,\n\n-- * Signals\n sourceBufferHighlightUpdated,\n sourceBufferRedoSignal,\n sourceBufferUndoSignal,\n sourceBufferSourceMarkUpdated,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GList\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.Signals#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\n{#import Graphics.UI.Gtk.SourceView.SourceMark#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (TextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | Controls whether syntax is highlighted in the buffer. If highlight is 'True', the text will be\n-- highlighted according to the syntax patterns specified in the language set with\n-- 'sourceBufferSetLanguage'. If highlight is 'False', syntax highlighting is disabled and all the\n-- 'TextTag' objects that have been added by the syntax highlighting engine are removed from the\n-- buffer.\nsourceBufferSetHighlightSyntax :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Bool -- ^ @highlight@ 'True' to enable syntax highlighting, 'False' to disable it. \n -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} \n (toSourceBuffer sb) \n (fromBool newVal)\n \n-- | Determines whether syntax highlighting is activated in the source buffer.\nsourceBufferGetHighlightSyntax :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if syntax highlighting is enabled, 'False' otherwise. \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} \n (toSourceBuffer sb)\n\n-- | Associate a 'SourceLanguage' with the source buffer. If language is not-'Nothing' and syntax\n-- highlighting is enabled (see 'sourceBufferSetHighlightSyntax', the syntax patterns defined\n-- in language will be used to highlight the text contained in the buffer. If language is 'Nothing', the\n-- text contained in the buffer is not highlighted.\nsourceBufferSetLanguage :: SourceBufferClass buffer => buffer \n -> Maybe SourceLanguage -- ^ @language@ a 'SourceLanguage' to set, or 'Nothing'. \n -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} \n (toSourceBuffer sb) \n (fromMaybe (SourceLanguage nullForeignPtr) lang)\n \n-- | Returns the 'SourceLanguage' associated with the buffer, see 'sourceBufferSetLanguage'. \nsourceBufferGetLanguage :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceLanguage) -- ^ returns 'SourceLanguage' associated with the buffer, or 'Nothing'. \nsourceBufferGetLanguage sb = \n maybeNull (makeNewGObject mkSourceLanguage) $\n {#call unsafe source_buffer_get_language#} (toSourceBuffer sb)\n\n-- | Controls the bracket match highlighting function in the buffer. If activated, when you position your\n-- cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or\n-- closing bracket character will be highlighted. You can specify the style with the\n-- 'sourceBufferSetBracketMatchStyle' function.\nsourceBufferSetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> Bool -- ^ @highlight@ 'True' if you want matching brackets highlighted. \n -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} (toSourceBuffer sb) (fromBool newVal)\n \n-- | Determines whether bracket match highlighting is activated for the source buffer.\nsourceBufferGetHighlightMatchingBrackets :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if the source buffer will highlight matching brackets. \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} (toSourceBuffer sb)\n\n-- | Sets style scheme used by the buffer. If scheme is 'Nothing' no style scheme is used.\nsourceBufferSetStyleScheme :: SourceBufferClass buffer => buffer \n -> Maybe SourceStyleScheme -- ^ @scheme@ style scheme. \n -> IO ()\nsourceBufferSetStyleScheme sb scheme =\n {#call unsafe source_buffer_set_style_scheme#} \n (toSourceBuffer sb) \n (fromMaybe (SourceStyleScheme nullForeignPtr) scheme)\n\n-- | Returns the 'SourceStyleScheme' currently used in buffer.\nsourceBufferGetStyleScheme :: SourceBufferClass buffer => buffer \n -> IO (Maybe SourceStyleScheme) -- ^ returns the 'SourceStyleScheme' set by 'sourceBufferSetStyleScheme', or 'Nothing'.\nsourceBufferGetStyleScheme sb = \n maybeNull (makeNewGObject mkSourceStyleScheme) $\n {#call unsafe source_buffer_get_style_scheme#} (toSourceBuffer sb)\n\n-- | Sets the number of undo levels for user actions the buffer will track. If the number of user actions\n-- exceeds the limit set by this function, older actions will be discarded.\n-- \n-- If @maxUndoLevels@ is -1, no limit is set.\n-- \n-- A new action is started whenever the function 'textBufferBeginUserAction' is called. In\n-- general, this happens whenever the user presses any key which modifies the buffer, but the undo\n-- manager will try to merge similar consecutive actions, such as multiple character insertions into\n-- one action. But, inserting a newline does start a new action.\nsourceBufferSetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> Int -- ^ @maxUndoLevels@ the desired maximum number of undo levels. \n -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} (toSourceBuffer sb) (fromIntegral newVal)\n \n-- | Determines the number of undo levels the buffer will track for buffer edits.\nsourceBufferGetMaxUndoLevels :: SourceBufferClass buffer => buffer \n -> IO Int -- ^ returns the maximum number of possible undo levels or -1 if no limit is set.\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} (toSourceBuffer sb)\n\n-- | Determines whether a source buffer can undo the last action.\nsourceBufferGetCanUndo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if it's possible to undo the last action. \nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} (toSourceBuffer sb)\n \n-- | Determines whether a source buffer can redo the last action (i.e. if the last operation was an\n-- undo).\nsourceBufferGetCanRedo :: SourceBufferClass buffer => buffer \n -> IO Bool -- ^ returns 'True' if a redo is possible. \nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} (toSourceBuffer sb)\n\n-- | Undoes the last user action which modified the buffer. Use 'sourceBufferCanUndo' to check\n-- whether a call to this function will have any effect.\n-- \n-- Actions are defined as groups of operations between a call to 'textBufferBeginUserAction'\n-- and 'textBufferEndUserAction' on the\n-- same line.\nsourceBufferUndo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} (toSourceBuffer sb)\n \n-- | Redoes the last undo operation. Use 'sourceBufferCanRedo' to check whether a call to this\n-- function will have any effect.\nsourceBufferRedo :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} (toSourceBuffer sb)\n\n-- | Marks the beginning of a not undoable action on the buffer, disabling the undo manager. Typically\n-- you would call this function before initially setting the contents of the buffer (e.g. when loading\n-- a file in a text editor).\n-- \n-- You may nest 'sourceBufferBeginNotUndoableAction' \/\n-- 'sourceBufferEndNotUndoableAction' blocks.\nsourceBufferBeginNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} (toSourceBuffer sb)\n \n-- | Marks the end of a not undoable action on the buffer. When the last not undoable block is closed\n-- through the call to this function, the list of undo actions is cleared and the undo manager is\n-- re-enabled.\nsourceBufferEndNotUndoableAction :: SourceBufferClass buffer => buffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} (toSourceBuffer sb)\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBufferClass buffer => buffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} (toSourceBuffer sb) strPtr1 strPtr2 iter\n\n-- | Returns the list of marks of the given category at line. If category is empty, all marks at line are\n-- returned.\nsourceBufferGetSourceMarksAtLine :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> Int -- ^ @line@ a line number. \n -> String -- ^ @category@ category to search for or empty \n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtLine buffer line category = \n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_line #}\n (toSourceBuffer buffer) \n (fromIntegral line)\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Returns the list of marks of the given category at iter. If category is empty it returns all marks at\n-- iter.\nsourceBufferGetSourceMarksAtIter :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or empty\n -> IO [SourceMark]\nsourceBufferGetSourceMarksAtIter buffer iter category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_get_source_marks_at_iter #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n >>= readGSList\n >>= mapM (\\markPtr -> makeNewGObject mkSourceMark (return markPtr))\n\n-- | Remove all marks of category between start and end from the buffer. If category is empty, all marks\n-- in the range will be removed.\nsourceBufferRemoveSourceMarks :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @start@ a 'TextIter' \n -> TextIter -- ^ @end@ a 'TextIter' \n -> String -- ^ @category@ category to search for or empty\n -> IO ()\nsourceBufferRemoveSourceMarks buffer start end category =\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_remove_source_marks #}\n (toSourceBuffer buffer)\n start\n end\n categoryPtr\n\n-- | Moves iter to the position of the next 'SourceMark' of the given category. Returns 'True' if iter was\n-- moved. If category is empty, the next source mark can be of any category.\nsourceBufferForwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferForwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_forward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Moves iter to the position of the previous 'SourceMark' of the given category. Returns 'True' if iter\n-- was moved. If category is empty, the previous source mark can be of any category.\nsourceBufferBackwardIterToSourceMark :: SourceBufferClass buffer => buffer -- ^ @buffer@ a 'SourceBuffer'. \n -> TextIter -- ^ @iter@ an iterator. \n -> String -- ^ @category@ category to search for or emtpy\n -> IO Bool -- ^ returns whether iter moved. \nsourceBufferBackwardIterToSourceMark buffer iter category =\n liftM toBool $\n withCString category $ \\categoryPtr ->\n {#call gtk_source_buffer_backward_iter_to_source_mark #}\n (toSourceBuffer buffer)\n iter\n categoryPtr\n\n-- | Forces buffer to analyze and highlight the given area synchronously.\n-- \n-- Note\n-- \n-- This is a potentially slow operation and should be used only when you need to make sure that some\n-- text not currently visible is highlighted, for instance before printing.\nsourceBufferEnsureHighlight :: SourceBufferClass buffer => buffer \n -> TextIter -- ^ @start@ start of the area to highlight. \n -> TextIter -- ^ @end@ end of the area to highlight. \n -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} (toSourceBuffer sb) start end\n\n-- | Whether Redo operation is possible.\n-- \n-- Default value: 'False'\n-- \nsourceBufferCanRedo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- | Whether Undo operation is possible.\n-- \n-- Default value: 'False'\nsourceBufferCanUndo :: SourceBufferClass buffer => ReadAttr buffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- | Whether to highlight matching brackets in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightMatchingBrackets :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Whether to highlight syntax in the buffer.\n-- \n-- Default value: 'True'\n--\nsourceBufferHighlightSyntax :: SourceBufferClass buffer => Attr buffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- | Language object to get highlighting patterns from.\n-- \nsourceBufferLanguage :: SourceBufferClass buffer => Attr buffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- | Number of undo levels for the buffer. -1 means no limit. This property will only affect the default\n-- undo manager.\n-- \n-- Allowed values: >= GMaxulong\n-- \n-- Default value: 1000\n--\nsourceBufferMaxUndoLevels :: SourceBufferClass buffer => Attr buffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- | Style scheme. It contains styles for syntax highlighting, optionally foreground, background, cursor\n-- color, current line color, and matching brackets style.\n-- \nsourceBufferSourceStyleScheme :: SourceBufferClass buffer => Attr buffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: SourceBufferClass buffer => Signal buffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n\n-- |\n--\nsourceBufferRedoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferRedoSignal = Signal $ connect_NONE__NONE \"redo\"\n\n-- |\n--\nsourceBufferUndoSignal :: SourceBufferClass buffer => Signal buffer (IO ())\nsourceBufferUndoSignal = Signal $ connect_NONE__NONE \"undo\"\n\n-- | The 'sourceBufferMarkUpdated' signal is emitted each time a mark is added to, moved or removed from the\n-- buffer.\n--\nsourceBufferSourceMarkUpdated :: SourceBufferClass buffer => Signal buffer (TextMark -> IO ())\nsourceBufferSourceMarkUpdated = Signal $ connect_OBJECT__NONE \"source-mark-updated\" \n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"8fdc6d59b4e329c9ee9d22e64f30c593ca51cc31","subject":"Fix IconTheme to only compile if gio is present.","message":"Fix IconTheme to only compile if gio is present.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/IconTheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items, such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0) && HAVE_GIO\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0) && HAVE_GIO\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget IconTheme\n--\n-- Author : Andy Stewart\n--\n-- Created: 28 Mar 2010\n--\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-- Looking up icons by name\n--\n-- * Module available since Gtk+ version 2.4\n--\nmodule Graphics.UI.Gtk.General.IconTheme (\n\n-- * Detail\n--\n-- | 'IconTheme' provides a facility for looking up icons by name and size. The main reason for using a\n-- name rather than simply providing a filename is to allow different icons to be used depending on\n-- what icon theme is selecetd by the user. The operation of icon themes on Linux and Unix follows the\n-- Icon Theme Specification. There is a default icon theme, named hicolor where applications should\n-- install their icons, but more additional application themes can be installed as operating system\n-- vendors and users choose.\n-- \n-- Named icons are similar to the Themeable Stock Images(3) facility, and the distinction between the\n-- two may be a bit confusing. A few things to keep in mind:\n-- \n-- \u25cf Stock images usually are used in conjunction with Stock Items(3)., such as ''StockOk'' or\n-- ''StockOpen''. Named icons are easier to set up and therefore are more useful for new icons\n-- that an application wants to add, such as application icons or window icons.\n-- \n-- \u25cf Stock images can only be loaded at the symbolic sizes defined by the 'IconSize' enumeration, or\n-- by custom sizes defined by 'iconSizeRegister', while named icons are more flexible and any\n-- pixel size can be specified.\n-- \n-- \u25cf Because stock images are closely tied to stock items, and thus to actions in the user interface,\n-- stock images may come in multiple variants for different widget states or writing directions.\n-- \n-- A good rule of thumb is that if there is a stock image for what you want to use, use it, otherwise\n-- use a named icon. It turns out that internally stock images are generally defined in terms of one or\n-- more named icons. (An example of the more than one case is icons that depend on writing direction;\n-- ''StockGoForward'' uses the two themed icons 'gtkStockGoForwardLtr' and\n-- 'gtkStockGoForwardRtl'.)\n-- \n-- In many cases, named themes are used indirectly, via 'Image' or stock items, rather than directly,\n-- but looking up icons directly is also simple. The 'IconTheme' object acts as a database of all the\n-- icons in the current theme. You can create new 'IconTheme' objects, but its much more efficient to\n-- use the standard icon theme for the 'Screen' so that the icon information is shared with other\n-- people looking up icons. In the case where the default screen is being used, looking up an icon can\n-- be as simple as:\n--\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----IconTheme\n-- @\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- * Types\n IconTheme,\n IconThemeClass,\n castToIconTheme,\n toIconTheme,\n\n IconInfo,\n\n-- * Enums\n IconLookupFlags(..),\n IconThemeError(..),\n\n-- * Constructors\n iconThemeNew,\n\n#if GTK_CHECK_VERSION(2,14,0)\n iconInfoNewForPixbuf,\n#endif\n\n-- * Methods\n iconThemeGetDefault,\n iconThemeGetForScreen,\n iconThemeSetScreen,\n iconThemeSetSearchPath,\n iconThemeGetSearchPath,\n iconThemeAppendSearchPath,\n iconThemePrependSearchPath,\n iconThemeSetCustomTheme,\n iconThemeHasIcon,\n iconThemeLookupIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeChooseIcon,\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n iconThemeLookupByGicon,\n#endif\n#endif\n#endif\n iconThemeLoadIcon,\n#if GTK_CHECK_VERSION(2,12,0)\n iconThemeListContexts,\n#endif\n iconThemeListIcons,\n#if GTK_CHECK_VERSION(2,6,0)\n iconThemeGetIconSizes,\n#endif\n iconThemeGetExampleIconName,\n iconThemeRescanIfNeeded,\n iconThemeAddBuiltinIcon,\n iconThemeErrorQuark,\n\n iconInfoCopy,\n iconInfoGetAttachPoints,\n iconInfoGetBaseSize,\n iconInfoGetBuiltinPixbuf,\n iconInfoGetDisplayName,\n iconInfoGetEmbeddedRect,\n iconInfoGetFilename,\n iconInfoLoadIcon,\n iconInfoSetRawCoordinates,\n\n-- * Signals\n iconThemeChanged,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject, Quark)\nimport System.Glib.GError (GErrorDomain, GErrorClass(..), propagateGError)\nimport Graphics.UI.Gtk.General.Structs (Rectangle, Point)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n#ifdef ENABLE_GIO\n{#import System.GIO.Types#}\n#endif\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n#if GTK_CHECK_VERSION(2,4,0)\n--------------------\n-- Enums\n{#enum IconLookupFlags {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n{#enum IconThemeError {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n--------------------\n-- Constructors\n\n-- | Creates a new icon theme object. Icon theme objects are used to lookup up\n-- an icon by name in a particular icon theme. Usually, you'll want to use\n-- 'iconThemeGetDefault' or 'iconThemeGetForScreen' rather than creating a new\n-- icon theme object for scratch.\n--\niconThemeNew :: IO IconTheme\niconThemeNew =\n constructNewGObject mkIconTheme $\n {# call gtk_icon_theme_new #}\n\n--------------------\n-- Methods\n\n-- | Gets the icon theme for the default screen. See 'iconThemeGetForScreen'.\n--\niconThemeGetDefault ::\n IO IconTheme -- ^ returns A unique 'IconTheme' associated with the default\n -- screen. This icon theme is associated with the screen and\n -- can be used as long as the screen is open. \niconThemeGetDefault =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_default #}\n\n-- | Gets the icon theme object associated with @screen@; if this function has\n-- not previously been called for the given screen, a new icon theme object\n-- will be created and associated with the screen. Icon theme objects are\n-- fairly expensive to create, so using this function is usually a better\n-- choice than calling than 'iconThemeNew' and setting the screen yourself; by\n-- using this function a single icon theme object will be shared between users.\n--\niconThemeGetForScreen ::\n Screen -- ^ @screen@ - a 'Screen'\n -> IO IconTheme -- ^ returns A unique 'IconTheme' associated with the given\n -- screen. \niconThemeGetForScreen screen =\n makeNewGObject mkIconTheme $\n {# call gtk_icon_theme_get_for_screen #}\n screen\n\n-- | Sets the screen for an icon theme; the screen is used to track the user's\n-- currently configured icon theme, which might be different for different\n-- screens.\n--\niconThemeSetScreen :: IconThemeClass self => self\n -> Screen -- ^ @screen@ - a 'Screen'\n -> IO ()\niconThemeSetScreen self screen =\n {# call gtk_icon_theme_set_screen #}\n (toIconTheme self)\n screen\n\n-- | Sets the search path for the icon theme object. When looking for an icon\n-- theme, Gtk+ will search for a subdirectory of one or more of the directories\n-- in @path@ with the same name as the icon theme. (Themes from multiple of the\n-- path elements are combined to allow themes to be extended by adding icons in\n-- the user's home directory.)\n--\n-- In addition if an icon found isn't found either in the current icon theme\n-- or the default icon theme, and an image file with the right name is found\n-- directly in one of the elements of @path@, then that image will be used for\n-- the icon name. (This is legacy feature, and new icons should be put into the\n-- default icon theme, which is called DEFAULT_THEME_NAME, rather than directly\n-- on the icon path.)\n--\niconThemeSetSearchPath :: IconThemeClass self => self\n -> [FilePath] -- ^ @path@ - list of directories that are searched for icon\n -- themes\n -> Int -- ^ @nElements@ - number of elements in @path@.\n -> IO ()\niconThemeSetSearchPath self path nElements =\n withUTFStringArray path $ \\pathPtr ->\n {# call gtk_icon_theme_set_search_path #}\n (toIconTheme self)\n pathPtr\n (fromIntegral nElements)\n\n-- | Gets the current search path. See 'iconThemeSetSearchPath'.\n--\niconThemeGetSearchPath :: IconThemeClass self => self\n -> IO ([FilePath], Int) -- ^ @(path, nElements)@ \n -- @path@ - location to store a list of icon theme path\n -- directories. \niconThemeGetSearchPath self =\n alloca $ \\nElementsPtr -> \n allocaArray 0 $ \\pathPtr -> do\n {# call gtk_icon_theme_get_search_path #}\n (toIconTheme self)\n (castPtr pathPtr)\n nElementsPtr\n pathStr <- readUTFStringArray0 pathPtr\n nElements <- peek nElementsPtr\n return (pathStr, fromIntegral nElements)\n\n-- | Appends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemeAppendSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to append to the icon path\n -> IO ()\niconThemeAppendSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_append_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Prepends a directory to the search path. See 'iconThemeSetSearchPath'.\n--\niconThemePrependSearchPath :: IconThemeClass self => self\n -> FilePath -- ^ @path@ - directory name to prepend to the icon path\n -> IO ()\niconThemePrependSearchPath self path =\n withUTFString path $ \\pathPtr ->\n {# call gtk_icon_theme_prepend_search_path #}\n (toIconTheme self)\n pathPtr\n\n-- | Sets the name of the icon theme that the 'IconTheme' object uses\n-- overriding system configuration. This function cannot be called on the icon\n-- theme objects returned from 'iconThemeGetDefault' and\n-- 'iconThemeGetForScreen'.\n--\niconThemeSetCustomTheme :: IconThemeClass self => self\n -> (Maybe String) -- ^ @themeName@ name of icon theme to use instead of configured theme, or 'Nothing' to unset a previously set custom theme\n -> IO ()\niconThemeSetCustomTheme self themeName =\n maybeWith withUTFString themeName $ \\themeNamePtr ->\n {# call gtk_icon_theme_set_custom_theme #}\n (toIconTheme self)\n themeNamePtr\n\n-- | Checks whether an icon theme includes an icon for a particular name.\n--\niconThemeHasIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO Bool -- ^ returns @True@ if @iconTheme@ includes an icon for\n -- @iconName@.\niconThemeHasIcon self iconName =\n liftM toBool $\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_has_icon #}\n (toIconTheme self)\n iconNamePtr\n\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\niconThemeLookupIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupIcon self iconName size flags =\n withUTFString iconName $ \\iconNamePtr -> do\n iiPtr <- {# call gtk_icon_theme_lookup_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Looks up a named icon and returns a structure containing information such\n-- as the filename of the icon. The icon can then be rendered into a pixbuf\n-- using 'iconInfoLoadIcon'. ('iconThemeLoadIcon' combines these two steps if\n-- all you need is the pixbuf.)\n--\n-- If @iconNames@ contains more than one name, this function tries them all\n-- in the given order before falling back to inherited icon themes.\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeChooseIcon :: IconThemeClass self => self\n -> [String] -- ^ @iconNames@ terminated list of icon names to lookup\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeChooseIcon self iconNames size flags =\n withUTFStringArray0 iconNames $ \\iconNamesPtr -> do\n iiPtr <- {# call gtk_icon_theme_choose_icon #}\n (toIconTheme self)\n iconNamesPtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n\n#ifdef ENABLE_GIO\n#if GTK_CHECK_VERSION(2,14,0)\n-- | Looks up an icon and returns a structure containing information such as\n-- the filename of the icon. The icon can then be rendered into a pixbuf using\n-- 'iconInfoLoadIcon'.\n--\n-- * Available since Gtk+ version 2.14\n--\niconThemeLookupByGicon :: (IconThemeClass self, IconClass icon) => self\n -> icon -- ^ @icon@ - the 'Icon' to look up\n -> Int -- ^ @size@ - desired icon size\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the\n -- icon lookup\n -> IO (Maybe IconInfo) -- ^ returns a 'IconInfo'\n -- structure containing information about the icon, or\n -- 'Nothing' if the icon wasn't found. \niconThemeLookupByGicon self icon size flags = do\n iiPtr <- {# call gtk_icon_theme_lookup_by_gicon #}\n (toIconTheme self)\n (toIcon icon)\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n if iiPtr == nullPtr \n then return Nothing\n else liftM Just (mkIconInfo (castPtr iiPtr))\n#endif\n#endif\n#endif\n\n-- | Looks up an icon in an icon theme, scales it to the given size and\n-- renders it into a pixbuf. This is a convenience function; if more details\n-- about the icon are needed, use 'iconThemeLookupIcon' followed by\n-- 'iconInfoLoadIcon'.\n--\n-- Note that you probably want to listen for icon theme changes and update\n-- the icon. This is usually done by connecting to the 'Widget'::style-set\n-- signal. If for some reason you do not want to update the icon when the icon\n-- theme changes, you should consider using 'pixbufCopy' to make a private copy\n-- of the pixbuf returned by this function. Otherwise Gtk+ may need to keep the\n-- old icon theme loaded, which would be a waste of memory.\n--\niconThemeLoadIcon :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of the icon to lookup\n -> Int -- ^ @size@ - the desired icon size. The resulting icon\n -- may not be exactly this size; see 'iconInfoLoadIcon'.\n -> IconLookupFlags -- ^ @flags@ - flags modifying the behavior of the icon\n -- lookup\n -> IO (Maybe Pixbuf) -- ^ returns the rendered icon; this may be a newly\n -- created icon or a new reference to an internal icon,\n -- so you must not modify the icon. \n -- `Nothing` if the icon isn't found.\niconThemeLoadIcon self iconName size flags =\n maybeNull (makeNewGObject mkPixbuf) $\n propagateGError $ \\errorPtr ->\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_load_icon #}\n (toIconTheme self)\n iconNamePtr\n (fromIntegral size)\n ((fromIntegral . fromEnum) flags)\n errorPtr\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Gets the list of contexts available within the current hierarchy of icon\n-- themes\n--\n-- * Available since Gtk+ version 2.12\n--\niconThemeListContexts :: IconThemeClass self => self\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the contexts in the\n -- theme. \niconThemeListContexts self = do\n glistPtr <- {# call gtk_icon_theme_list_contexts #} (toIconTheme self)\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free #} (castPtr glistPtr)\n return result\n#endif\n\n-- | Lists the icons in the current icon theme. Only a subset of the icons can\n-- be listed by providing a context string. The set of values for the context\n-- string is system dependent, but will typically include such values as\n-- \\\"Applications\\\" and \\\"MimeTypes\\\".\n--\niconThemeListIcons :: IconThemeClass self => self\n -> (Maybe String) -- ^ @context@ a string identifying a particular type of icon, or 'Nothing' to list all icons.\n -> IO [String] -- ^ returns a String list\n -- holding the names of all the icons in the theme.\niconThemeListIcons self context =\n maybeWith withUTFString context $ \\contextPtr -> do\n glistPtr <- {# call gtk_icon_theme_list_icons #}\n (toIconTheme self)\n contextPtr\n list <- fromGList glistPtr\n result <- mapM readUTFString list \n {#call unsafe g_list_free#} (castPtr glistPtr)\n return result\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns an list of integers describing the sizes at which the icon is\n-- available without scaling. A size of -1 means that the icon is available in\n-- a scalable format. The list is zero-terminated.\n--\n-- * Available since Gtk+ version 2.6\n--\niconThemeGetIconSizes :: IconThemeClass self => self\n -> String -- ^ @iconName@ - the name of an icon\n -> IO [Int] -- ^ returns An newly allocated list describing the sizes at\n -- which the icon is available. \niconThemeGetIconSizes self iconName =\n withUTFString iconName $ \\iconNamePtr -> do\n listPtr <- {# call gtk_icon_theme_get_icon_sizes #}\n (toIconTheme self)\n iconNamePtr\n list <- peekArray 0 listPtr\n {#call unsafe g_free #} (castPtr listPtr)\n return (map fromIntegral list)\n#endif\n\n-- | Gets the name of an icon that is representative of the current theme (for\n-- instance, to use when presenting a list of themes to the user.)\n--\niconThemeGetExampleIconName :: IconThemeClass self => self\n -> IO (Maybe String) -- ^ returns the name of an example icon or `Nothing'\niconThemeGetExampleIconName self = do\n namePtr <- {# call gtk_icon_theme_get_example_icon_name #} (toIconTheme self)\n if namePtr == nullPtr\n then return Nothing\n else liftM Just $ readUTFString namePtr\n\n-- | Checks to see if the icon theme has changed; if it has, any currently\n-- cached information is discarded and will be reloaded next time @iconTheme@\n-- is accessed.\n--\niconThemeRescanIfNeeded :: IconThemeClass self => self\n -> IO Bool -- ^ returns @True@ if the icon theme has changed and needed to be\n -- reloaded.\niconThemeRescanIfNeeded self =\n liftM toBool $\n {# call gtk_icon_theme_rescan_if_needed #}\n (toIconTheme self)\n\n-- | Registers a built-in icon for icon theme lookups. The idea of built-in\n-- icons is to allow an application or library that uses themed icons to\n-- function requiring files to be present in the file system. For instance, the\n-- default images for all of Gtk+'s stock icons are registered as built-icons.\n--\n-- In general, if you use 'iconThemeAddBuiltinIcon' you should also install\n-- the icon in the icon theme, so that the icon is generally available.\n--\n-- This function will generally be used with pixbufs loaded via\n-- 'pixbufNewFromInline'.\n--\niconThemeAddBuiltinIcon ::\n String -- ^ @iconName@ - the name of the icon to register\n -> Int -- ^ @size@ - the size at which to register the icon (different\n -- images can be registered for the same icon name at different\n -- sizes.)\n -> Pixbuf -- ^ @pixbuf@ - 'Pixbuf' that contains the image to use for\n -- @iconName@.\n -> IO ()\niconThemeAddBuiltinIcon iconName size pixbuf =\n withUTFString iconName $ \\iconNamePtr ->\n {# call gtk_icon_theme_add_builtin_icon #}\n iconNamePtr\n (fromIntegral size)\n pixbuf\n\n-- |\n--\niconThemeErrorQuark :: IO Quark\niconThemeErrorQuark =\n {# call gtk_icon_theme_error_quark #}\n\n--------------------\n-- Types\n{#pointer *IconInfo foreign newtype#}\n\nforeign import ccall unsafe \">k_icon_info_free\"\n icon_info_free :: FinalizerPtr IconInfo\n\n-- | Helper function for build 'IconInfo'\nmkIconInfo :: Ptr IconInfo -> IO IconInfo\nmkIconInfo infoPtr = \n liftM IconInfo $ newForeignPtr infoPtr icon_info_free\n\n--------------------\n-- Constructors\n\n#if GTK_CHECK_VERSION(2,14,0)\n-- |\n--\niconInfoNewForPixbuf :: IconThemeClass iconTheme => iconTheme -> Pixbuf -> IO IconInfo\niconInfoNewForPixbuf iconTheme pixbuf = \n {# call gtk_icon_info_new_for_pixbuf #}\n (toIconTheme iconTheme)\n pixbuf\n >>= mkIconInfo\n#endif\n\n--------------------\n-- Methods\n\n-- |\n--\niconInfoCopy :: IconInfo -> IO IconInfo\niconInfoCopy self = \n {# call gtk_icon_info_copy #} self\n >>= mkIconInfo\n\n-- | Fetches the set of attach points for an icon. An attach point is a location in the icon that can be\n-- used as anchor points for attaching emblems or overlays to the icon.\niconInfoGetAttachPoints :: IconInfo -> IO (Maybe [Point])\niconInfoGetAttachPoints self =\n alloca $ \\arrPtrPtr -> \n alloca $ \\nPointsPtr -> do\n success <- liftM toBool $ \n {# call gtk_icon_info_get_attach_points #}\n self\n (castPtr arrPtrPtr)\n nPointsPtr\n if success \n then do\n arrPtr <- peek arrPtrPtr\n nPoints <- peek nPointsPtr\n pointList <- peekArray (fromIntegral nPoints) arrPtr\n {#call unsafe g_free#} (castPtr arrPtr)\n return $ Just pointList\n else return Nothing\n\n-- | Gets the base size for the icon. The base size is a size for the icon that was specified by the icon\n-- theme creator. This may be different than the actual size of image; an example of this is small\n-- emblem icons that can be attached to a larger icon. These icons will be given the same base size as\n-- the larger icons to which they are attached.\n-- \niconInfoGetBaseSize :: IconInfo -> IO Int\niconInfoGetBaseSize self = \n liftM fromIntegral $\n {# call gtk_icon_info_get_base_size #} self\n\n-- | Gets the built-in image for this icon, if any. To allow GTK+ to use built in icon images, you must\n-- pass the ''IconLookupUseBuiltin'' to 'iconThemeLookupIcon'.\niconInfoGetBuiltinPixbuf :: IconInfo \n -> IO (Maybe Pixbuf) -- ^ returns the built-in image pixbuf, or 'Nothing'. \niconInfoGetBuiltinPixbuf self = do\n pixbufPtr <- {# call gtk_icon_info_get_builtin_pixbuf #} self\n if pixbufPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewGObject mkPixbuf (return pixbufPtr)\n\n-- | Gets the display name for an icon. A display name is a string to be used in place of the icon name\n-- in a user visible context like a list of icons.\niconInfoGetDisplayName :: IconInfo \n -> IO (Maybe String) -- ^ returns the display name for the icon or 'Nothing', if the icon doesn't have a specified display name. \niconInfoGetDisplayName self = do\n strPtr <- {# call gtk_icon_info_get_display_name #} self\n if strPtr == nullPtr \n then return Nothing\n else liftM Just $ peekUTFString strPtr\n\n-- | Gets the coordinates of a rectangle within the icon that can be used for display of information such\n-- as a preview of the contents of a text file. See 'iconInfoSetRawCoordinates' for further\n-- information about the coordinate system.\niconInfoGetEmbeddedRect :: IconInfo \n -> IO (Maybe Rectangle) -- ^ @rectangle@ 'Rectangle' in which to store embedded \n -- rectangle coordinates.\niconInfoGetEmbeddedRect self =\n alloca $ \\rectPtr -> do\n success <- liftM toBool $\n {# call gtk_icon_info_get_embedded_rect #}\n self\n (castPtr rectPtr)\n if success\n then liftM Just $ peek rectPtr\n else return Nothing\n\n-- | Gets the filename for the icon. If the ''IconLookupUseBuiltin'' flag was passed to\n-- 'iconThemeLookupIcon', there may be no filename if a builtin icon is returned; in this case,\n-- you should use 'iconInfoGetBuiltinPixbuf'.\niconInfoGetFilename :: IconInfo \n -> IO (Maybe String) -- ^ returns the filename for the icon, \n -- or 'Nothing' if 'iconInfoGetBuiltinPixbuf' should be used instead. \niconInfoGetFilename self = do\n namePtr <- {# call gtk_icon_info_get_filename #} self\n if namePtr == nullPtr\n then return Nothing \n else liftM Just $ peekUTFString namePtr\n\n-- | Looks up an icon in an icon theme, scales it to the given size and renders it into a pixbuf. This is\n-- a convenience function; if more details about the icon are needed, use 'iconThemeLookupIcon'\n-- followed by 'iconInfoLoadIcon'.\n-- \n-- Note that you probably want to listen for icon theme changes and update the icon. This is usually\n-- done by connecting to the 'styleSet' signal. If for some reason you do not want to update\n-- the icon when the icon theme changes, you should consider using 'pixbufCopy' to make a private\n-- copy of the pixbuf returned by this function. Otherwise GTK+ may need to keep the old icon theme\n-- loaded, which would be a waste of memory.\niconInfoLoadIcon :: IconInfo -> IO Pixbuf\niconInfoLoadIcon self =\n makeNewGObject mkPixbuf $\n propagateGError $ \\errorPtr ->\n {# call gtk_icon_info_load_icon #}\n self\n errorPtr\n\n-- | Sets whether the coordinates returned by 'iconInfoGetEmbeddedRect' and\n-- 'iconInfoGetAttachPoints' should be returned in their original form as specified in the icon\n-- theme, instead of scaled appropriately for the pixbuf returned by 'iconInfoLoadIcon'.\n-- \n-- Raw coordinates are somewhat strange; they are specified to be with respect to the unscaled pixmap\n-- for PNG and XPM icons, but for SVG icons, they are in a 1000x1000 coordinate space that is scaled to\n-- the final size of the icon. You can determine if the icon is an SVG icon by using\n-- 'iconInfoGetFilename', and seeing if it is non-'Nothing' and ends in '.svg'.\n-- \n-- This function is provided primarily to allow compatibility wrappers for older API's, and is not\n-- expected to be useful for applications.\niconInfoSetRawCoordinates :: IconInfo \n -> Bool -- ^ @rawCoordinates@ whether the coordinates of \n -- embedded rectangles and attached points should be returned in their original \n -> IO ()\niconInfoSetRawCoordinates self rawCoordinates =\n {# call gtk_icon_info_set_raw_coordinates #}\n self\n (fromBool rawCoordinates)\n\n--------------------\n-- Signals\n\n-- | Emitted when the current icon theme is switched or Gtk+ detects that a\n-- change has occurred in the contents of the current icon theme.\n--\niconThemeChanged :: IconThemeClass self => Signal self (IO ())\niconThemeChanged = Signal (connect_NONE__NONE \"changed\")\n\n#endif\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"8ad71b173cf7e2fd34c8079bf528c3359c33f6e1","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\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte","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":"5ec6c199901879d58e61118417f21ee9cad4b961","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","repos":"vincenthz\/webkit","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":"c46ad9a360324f0dbe4502f354b9d8e62b13da86","subject":"Export Histogram","message":"Export Histogram\n","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/Histogram.chs","new_file":"CV\/Histogram.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram\n ( module CV.Histogram\n , I.Histogram\n ) where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\nhistogram imageBins accumulate mask = unsafePerformIO $\n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds\n withPtrList (map imageFPTR images) $ \\ptrs ->\n case mask of\n Just m -> do\n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where\n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Histogram where\n\nimport CV.Image\n{#import CV.Image#}\n\nimport Data.List\nimport Data.Array\nimport Data.Array.ST\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport CV.Bindings.Types\nimport qualified CV.Bindings.ImgProc as I\nimport System.IO.Unsafe\nimport Utils.Pointer\n\n-- import Utils.List\n\nnewtype HistogramData a = HGD [(a,a)]\n\n-- | Given a set of images, such as the color channels of color image, and\n-- a histogram with corresponding number of channels, replace the pixels of\n-- the image with the likelihoods from the histogram\nbackProjectHistogram :: [Image GrayScale D8] -> I.Histogram -> Image GrayScale D8\nbackProjectHistogram images@(img:_) (I.Histogram hist) = unsafePerformIO $ do\n r <- cloneImage img\n withImage r $ \\c_r ->\n withPtrList (map imageFPTR images) $ \\ptrs ->\n withForeignPtr hist $ \\c_hist ->\n I.c'cvCalcArrBackProject (castPtr ptrs) (castPtr c_r) c_hist\n return r\nbackProjectHistogram _ _ = error \"Empty list of images\"\n\n-- |\u00a0Calculate an opencv histogram object from set of images, each with it's\n-- own number of bins.\nhistogram :: [(Image GrayScale D8, Int)] -> Bool -> Maybe (Image GrayScale D8)\n -> I.Histogram\nhistogram imageBins accumulate mask = unsafePerformIO $\n I.creatingHistogram $ do\n hist <- I.emptyUniformHistogramND ds\n withPtrList (map imageFPTR images) $ \\ptrs ->\n case mask of\n Just m -> do\n withImage m $ \\c_mask -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (castPtr c_mask)\n return hist\n Nothing -> do\n I.c'cvCalcArrHist (castPtr ptrs) hist c_accumulate (nullPtr)\n return hist\n where\n (images,ds) = unzip imageBins\n c_accumulate = 0\n\n-- getHistogramBin (I.Histogram hs) n = unsafePerformIO $ withForeignPtr hs (\\h -> I.c'cvGetHistValue_1D (castPtr h) n)\n\n---- Assume [0,1] distribution and calculate skewness\n--skewness bins image = do\n-- hg <- buildHistogram cbins image\n-- bins <- mapM (getBin hg) [0..cbins-1]\n-- let avg = sum bins \/ (fromIntegral.length) bins\n-- let u3 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n-- let u2 = sum.map (\\(value,bin) ->\n-- (value-avg)*(value-avg)\n-- *bin) $\n-- zip binValues bins\n----\n-- return (u3 \/ (sqrt u2*sqrt u2*sqrt u2))\n-- where\n-- cbins :: CInt\n-- cbins = fromIntegral bins\n-- binValues = [0,fstep..1]\n-- fstep = 1\/(fromIntegral bins)\n\nvalues (HGD a) = snd.unzip $ a\n\n-- This does not make any sense!\ncmpUnion a b = sum $ zipWith (max) a b\n\ncmpIntersect a b = sum $ zipWith min a b\n\ncmpEuclidian a b = sum $ (zipWith (\\x y -> (x-y)^2) a b)\ncmpAbs a b = sum $ (zipWith (\\x y -> abs (x-y)) a b)\n\nchiSqrHG a b = chiSqr (values a) (values b)\nchiSqr a b = sum $ zipWith (calc) a b\n where\n calc a b = (a-b)*(a-b) `divide` (a+b)\n divide a b | abs(b) > 0.000001 = a\/b\n | otherwise = 0\n\nliftBins op (HGD a) = zip (op bins) values\n where (bins,values) = unzip a\n\nliftValues op (HGD a) = zip bins (op values)\n where (bins,values) = unzip a\n\nsub (HGD a) (HGD b) | bins a == bins b\n = HGD $ zip (bins a) values\n where\n bins a = map fst a\n msnd = map snd\n values = zipWith (-) (msnd a) (msnd b)\n\n\nnoBins (HGD a) = length a\n\ngetPositivePart (HGD a) = HGD $ dropWhile ((<0).fst) a\ntcumulate [] = []\ntcumulate values = tail $ scanl (+) 0 values\n\n--getCumulativeNormalHistogram binCount image\n-- = HGD $ zip bins $ tcumulate values\n-- where\n-- HGD lst = getNormalHistogram binCount image\n-- bins :: [Double]\n-- values :: [Double]\n-- (bins,values) = unzip lst\n\nweightedHistogram img weights start end binCount = unsafePerformIO $\n withImage img $ \\i ->\n withImage weights $ \\w -> do\n bins <- mallocArray (fromIntegral binCount)\n {#call get_weighted_histogram#} i w (realToFrac start)\n (realToFrac end)\n (fromIntegral binCount) bins\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n-- TODO: Add binary images\nsimpleGetHistogram :: Image GrayScale D32 -> Maybe (Image GrayScale D8)\n -> D32 -> D32 -> Int -> Bool -> [D32]\nsimpleGetHistogram img mask start end binCount cumulative = unsafePerformIO $\n withImage img $ \\i -> do\n bins <- mallocArray binCount\n let isCum | cumulative == True = 1\n | cumulative == False = 0\n\n case mask of\n (Just msk) -> do\n withImage msk $ \\m -> do\n {#call get_histogram#} i m (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n Nothing -> {#call get_histogram#} i (nullPtr)\n (realToFrac start) (realToFrac end)\n isCum (fromIntegral binCount) bins\n\n r <- peekArray binCount bins >>= return.map realToFrac\n free bins\n return r\n\n\n\n\n--getNormalHistogram bins image = HGD new\n-- where\n-- (HGD lst) = getHistogram bins image\n----\n---- value :: [Double]\n-- bin :: [Double]\n-- (bin,value) = unzip lst\n-- new = zip bin $ map (\/size) value\n-- size = fromIntegral $ uncurry (*) $ getSize image\n\n--getHistogram :: Int -> Image GrayScale D32 -> HistogramData Double\n--getHistogram bins image = unsafePerformIO $ do\n-- h <- buildHistogram cbins image\n-- values <- mapM (getBin h)\n-- [0..fromIntegral bins-1]\n-- return.HGD $\n-- zip [-1,-1+2\/(realToFrac bins)..1] values\n-- where\n-- cbins = fromIntegral bins\n\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d0e171d0c020fe5b9fb0b4188bc3757881019de2","subject":"variable grouping","message":"variable grouping\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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall unsafe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\n--Reorder right now\nforeign import ccall unsafe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall unsafe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n\n--Reordering stats\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall unsafe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall unsafe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddturnOffCountDead :: DdManager -> IO ()\ncuddturnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall unsafe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall unsafe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall unsafe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\n","old_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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall unsafe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\n--Reorder right now\nforeign import ccall unsafe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Reordering stats\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall unsafe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall unsafe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall unsafe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall unsafe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddturnOffCountDead :: DdManager -> IO ()\ncuddturnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall unsafe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall unsafe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall unsafe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall unsafe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall unsafe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall unsafe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall unsafe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall unsafe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5302c31e7b6fa35fda31a05db9462e507787d601","subject":"fix type of memset, and minor tidy up","message":"fix type of memset, and minor tidy up\n\nIgnore-this: 6cb278c8bcd50b703e9476f9837254fb\n\ndarcs-hash:20090720021953-115f9-192fea0cb1be6f0533e817c91809c3df21b6243a.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/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 -- Thread management\n --\n threadSynchronize,\n\n --\n -- Device management\n --\n chooseDevice,\n getDevice,\n getDeviceCount,\n getDeviceProperties,\n setDevice,\n setDeviceFlags,\n setValidDevices,\n\n --\n -- Memory management\n --\n malloc, mallocPitch,\n memcpy, memcpyAsync,\n memset,\n\n\n --\n -- Stream management\n --\n streamCreate,\n streamDestroy,\n streamQuery,\n streamSynchronize\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--------------------------------------------------------------------------------\n-- Thread Management\n--------------------------------------------------------------------------------\n\n--\n-- Block until the device has completed all preceding requests\n--\nthreadSynchronize :: IO (Maybe String)\nthreadSynchronize = nothingIfOk `fmap` cudaThreadSynchronize\n\n{# fun unsafe cudaThreadSynchronize\n { } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Select compute device which best matches criteria\n--\nchooseDevice :: DeviceProperties -> IO (Either String Int)\nchooseDevice dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n--\n-- Returns which device is currently being used\n--\ngetDevice :: IO (Either String Int)\ngetDevice = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\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* } -> `Status' 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' } -> `Status' 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' } -> `Status' cToEnum #}\n\n--\n-- Set flags to be used for device executions\n--\nsetDeviceFlags :: [DeviceFlags] -> IO (Maybe String)\nsetDeviceFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n--\n-- Set list of devices for CUDA execution in priority order\n--\nsetValidDevices :: [Int] -> IO (Maybe String)\nsetValidDevices l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\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--\n-- If the allocation is successful, it is marked to be automatically released\n-- when no longer needed.\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' } -> `Status' cToEnum #}\n\n--\n-- Allocate pitched memory on the device\n--\nmallocPitch :: Integer -> Integer -> IO (Either String (DevicePtr,Integer))\nmallocPitch width height = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ getErrorString rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n--\n-- Copy data between host and device\n--\nmemcpy :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n--\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> Stream -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Initialize device memory to a given value\n--\nmemset :: DevicePtr -> Int -> Integer -> IO (Maybe String)\nmemset ptr symbol bytes = nothingIfOk `fmap` cudaMemset ptr bytes symbol\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\n--\n-- Create an asynchronous stream\n--\nstreamCreate :: IO (Either String Stream)\nstreamCreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peek* } -> `Status' cToEnum #}\n\n--\n-- Destroy and clean up an asynchronous stream\n--\nstreamDestroy :: Stream -> IO (Maybe String)\nstreamDestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Determine if all operations in a stream have completed\n--\nstreamQuery :: Stream -> IO (Either String Bool)\nstreamQuery s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (getErrorString rv)\n\n{# fun unsafe cudaStreamQuery\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Block until all operations have been completed\n--\nstreamSynchronize :: Stream -> IO (Maybe String)\nstreamSynchronize s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\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 -- Thread management\n --\n threadSynchronize,\n\n --\n -- Device management\n --\n chooseDevice,\n getDevice,\n getDeviceCount,\n getDeviceProperties,\n setDevice,\n setDeviceFlags,\n setValidDevices,\n\n --\n -- Memory management\n --\n malloc, mallocPitch,\n memcpy, memcpyAsync,\n memset,\n\n\n --\n -- Stream management\n --\n streamCreate,\n streamDestroy,\n streamQuery,\n streamSynchronize\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--------------------------------------------------------------------------------\n-- Thread Management\n--------------------------------------------------------------------------------\n\n--\n-- Block until the device has completed all preceding requests\n--\nthreadSynchronize :: IO (Maybe String)\nthreadSynchronize = nothingIfOk `fmap` cudaThreadSynchronize\n\n{# fun unsafe cudaThreadSynchronize\n { } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Select compute device which best matches criteria\n--\nchooseDevice :: DeviceProperties -> IO (Either String Int)\nchooseDevice dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n--\n-- Returns which device is currently being used\n--\ngetDevice :: IO (Either String Int)\ngetDevice = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\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* } -> `Status' 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' } -> `Status' 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' } -> `Status' cToEnum #}\n\n--\n-- Set flags to be used for device executions\n--\nsetDeviceFlags :: [DeviceFlags] -> IO (Maybe String)\nsetDeviceFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n--\n-- Set list of devices for CUDA execution in priority order\n--\nsetValidDevices :: [Int] -> IO (Maybe String)\nsetValidDevices l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\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--\n-- If the allocation is successful, it is marked to be automatically released\n-- when no longer needed.\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' } -> `Status' cToEnum #}\n\n--\n-- Allocate pitched memory on the device\n--\nmallocPitch :: Integer -> Integer -> IO (Either String (DevicePtr,Integer))\nmallocPitch width height = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ getErrorString rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n--\n-- Copy data between host and device\n--\nmemcpy :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n--\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> Stream -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Initialize device memory to a given value\n--\nmemset :: DevicePtr -> Integer -> Int -> IO (Maybe String)\nmemset ptr symbol bytes = nothingIfOk `fmap` cudaMemset ptr bytes symbol\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\n--\n-- Create an asynchronous stream\n--\nstreamCreate :: IO (Either String Stream)\nstreamCreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peek* } -> `Status' cToEnum #}\n\n--\n-- Destroy and clean up an asynchronous stream\n--\nstreamDestroy :: Stream -> IO (Maybe String)\nstreamDestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Determine if all operations in a stream have completed\n--\nstreamQuery :: Stream -> IO (Either String Bool)\nstreamQuery s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (getErrorString rv)\n\n{# fun unsafe cudaStreamQuery\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Block until all operations have been completed\n--\nstreamSynchronize :: Stream -> IO (Maybe String)\nstreamSynchronize s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e121fd553f187bb1dce01fafc65879f9d12b5d27","subject":"cuddAutydynDisable","message":"cuddAutydynDisable\n","repos":"adamwalker\/haskell_cudd,maweki\/haskell_cudd","old_file":"CuddReorder.chs","new_file":"CuddReorder.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddAutodynDisable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynDisable\"\n\tc_cuddAutodynDisable :: Ptr CDdManager -> IO ()\n\ncuddAutodynDisable :: DdManager -> IO ()\ncuddAutodynDisable (DdManager m) = c_cuddAutodynDisable m\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: DdManager -> IO ()\ncuddTurnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: DdManager -> IO Int\nregReordGCHook m = do\n hk <- makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder (\n CuddReorderingType(..),\n cuddReorderingStatus,\n cuddAutodynEnable,\n cuddReduceHeap,\n cuddMakeTreeNode,\n cuddReadReorderingTime,\n cuddReadReorderings,\n cuddEnableReorderingReporting,\n cuddDisableReorderingReporting,\n cuddReorderingReporting,\n regStdPreReordHook,\n regStdPostReordHook,\n cuddTurnOnCountDead,\n cuddTurnOffCountDead,\n cuddDeadAreCounted,\n cuddReadSiftMaxSwap,\n cuddSetSiftMaxSwap,\n cuddReadNextReordering,\n cuddSetNextReordering,\n cuddReadMaxGrowthAlternate,\n cuddSetMaxGrowthAlternate,\n cuddReadMaxGrowth,\n cuddReadReorderingCycle,\n cuddSetReorderingCycle,\n cuddSetPopulationSize,\n cuddReadNumberXovers,\n cuddSetNumberXovers,\n regReordGCHook\n ) where\n\nimport System.IO\nimport System.Mem\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 \n\nreadIntegral :: (Integral i, Num j) => (Ptr CDdManager -> IO i) -> DdManager -> IO j\nreadIntegral f (DdManager m) = liftM fromIntegral $ f m\n\nsetIntegral :: (Integral i, Num j) => (Ptr CDdManager -> j -> IO ()) -> DdManager -> i -> IO ()\nsetIntegral f (DdManager m) v = f m (fromIntegral v)\n\nreadFloat :: (Real r, Fractional f) => (Ptr CDdManager -> IO r) -> DdManager -> IO f\nreadFloat f (DdManager m) = liftM realToFrac $ f m \n\nsetFloat :: (Real r, Fractional f) => (Ptr CDdManager -> f -> IO ()) -> DdManager -> r -> IO ()\nsetFloat f (DdManager m) v = f m (realToFrac v)\n\n--Reordering types\n{#enum Cudd_ReorderingType as CuddReorderingType {underscoreToCase} deriving (Show, Eq) #}\n\n--Reorder when needed\nforeign import ccall safe \"cudd.h Cudd_ReorderingStatus\"\n\tc_cuddReorderingStatus :: Ptr CDdManager -> Ptr CInt -> IO (CInt)\n\ncuddReorderingStatus :: DdManager -> IO (Int, CuddReorderingType)\ncuddReorderingStatus (DdManager m) = do\n\talloca $ \\mem -> do\n\t\tres <- c_cuddReorderingStatus m mem\n\t\ttyp <- peek mem\n\t\treturn $ (fromIntegral res, toEnum $ fromIntegral typ)\n\nforeign import ccall safe \"cudd.h Cudd_AutodynEnable\"\n\tc_cuddAutodynEnable :: Ptr CDdManager -> CInt -> IO ()\n\ncuddAutodynEnable :: DdManager -> CuddReorderingType -> IO ()\ncuddAutodynEnable (DdManager m) t = c_cuddAutodynEnable m (fromIntegral $ fromEnum t)\n\n--Reorder right now\nforeign import ccall safe \"cudd.h Cudd_ReduceHeap\"\n\tc_cuddReduceHeap :: Ptr CDdManager -> CInt -> CInt -> IO (CInt)\n\ncuddReduceHeap :: DdManager -> CuddReorderingType -> Int -> IO (Int)\ncuddReduceHeap (DdManager m) typ minsize = liftM fromIntegral $ c_cuddReduceHeap m (fromIntegral $ fromEnum typ) (fromIntegral minsize)\n\n--Grouping\nforeign import ccall safe \"cudd.h Cudd_MakeTreeNode\"\n\tc_cuddMakeTreeNode :: Ptr CDdManager -> CUInt -> CUInt -> CUInt -> IO (Ptr ())\n\ncuddMakeTreeNode :: DdManager -> Int -> Int -> Int -> IO (Ptr ())\ncuddMakeTreeNode (DdManager m) low size typ = do\n res <- c_cuddMakeTreeNode m (fromIntegral low) (fromIntegral size) (fromIntegral typ)\n when (res==nullPtr) (error \"cuddMakeTreeNode returned error\")\n return res\n\n--Reordering stats\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingTime\"\n\tc_cuddReadReorderingTime :: Ptr CDdManager -> IO (CLong)\n\ncuddReadReorderingTime :: DdManager -> IO (Int)\ncuddReadReorderingTime = readIntegral c_cuddReadReorderingTime\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderings\"\n\tc_cuddReadReorderings :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderings :: DdManager -> IO (Int)\ncuddReadReorderings = readIntegral c_cuddReadReorderings\n\n--Hooks\nforeign import ccall safe \"cudd.h &Cudd_StdPreReordHook\"\n\tc_cuddStdPreReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h &Cudd_StdPostReordHook\"\n\tc_cuddStdPostReordHook :: HookFP\n\nforeign import ccall safe \"cudd.h Cudd_EnableReorderingReporting\"\n\tc_cuddEnableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddEnableReorderingReporting :: DdManager -> IO (Int)\ncuddEnableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddEnableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_DisableReorderingReporting\"\n\tc_cuddDisableReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddDisableReorderingReporting :: DdManager -> IO (Int)\ncuddDisableReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddDisableReorderingReporting m\n\nforeign import ccall safe \"cudd.h Cudd_ReorderingReporting\"\n\tc_cuddReorderingReporting :: Ptr CDdManager -> IO (CInt)\n\ncuddReorderingReporting :: DdManager -> IO (Int)\ncuddReorderingReporting (DdManager m) = liftM fromIntegral $ c_cuddReorderingReporting m\n\nregStdPreReordHook :: DdManager -> IO (Int)\nregStdPreReordHook m = cuddAddHook m c_cuddStdPreReordHook CuddPreReorderingHook\n\nregStdPostReordHook :: DdManager -> IO (Int)\nregStdPostReordHook m = cuddAddHook m c_cuddStdPostReordHook CuddPostReorderingHook\n\n--Universal reordering params\nforeign import ccall safe \"cudd.h Cudd_TurnOffCountDead\"\n\tc_cuddTurnOffCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOffCountDead :: DdManager -> IO ()\ncuddTurnOffCountDead (DdManager m) = c_cuddTurnOffCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_TurnOnCountDead\"\n\tc_cuddTurnOnCountDead :: Ptr CDdManager -> IO ()\n\ncuddTurnOnCountDead :: DdManager -> IO ()\ncuddTurnOnCountDead (DdManager m) = c_cuddTurnOnCountDead m\n\nforeign import ccall safe \"cudd.h Cudd_DeadAreCounted\"\n\tc_cuddDeadAreCounted :: Ptr CDdManager -> IO CInt\n\ncuddDeadAreCounted :: DdManager -> IO (Int)\ncuddDeadAreCounted (DdManager m) = liftM fromIntegral $ c_cuddDeadAreCounted m\n\n--Sifting parameters\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxSwap\"\n\tc_cuddReadSiftMaxSwap :: Ptr CDdManager -> IO (CInt)\n\ncuddReadSiftMaxSwap :: DdManager -> IO (Int)\ncuddReadSiftMaxSwap = readIntegral c_cuddReadSiftMaxSwap\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxSwap\"\n\tc_cuddSetSiftMaxSwap :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetSiftMaxSwap :: DdManager -> Int -> IO ()\ncuddSetSiftMaxSwap = setIntegral c_cuddSetSiftMaxSwap \n\nforeign import ccall safe \"cudd.h Cudd_ReadSiftMaxVar\"\n\tc_cuddReadSiftMaxVar :: Ptr CDdManager -> IO (Int)\n\ncuddReadSiftMaxVar :: DdManager -> IO (Int)\ncuddReadSiftMaxVar = readIntegral c_cuddReadSiftMaxVar\n\nforeign import ccall safe \"cudd.h Cudd_SetSiftMaxVar\"\n\tc_cuddSetSiftMaxVar :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetsiftMaxVar :: DdManager -> Int -> IO ()\ncuddSetsiftMaxVar = setIntegral c_cuddSetSiftMaxVar\n\t\nforeign import ccall safe \"cudd.h Cudd_ReadNextReordering\"\n\tc_cuddReadNextReordering :: Ptr CDdManager -> IO (Int)\n\ncuddReadNextReordering :: DdManager -> IO (Int)\ncuddReadNextReordering = readIntegral c_cuddReadNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_SetNextReordering\"\n\tc_cuddSetNextReordering :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNextReordering :: DdManager -> Int -> IO ()\ncuddSetNextReordering = setIntegral c_cuddSetNextReordering\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowthAlternate\"\n\tc_cuddReadMaxGrowthAlternate :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowthAlternate :: DdManager -> IO (Double)\ncuddReadMaxGrowthAlternate = readFloat c_cuddReadMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowthAlternate\"\n\tc_cuddSetMaxGrowthAlternate :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowthAlternate :: DdManager -> Double -> IO ()\ncuddSetMaxGrowthAlternate = setFloat c_cuddSetMaxGrowthAlternate\n\nforeign import ccall safe \"cudd.h Cudd_ReadMaxGrowth\"\n\tc_cuddReadMaxGrowth :: Ptr CDdManager -> IO CDouble\n\ncuddReadMaxGrowth :: DdManager -> IO CDouble\ncuddReadMaxGrowth = readFloat c_cuddReadMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_SetMaxGrowth\"\n\tc_cuddSetMaxGrowth :: Ptr CDdManager -> CDouble -> IO ()\n\ncuddSetMaxGrowth :: DdManager -> Double -> IO ()\ncuddSetMaxGrowth = setFloat c_cuddSetMaxGrowth\n\nforeign import ccall safe \"cudd.h Cudd_ReadReorderingCycle\"\n\tc_cuddReadReorderingCycle :: Ptr CDdManager -> IO (CInt)\n\ncuddReadReorderingCycle :: DdManager -> IO Int\ncuddReadReorderingCycle = readIntegral c_cuddReadReorderingCycle\n\nforeign import ccall safe \"cudd.h Cudd_SetReorderingCycle\"\n\tc_cuddSetReorderingCycle :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetReorderingCycle :: DdManager -> CInt -> IO ()\ncuddSetReorderingCycle = setIntegral c_cuddSetReorderingCycle\n\n--Genetic algorithm\nforeign import ccall safe \"cudd.h Cudd_ReadPopulationSize\"\n\tc_cuddReadPopulationSize :: Ptr CDdManager -> IO (CInt)\n\ncuddReadPopulationSize :: DdManager -> IO (Int)\ncuddReadPopulationSize = readIntegral c_cuddReadPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_SetPopulationSize\"\n\tc_cuddSetPopulationSize :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetPopulationSize :: DdManager -> Int -> IO ()\ncuddSetPopulationSize = setIntegral c_cuddSetPopulationSize\n\nforeign import ccall safe \"cudd.h Cudd_ReadNumberXovers\"\n\tc_cuddReadNumberXovers :: Ptr CDdManager -> IO (CInt)\n\ncuddReadNumberXovers :: DdManager -> IO (Int)\ncuddReadNumberXovers = readIntegral c_cuddReadNumberXovers\n\nforeign import ccall safe \"cudd.h Cudd_SetNumberXovers\"\n\tc_cuddSetNumberXovers :: Ptr CDdManager -> CInt -> IO ()\n\ncuddSetNumberXovers :: DdManager -> Int -> IO ()\ncuddSetNumberXovers = setIntegral c_cuddSetNumberXovers\n\nreordGCHook :: HookTyp\nreordGCHook _ _ _ = do\n --putStrLn \"reordGCHook\"\n performGC\n --putStrLn \"gc done\"\n return (fromIntegral 1)\n\nforeign import ccall \"wrapper\"\n makeFunPtr :: HookTyp -> IO (FunPtr HookTyp)\n\nregReordGCHook :: DdManager -> IO Int\nregReordGCHook m = do\n hk <- makeFunPtr reordGCHook\n cuddAddHook m hk CuddPreReorderingHook\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"fe567ef72a2fc14dc581bd6660973051e7e5d526","subject":"Added clCreateFromGLTexture2D.","message":"Added clCreateFromGLTexture2D.\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, 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, 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 \"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 :: CLContext -> [CLMemFlag] -> CLuint -> IO CLMem\nclCreateFromGLBuffer ctx xs glObj = wrapPError $ \\perr -> do\n raw_clCreateFromGLBuffer ctx flags glObj perr\n where 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d1dcbe8faa2f6637fe2cb85563b05cef9d4da965","subject":"Fix types, remove key binding signals.","message":"Fix types, remove key binding signals.","repos":"vincenthz\/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":"7882f213b41d47e819b543ffa03987e3f08794b7","subject":"fix up gc hooks","message":"fix up gc hooks\n","repos":"maweki\/haskell_cudd,adamwalker\/haskell_cudd","old_file":"CuddGC.chs","new_file":"CuddGC.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddGC (\n cuddEnableGarbageCollection,\n cuddDisableGarbageCollection,\n cuddGarbageCollectionEnabled,\n c_PreGCHook,\n c_PostGCHook,\n regPreGCHook,\n regPostGCHook\n ) 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\nimport Control.Monad.ST\n\nimport CuddInternal\nimport CuddHook\n\n#include \n#include \n\nforeign import ccall safe \"cudd.h Cudd_EnableGarbageCollection\"\n\tc_cuddEnableGarbageCollection :: Ptr CDdManager -> IO ()\n\ncuddEnableGarbageCollection :: STDdManager s u -> ST s ()\ncuddEnableGarbageCollection (STDdManager m) = unsafeIOToST $ c_cuddEnableGarbageCollection m\n\nforeign import ccall safe \"cudd.h Cudd_DisableGarbageCollection\"\n\tc_cuddDisableGarbageCollection :: Ptr CDdManager -> IO ()\n\ncuddDisableGarbageCollection :: STDdManager s u -> ST s ()\ncuddDisableGarbageCollection (STDdManager m) = unsafeIOToST $ c_cuddDisableGarbageCollection m\n\nforeign import ccall safe \"cudd.h Cudd_GarbageCollectionEnabled\"\n\tc_cuddGarbageCollectionEnabled :: Ptr CDdManager -> IO (CInt)\n\ncuddGarbageCollectionEnabled :: STDdManager s u -> ST s Int\ncuddGarbageCollectionEnabled (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddGarbageCollectionEnabled m\n\nforeign import ccall safe \"cuddwrap.h &PreGCHook\"\n\tc_PreGCHook :: HookFP\n\nforeign import ccall safe \"cuddwrap.h &PostGCHook\"\n\tc_PostGCHook :: HookFP\n\nregPreGCHook :: STDdManager s u -> HookFP -> ST s Int\nregPreGCHook m func = cuddAddHook m func CuddPreGcHook\n\nregPostGCHook :: STDdManager s u -> HookFP -> ST s Int\nregPostGCHook m func = cuddAddHook m func CuddPostGcHook\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddGC (\n cuddEnableGarbageCollection,\n cuddDisableGarbageCollection,\n cuddGarbageCollectionEnabled,\n regPreGCHook,\n regPostGCHook\n ) 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\nimport Control.Monad.ST\n\nimport CuddInternal\nimport CuddHook\n\n#include \n#include \n\nforeign import ccall safe \"cudd.h Cudd_EnableGarbageCollection\"\n\tc_cuddEnableGarbageCollection :: Ptr CDdManager -> IO ()\n\ncuddEnableGarbageCollection :: STDdManager s u -> ST s ()\ncuddEnableGarbageCollection (STDdManager m) = unsafeIOToST $ c_cuddEnableGarbageCollection m\n\nforeign import ccall safe \"cudd.h Cudd_DisableGarbageCollection\"\n\tc_cuddDisableGarbageCollection :: Ptr CDdManager -> IO ()\n\ncuddDisableGarbageCollection :: STDdManager s u -> ST s ()\ncuddDisableGarbageCollection (STDdManager m) = unsafeIOToST $ c_cuddDisableGarbageCollection m\n\nforeign import ccall safe \"cudd.h Cudd_GarbageCollectionEnabled\"\n\tc_cuddGarbageCollectionEnabled :: Ptr CDdManager -> IO (CInt)\n\ncuddGarbageCollectionEnabled :: STDdManager s u -> ST s Int\ncuddGarbageCollectionEnabled (STDdManager m) = unsafeIOToST $ liftM fromIntegral $ c_cuddGarbageCollectionEnabled m\n\nforeign import ccall safe \"cuddwrap.h &PreGCHook\"\n\tc_PreGCHook :: HookFP\n\nforeign import ccall safe \"cuddwrap.h &PostGCHook\"\n\tc_PostGCHook :: HookFP\n\nregPreGCHook :: STDdManager s u -> ST s Int\nregPreGCHook m = cuddAddHook m c_PreGCHook CuddPreGcHook\n\nregPostGCHook :: STDdManager s u -> ST s Int\nregPostGCHook m = cuddAddHook m c_PostGCHook CuddPostGcHook\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"a0b4ae1522ee321517c34cd41e02b39051b0faaf","subject":"Added iSend.","message":"Added iSend.\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Bindings\/MPI\/Internal.chs","new_file":"src\/Bindings\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n ( init, finalize, send, recv, commRank, probe, commSize,\n iSend, iRecv \n ) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Applicative ((<$>))\nimport Bindings.MPI.Comm (Comm)\nimport Bindings.MPI.Request (Request)\nimport Bindings.MPI.Status (Status, StatusPtr)\nimport Bindings.MPI.MarshalUtils (enumToCInt)\nimport Bindings.MPI.ErrorClasses (ErrorClass)\nimport Bindings.MPI.MarshalUtils (enumFromCInt)\nimport Bindings.MPI.Utils (checkError)\n\n{# context prefix = \"MPI\" #}\n\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #}\ncommRank = {# call unsafe Comm_rank as commRank_ #}\nprobe = {# call unsafe Probe as probe_ #}\nsend = {# call unsafe Send as send_ #}\nrecv = {# call unsafe Recv as recv_ #}\niSend = {# call unsafe Isend as iSend_ #}\niRecv = {# call unsafe Irecv as iRecv_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n#include \"init_wrapper.h\"\n\nmodule Bindings.MPI.Internal \n (init, finalize, send, recv, commRank, probe) where\n\nimport Prelude hiding (init, error)\nimport C2HS\nimport Control.Applicative ((<$>))\nimport Bindings.MPI.Comm (Comm)\nimport Bindings.MPI.Status (Status, StatusPtr)\nimport Bindings.MPI.MarshalUtils (enumToCInt)\nimport Bindings.MPI.ErrorClasses (ErrorClass)\nimport Bindings.MPI.MarshalUtils (enumFromCInt)\nimport Bindings.MPI.Utils (checkError)\n\n{# context prefix = \"MPI\" #}\n\n-- {# fun unsafe init_wrapper as init {} -> `ErrorClass' enumFromCInt #}\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\n\n-- {# fun unsafe Finalize as finalize {} -> `ErrorClass' enumFromCInt #}\nfinalize = {# call unsafe Finalize as finalize_ #}\n\ncommRank = {# call unsafe Comm_rank as commRank_ #}\n\nsend = {# call unsafe Send as send_ #}\n\nrecv = {# call unsafe Recv as recv_ #}\n\nprobe = {# call unsafe Probe as probe_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"da06eca22bcc3f8219e9e09d1c18a8887c1604ae","subject":"add buffer queue ops","message":"add buffer queue ops\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 -- * 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(..),\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 \"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-- -----------------------------------------------------------------------------\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 :: CLCommandQueue -> CLMem -> Bool -> CSize -> CSize \n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueReadBuffer cq mem check off size dat [] = alloca $ \\event -> do\n errcode <- raw_clEnqueueReadBuffer cq mem (fromBool check) off size dat 0 nullPtr event\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap Right $ peek event\n else return . Left . toEnum . fromIntegral $ errcode\nclEnqueueReadBuffer cq mem check off size dat events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> do\n errcode <- raw_clEnqueueReadBuffer cq mem (fromBool check) off size dat 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{-| 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 :: CLCommandQueue -> CLMem -> Bool -> CSize -> CSize \n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueWriteBuffer cq mem check off size dat [] = alloca $ \\event -> do\n errcode <- raw_clEnqueueWriteBuffer cq mem (fromBool check) off size dat 0 nullPtr event\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap Right $ peek event\n else return . Left . toEnum . fromIntegral $ errcode\nclEnqueueWriteBuffer cq mem check off size dat events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> do\n errcode <- raw_clEnqueueWriteBuffer cq mem (fromBool check) off size dat 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-- | 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","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 -- * Executing Kernels\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_, CLError,\n CLCommandQueue, CLDeviceID, CLContext, CLCommandQueueProperty(..), ErrorCode(..),\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 \"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-- -----------------------------------------------------------------------------\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":"44b6eeebcf3d98ae27662ac6481ee3763f299f40","subject":"glade: remove glade\/Glade.chs (not sure why this file is here...)","message":"glade: remove glade\/Glade.chs (not sure why this file is here...)","repos":"vincenthz\/webkit","old_file":"glade\/Glade.chs","new_file":"glade\/Glade.chs","new_contents":"","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to Libglade -*-haskell-*-\n-- for loading XML widget specifications\n--\n-- Author : Manuel M T Chakravarty\n-- Created: 13 March 2002\n--\n-- Copyright (c) 2002 Manuel M T Chakravarty\n-- Modified 2003 by Duncan Coutts (gtk2hs port)\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-- |\n--\n-- Libglade facilitates loading of XML specifications of whole widget trees\n-- that have been interactively designed with the GUI builder Glade. The\n-- present module exports operations for manipulating 'GladeXML' objects.\n--\n-- @glade_xml_signal_autoconnect()@ is not supported. The C variant is not\n-- suitable for Haskell as @-rdynamic@ leads to huge executable and we\n-- usually don't want to connect staticly named functions, but closures.\n--\n-- * @glade_xml_construct()@ is not bound, as it doesn't seem to be useful\n-- in Haskell. As usual, the @signal_connect_data@ variant for\n-- registering signal handlers isn't bound either. Moreover, the\n-- @connect_full@ functions are not bound.\n--\n-- * This binding does not support Libglade functionality that is\n-- exclusively meant for extending Libglade with new widgets. Like new\n-- widgets, such functionality is currently expected to be implemented in\n-- C.\n--\n\nmodule Glade (\n\n -- * Data types\n --\n GladeXMLClass, GladeXML,\n\n -- * Creation operations\n --\n xmlNew, xmlNewWithRootAndDomain,\n\n -- * Obtaining widget handles\n --\n xmlGetWidget, xmlGetWidgetRaw\n\n) where\n\nimport Monad\t(liftM)\nimport FFI\nimport GType\nimport Object (makeNewObject)\nimport GObject (makeNewGObject)\n{#import Hierarchy#}\n{#import GladeType#}\nimport GList\n\n{#context lib=\"glade\" prefix =\"glade\"#}\n\n\n-- | Create a new XML object (and the corresponding\n-- widgets) from the given XML file; corresponds to\n-- 'xmlNewWithRootAndDomain', but without the ability to specify a root\n-- widget or translation domain.\n--\nxmlNew :: FilePath -> IO (Maybe GladeXML)\nxmlNew file =\n withCString file $ \\strPtr1 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 nullPtr nullPtr\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Create a new GladeXML object (and\n-- the corresponding widgets) from the given XML file with an optional\n-- root widget and translation domain.\n--\n-- * If the second argument is not @Nothing@, the interface will only be built\n-- from the widget whose name is given. This feature is useful if you only\n-- want to build say a toolbar or menu from the XML file, but not the window\n-- it is embedded in. Note also that the XML parse tree is cached to speed\n-- up creating another \\'XML\\' object for the same file.\n--\nxmlNewWithRootAndDomain :: FilePath -> Maybe String -> Maybe String -> IO (Maybe GladeXML)\nxmlNewWithRootAndDomain file rootWidgetName domain =\n withCString file $ \\strPtr1 ->\n withMaybeCString rootWidgetName $ \\strPtr2 ->\n withMaybeCString domain $ \\strPtr3 -> do\n xmlPtr <- {#call unsafe xml_new#} strPtr1 strPtr2 strPtr3\n if xmlPtr==nullPtr then return Nothing\n else liftM Just $ makeNewGObject mkGladeXML (return xmlPtr)\n\n-- | Get the widget that has the given name in\n-- the interface description. If the named widget cannot be found\n-- or is of the wrong type the result is an error.\n--\n-- * the second parameter should be a dynamic cast function that\n-- returns the type of object that you expect, eg castToButton\n--\n-- * the third parameter is the ID of the widget in the glade xml\n-- file, eg \\\"button1\\\".\n--\nxmlGetWidget :: (WidgetClass widget) => GladeXML -> (GObject -> widget) -> String -> IO widget\nxmlGetWidget xml cast name = do\n maybeWidget <- xmlGetWidgetRaw xml name\n return $ case maybeWidget of\n Just widget -> cast (toGObject widget) --the cast will return an error if the object is of the wrong type\n Nothing -> error $ \"glade.xmlGetWidget: no object named \" ++ show name ++ \" in the glade file\"\n\nxmlGetWidgetRaw :: GladeXML -> String -> IO (Maybe Widget)\nxmlGetWidgetRaw xml name =\n withCString name $ \\strPtr1 -> do\n widgetPtr <- {#call unsafe xml_get_widget#} xml strPtr1\n if widgetPtr==nullPtr then return Nothing\n else liftM Just $ makeNewObject mkWidget (return widgetPtr)\n\n-- Auxilliary routines\n-- -------------------\n\n-- Marshall an optional string\n--\nwithMaybeCString :: Maybe String -> (Ptr CChar -> IO a) -> IO a\nwithMaybeCString = maybeWith withCString\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"999c995da5202d340f2bb5846862e3dbdc880c90","subject":"Fix typo specic -> specific","message":"Fix typo specic -> specific\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 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-- | 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(..), 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, 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-- | 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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2b8ba4a31abc0bb8eceb42712514f67ce6ee877a","subject":"Fix signature of callbacks that may pass NULL objects.","message":"Fix signature of callbacks that may pass NULL objects.\n","repos":"gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Widget -> IO ())\nparentSet = Signal (connect_OBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Widget -> IO ())\nhierarchyChanged = Signal (connect_OBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"27295c75a3bb09d6a689b38e50d48bfc3a1c77b7","subject":"Doc fixes.","message":"Doc fixes.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Misc\/DrawingArea.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Misc\/DrawingArea.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget DrawingArea\n--\n-- Author : Axel Simon\n--\n-- Created: 22 September 2002\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-- A widget for custom user interface elements\n--\nmodule Graphics.UI.Gtk.Misc.DrawingArea (\n-- * Detail\n-- \n-- | The 'DrawingArea' widget is used for creating custom user interface\n-- elements. It's essentially a blank widget; you can draw on\n-- the 'Drawable' returned by 'drawingAreaGetDrawWindow'.\n--\n-- After creating a drawing area, the application may want to connect to:\n--\n-- * Mouse and button press signals to respond to input from the user.\n--\n-- * The 'realize' signal to take any necessary actions when the widget is\n-- instantiated on a particular display. (Create GDK resources in response to\n-- this signal.)\n--\n-- * The 'configureEvent' signal to take any necessary actions when the\n-- widget changes size.\n--\n-- * The 'exposeEvent' signal to handle redrawing the contents of the\n-- widget.\n--\n-- Expose events are normally delivered when a drawing area first comes\n-- onscreen, or when it's covered by another window and then uncovered\n-- (exposed). You can also force an expose event by adding to the \\\"damage\n-- region\\\" of the drawing area's window; 'widgetQueueDrawArea' and\n-- 'windowInvalidateRect' are equally good ways to do this. You\\'ll then get an\n-- expose event for the invalid region.\n--\n-- The available routines for drawing are documented on the GDK Drawing\n-- Primitives page.\n--\n-- To receive mouse events on a drawing area, you will need to enable them\n-- with 'widgetAddEvents'. To receive keyboard events, you will need to set the\n-- 'widgetCanFocus' attribute on the drawing area, and should probably draw some\n-- user-visible indication that the drawing area is focused.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----DrawingArea\n-- @\n\n-- * Types\n DrawingArea,\n DrawingAreaClass,\n castToDrawingArea,\n toDrawingArea,\n\n-- * Constructors\n drawingAreaNew,\n\n-- * Methods\n drawingAreaGetDrawWindow,\n drawingAreaGetSize\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.General.Structs\t(widgetGetDrawWindow, widgetGetSize)\n-- to make haddock happy:\nimport Graphics.UI.Gtk.Abstract.Widget\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new drawing area.\n--\ndrawingAreaNew :: IO DrawingArea\ndrawingAreaNew =\n makeNewObject mkDrawingArea $\n liftM (castPtr :: Ptr Widget -> Ptr DrawingArea) $\n {# call unsafe drawing_area_new #}\n\n-- | See 'widgetGetDrawWindow'\n--\ndrawingAreaGetDrawWindow :: DrawingArea -> IO DrawWindow\ndrawingAreaGetDrawWindow = widgetGetDrawWindow\n{-# DEPRECATED drawingAreaGetDrawWindow \"use widgetGetDrawWindow instead\" #-}\n\n-- | See 'widgetGetSize'\n--\ndrawingAreaGetSize :: DrawingArea -> IO (Int, Int)\ndrawingAreaGetSize = widgetGetSize\n{-# DEPRECATED drawingAreaGetSize \"use widgetGetSize instead\" #-}\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget DrawingArea\n--\n-- Author : Axel Simon\n--\n-- Created: 22 September 2002\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-- A widget for custom user interface elements\n--\nmodule Graphics.UI.Gtk.Misc.DrawingArea (\n-- * Detail\n-- \n-- | The 'DrawingArea' widget is used for creating custom user interface\n-- elements. It's essentially a blank widget; you can draw on\n-- the 'Drawable' returned by 'drawingAreaGetWindow'.\n--\n-- After creating a drawing area, the application may want to connect to:\n--\n-- * Mouse and button press signals to respond to input from the user. (Use\n-- 'widgetAddEvents' to enable events you wish to receive.)\n--\n-- * The \\\"realize\\\" signal to take any necessary actions when the widget is\n-- instantiated on a particular display. (Create GDK resources in response to\n-- this signal.)\n--\n-- * The \\\"configure_event\\\" signal to take any necessary actions when the\n-- widget changes size.\n--\n-- * The \\\"expose_event\\\" signal to handle redrawing the contents of the\n-- widget.\n--\n-- Expose events are normally delivered when a drawing area first comes\n-- onscreen, or when it's covered by another window and then uncovered\n-- (exposed). You can also force an expose event by adding to the \\\"damage\n-- region\\\" of the drawing area's window; 'widgetQueueDrawArea' and\n-- 'windowInvalidateRect' are equally good ways to do this. You\\'ll then get an\n-- expose event for the invalid region.\n--\n-- The available routines for drawing are documented on the GDK Drawing\n-- Primitives page. See also 'pixbufRenderToDrawable' for drawing a 'Pixbuf'.\n--\n-- To receive mouse events on a drawing area, you will need to enable them\n-- with 'widgetAddEvents'. To receive keyboard events, you will need to set the\n-- 'CanFocus' flag on the drawing area, and should probably draw some\n-- user-visible indication that the drawing area is focused.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----DrawingArea\n-- @\n\n-- * Types\n DrawingArea,\n DrawingAreaClass,\n castToDrawingArea,\n toDrawingArea,\n\n-- * Constructors\n drawingAreaNew,\n\n-- * Methods\n drawingAreaGetDrawWindow,\n drawingAreaGetSize\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.General.Structs\t(widgetGetDrawWindow, widgetGetSize)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new drawing area.\n--\ndrawingAreaNew :: IO DrawingArea\ndrawingAreaNew =\n makeNewObject mkDrawingArea $\n liftM (castPtr :: Ptr Widget -> Ptr DrawingArea) $\n {# call unsafe drawing_area_new #}\n\n-- | See 'widgetGetDrawWindow'\n--\ndrawingAreaGetDrawWindow :: DrawingArea -> IO DrawWindow\ndrawingAreaGetDrawWindow = widgetGetDrawWindow\n{-# DEPRECATED drawingAreaGetDrawWindow \"use widgetGetDrawWindow instead\" #-}\n\n-- | See 'widgetGetSize'\n--\ndrawingAreaGetSize :: DrawingArea -> IO (Int, Int)\ndrawingAreaGetSize = widgetGetSize\n{-# DEPRECATED drawingAreaGetSize \"use widgetGetSize instead\" #-}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a67e1ad10ecaef1aaafa835e8db5b979da90c44c","subject":"comments & stuff","message":"comments & stuff\n\nIgnore-this: ec695c2a1e37b4740063dbbf521e28fb\n\ndarcs-hash:20090721012419-115f9-33a331fab704bdb73063f171191a9438fc1711c0.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/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\n -- ** Dynamic allocation\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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. It is automatically freed.\n--\nnewtype DevicePtr = DevicePtr (ForeignPtr ())\n\nwithDevicePtr :: DevicePtr -> (Ptr () -> IO b) -> IO b\nwithDevicePtr (DevicePtr d) = withForeignPtr d\n\nnewDevicePtr :: FinalizerPtr () -> Ptr () -> IO DevicePtr\nnewDevicePtr fp p = newForeignPtr fp p >>= (return.DevicePtr)\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 :: Integer -> IO (Either String DevicePtr)\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> doAutoRelease free_ >>= \\fp ->\n newDevicePtr fp ptr >>= (return.Right)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 :: (Integer, Integer) -- ^ allocation (width,height) in bytes\n -> IO (Either String (DevicePtr,Integer))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease free_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 :: (Integer,Integer,Integer) -- ^ allocation (width,height,depth) in bytes\n -> IO (Either String (DevicePtr,Integer))\nmalloc3D = error \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr -> Integer -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr -- ^ The device memory\n -> (Integer,Integer) -- ^ The (width,height) of the matrix in bytes\n -> Integer -- ^ 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 = nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n `Int' ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise the elements of a 3D array to a given value\n--\nmemset3D :: DevicePtr -- ^ The device memory\n -> (Integer,Integer,Integer) -- ^ The (width,height,depth) of the array in bytes\n -> Integer -- ^ The allocation pitch, as returned by 'malloc3D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset3D = error \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- peek\n-- poke\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- newArray\n-- withArray\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 -> Integer -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n-- |\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Integer -- ^ number of bytes\n -> CopyDirection\n -> Stream\n -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\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\n -- ** Allocation\n malloc,\n malloc2D,\n memset,\n\n -- ** Marshalling\n\n -- ** Combined allocation and marshalling\n\n -- ** Copying\n memcpy,\n memcpyAsync,\n )\n where\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\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--\nnewtype DevicePtr = DevicePtr (ForeignPtr ())\n\nwithDevicePtr :: DevicePtr -> (Ptr () -> IO b) -> IO b\nwithDevicePtr (DevicePtr d) = withForeignPtr d\n\nnewDevicePtr :: FinalizerPtr () -> Ptr () -> IO DevicePtr\nnewDevicePtr fp p = newForeignPtr fp p >>= (return.DevicePtr)\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- 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 :: Integer -> IO (Either String DevicePtr)\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> doAutoRelease free_ >>= \\fp ->\n newDevicePtr fp ptr >>= (return.Right)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek* ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 :: Integer -- ^ width in bytes\n -> Integer -- ^ height in bytes\n -> IO (Either String (DevicePtr,Integer))\nmalloc2D width height = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease free_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ describe rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 width is returned\n--\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n-- free :: Ptr () -> IO (Maybe String)\n-- free p = nothingIfOk `fmap` cudaFree p\n\nfree_ :: Ptr () -> IO ()\nfree_ p = throwIf_ (\/= Success) (describe) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n-- |\n-- Copy data between host and device\n--\nmemcpy :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n-- |\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> Stream -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n-- |\n-- Initialize device memory to a given value\n--\nmemset :: DevicePtr -> Integer -> Int -> IO (Maybe String)\nmemset ptr bytes symbol = nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c7bbdbe5dc6025c8be33d57ab671b0f8a264446f","subject":"add thread synchronise function","message":"add thread synchronise function\n\nIgnore-this: 51b95fb4baeaede26439598a1e6d05a1\n\ndarcs-hash:20090720021919-115f9-afeaffebb6cb620dda2e12c4622d9dc853b6618c.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/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 -- Thread management\n --\n threadSynchronize,\n\n --\n -- Device management\n --\n chooseDevice,\n getDevice,\n getDeviceCount,\n getDeviceProperties,\n setDevice,\n setDeviceFlags,\n setValidDevices,\n\n --\n -- Memory management\n --\n malloc, mallocPitch,\n memcpy, memcpyAsync,\n memset,\n\n\n --\n -- Stream management\n --\n streamCreate,\n streamDestroy,\n streamQuery,\n streamSynchronize\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--------------------------------------------------------------------------------\n-- Thread Management\n--------------------------------------------------------------------------------\n\n--\n-- Block until the device has completed all preceding requests\n--\nthreadSynchronize :: IO (Maybe String)\nthreadSynchronize = nothingIfOk `fmap` cudaThreadSynchronize\n\n{# fun unsafe cudaThreadSynchronize\n { } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Select compute device which best matches criteria\n--\nchooseDevice :: DeviceProperties -> IO (Either String Int)\nchooseDevice dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n--\n-- Returns which device is currently being used\n--\ngetDevice :: IO (Either String Int)\ngetDevice = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\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* } -> `Status' 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' } -> `Status' 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' } -> `Status' cToEnum #}\n\n--\n-- Set flags to be used for device executions\n--\nsetDeviceFlags :: [DeviceFlags] -> IO (Maybe String)\nsetDeviceFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n--\n-- Set list of devices for CUDA execution in priority order\n--\nsetValidDevices :: [Int] -> IO (Maybe String)\nsetValidDevices l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\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--\n-- If the allocation is successful, it is marked to be automatically released\n-- when no longer needed.\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' } -> `Status' cToEnum #}\n\n--\n-- Allocate pitched memory on the device\n--\nmallocPitch :: Integer -> Integer -> IO (Either String (DevicePtr,Integer))\nmallocPitch width height = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ getErrorString rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n--\n-- Copy data between host and device\n--\nmemcpy :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n--\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> Stream -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Initialize device memory to a given value\n--\nmemset :: DevicePtr -> Integer -> Int -> IO (Maybe String)\nmemset ptr symbol bytes = nothingIfOk `fmap` cudaMemset ptr bytes symbol\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\n--\n-- Create an asynchronous stream\n--\nstreamCreate :: IO (Either String Stream)\nstreamCreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peek* } -> `Status' cToEnum #}\n\n--\n-- Destroy and clean up an asynchronous stream\n--\nstreamDestroy :: Stream -> IO (Maybe String)\nstreamDestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Determine if all operations in a stream have completed\n--\nstreamQuery :: Stream -> IO (Either String Bool)\nstreamQuery s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (getErrorString rv)\n\n{# fun unsafe cudaStreamQuery\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Block until all operations have been completed\n--\nstreamSynchronize :: Stream -> IO (Maybe String)\nstreamSynchronize s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\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 chooseDevice,\n getDevice,\n getDeviceCount,\n getDeviceProperties,\n setDevice,\n setDeviceFlags,\n setValidDevices,\n\n --\n -- Memory management\n --\n malloc, mallocPitch,\n memcpy, memcpyAsync,\n memset,\n\n\n --\n -- Stream management\n --\n streamCreate,\n streamDestroy,\n streamQuery,\n streamSynchronize\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--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Select compute device which best matches criteria\n--\nchooseDevice :: DeviceProperties -> IO (Either String Int)\nchooseDevice dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n--\n-- Returns which device is currently being used\n--\ngetDevice :: IO (Either String Int)\ngetDevice = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\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* } -> `Status' 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' } -> `Status' 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' } -> `Status' cToEnum #}\n\n--\n-- Set flags to be used for device executions\n--\nsetDeviceFlags :: [DeviceFlags] -> IO (Maybe String)\nsetDeviceFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n--\n-- Set list of devices for CUDA execution in priority order\n--\nsetValidDevices :: [Int] -> IO (Maybe String)\nsetValidDevices l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\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--\n-- If the allocation is successful, it is marked to be automatically released\n-- when no longer needed.\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' } -> `Status' cToEnum #}\n\n--\n-- Allocate pitched memory on the device\n--\nmallocPitch :: Integer -> Integer -> IO (Either String (DevicePtr,Integer))\nmallocPitch width height = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ getErrorString rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\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 ()' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n\n--\n-- Copy data between host and device\n--\nmemcpy :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n--\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> Stream -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Initialize device memory to a given value\n--\nmemset :: DevicePtr -> Integer -> Int -> IO (Maybe String)\nmemset ptr symbol bytes = nothingIfOk `fmap` cudaMemset ptr bytes symbol\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\n--\n-- Create an asynchronous stream\n--\nstreamCreate :: IO (Either String Stream)\nstreamCreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peek* } -> `Status' cToEnum #}\n\n--\n-- Destroy and clean up an asynchronous stream\n--\nstreamDestroy :: Stream -> IO (Maybe String)\nstreamDestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Determine if all operations in a stream have completed\n--\nstreamQuery :: Stream -> IO (Either String Bool)\nstreamQuery s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (getErrorString rv)\n\n{# fun unsafe cudaStreamQuery\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n--\n-- Block until all operations have been completed\n--\nstreamSynchronize :: Stream -> IO (Maybe String)\nstreamSynchronize s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { cIntConv `Stream' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"651b1bf0fa131bb5a214657022b6b89aa60515e6","subject":"Make safe calls to g_object_get_property This is too complex a function for use to be confident that it's ok to make an unsafe foreign call to it. This probably does not fix Axel's current segfault bug.","message":"Make safe calls to g_object_get_property\nThis is too complex a function for use to be confident that it's ok to make an\nunsafe foreign call to it.\nThis probably does not fix Axel's current segfault bug.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,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 objectSetPropertyGObject,\n objectGetPropertyGObject,\n \n objectSetPropertyInternal,\n objectGetPropertyInternal,\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 newAttrFromMaybeStringProperty,\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 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\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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString 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 objectSetPropertyGObject,\n objectGetPropertyGObject,\n \n objectSetPropertyInternal,\n objectGetPropertyInternal,\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 newAttrFromMaybeStringProperty,\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\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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString 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":"2cdd8c1b374cc6236eb8e057b902ba7ff14af69d","subject":"Use withMVar instead of bracket","message":"Use withMVar instead of bracket\n","repos":"abbradar\/MySDL","old_file":"src\/Graphics\/UI\/SDL\/Video\/Keyboard.chs","new_file":"src\/Graphics\/UI\/SDL\/Video\/Keyboard.chs","new_contents":"{-# LANGUAGE TemplateHaskell #-}\n\nmodule Graphics.UI.SDL.Video.Keyboard\n ( keyName\n , keyFromName\n , scancodeName\n , scancodeFromName\n , scancodeFromKey\n , keyFromScancode\n\n , startTextInput\n , stopTextInput\n , setTextInputRect\n ) where\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM)\nimport Control.Concurrent.MVar.Lifted ( MVar\n , newMVar\n , takeMVar\n , putMVar\n , withMVar\n )\nimport Control.Exception (bracket_)\nimport Control.Monad.Base (liftBase)\nimport Data.ByteString (ByteString, packCString, useAsCString)\nimport qualified Data.ByteString as B\nimport Data.ByteString.Unsafe (unsafePackCString)\nimport System.IO.Unsafe (unsafePerformIO, unsafeDupablePerformIO)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr)\nimport Control.Lens.TH (makeLenses)\n\nimport Graphics.UI.SDL.Internal.Prim\nimport Graphics.UI.SDL.Video.Internal.Surface\nimport Graphics.UI.SDL.Class\n\n{#import Graphics.UI.SDL.Video.Keyboard.Types #}\n\n#include \n\n-- This function needs to be guarded to be thread-safe. Global variables!\nkeyNameGuard :: MVar ()\n{-# NOINLINE keyNameGuard #-}\nkeyNameGuard = unsafePerformIO $ newMVar ()\n\nkeyName :: KeyCode -> ByteString\nkeyName c = unsafeDupablePerformIO $ withMVar keyNameGuard $ const $\n sdlCall \"SDL_GetKeyName\" (sDLGetKeyName $ fromEnum c) (not . B.null)\n where {#fun unsafe SDL_GetKeyName as ^\n {`Int'} -> `ByteString' packCString* #}\n\nkeyFromName :: ByteString -> KeyCode\nkeyFromName c = unsafeDupablePerformIO $ sdlCall \"SDL_GetKeyFromName\"\n (toEnum <$> sDLGetKeyFromName c) (\/= SdlkUnknown)\n where {#fun unsafe SDL_GetKeyFromName as ^\n {useAsCString* `ByteString'} -> `Int' #}\n\n-- Unlike 'keyName', this is thread-safe\nscancodeName :: ScanCode -> ByteString\nscancodeName c = unsafeDupablePerformIO $\n sdlCall \"SDL_GetScancodeName\" (sDLGetScancodeName $ fromEnum c) (not . B.null)\n where {#fun unsafe SDL_GetScancodeName as ^\n {`Int'} -> `ByteString' unsafePackCString* #}\n\nscancodeFromName :: ByteString -> ScanCode\nscancodeFromName c = unsafeDupablePerformIO $ sdlCall \"SDL_GetScancodeFromName\"\n (toEnum <$> sDLGetScancodeFromName c) (\/= SdlScancodeUnknown)\n where {#fun unsafe SDL_GetScancodeFromName as ^\n {useAsCString* `ByteString'} -> `Int' #}\n\nscancodeFromKey :: MonadSDLVideo m => KeyCode -> m ScanCode\nscancodeFromKey = liftBase . liftM toEnum . sDLGetScancodeFromKey . fromEnum\n where {#fun unsafe SDL_GetScancodeFromKey as ^\n {`Int'} -> `Int' #}\n\nkeyFromScancode :: MonadSDLVideo m => ScanCode -> m KeyCode\nkeyFromScancode = liftBase . liftM toEnum . sDLGetKeyFromScancode . fromEnum\n where {#fun unsafe SDL_GetKeyFromScancode as ^\n {`Int'} -> `Int' #}\n\nstartTextInput :: MonadSDLVideo m => m ()\nstartTextInput = liftBase {#call unsafe SDL_StartTextInput as ^ #}\n\nstopTextInput :: MonadSDLVideo m => m ()\nstopTextInput = liftBase {#call unsafe SDL_StopTextInput as ^ #}\n\nsetTextInputRect :: MonadSDLVideo m => Rect -> m ()\nsetTextInputRect r = liftBase $ withCRect r {#call unsafe SDL_SetTextInputRect as ^ #}\n","old_contents":"{-# LANGUAGE TemplateHaskell #-}\n\nmodule Graphics.UI.SDL.Video.Keyboard\n ( keyName\n , keyFromName\n , scancodeName\n , scancodeFromName\n , scancodeFromKey\n , keyFromScancode\n\n , startTextInput\n , stopTextInput\n , setTextInputRect\n ) where\n\nimport Control.Applicative ((<$>))\nimport Control.Monad (liftM)\nimport Control.Concurrent.MVar (MVar,\n newMVar,\n takeMVar,\n putMVar)\nimport Control.Exception (bracket_)\nimport Control.Monad.Base (liftBase)\nimport Data.ByteString (ByteString, packCString, useAsCString)\nimport qualified Data.ByteString as B\nimport Data.ByteString.Unsafe (unsafePackCString)\nimport System.IO.Unsafe (unsafePerformIO, unsafeDupablePerformIO)\nimport Foreign.C.Types (CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr)\nimport Control.Lens.TH (makeLenses)\n\nimport Graphics.UI.SDL.Internal.Prim\nimport Graphics.UI.SDL.Video.Internal.Surface\nimport Graphics.UI.SDL.Class\n\n{#import Graphics.UI.SDL.Video.Keyboard.Types #}\n\n#include \n\n-- This function needs to be guarded to be thread-safe. Global variables!\nkeyNameGuard :: MVar ()\n{-# NOINLINE keyNameGuard #-}\nkeyNameGuard = unsafePerformIO $ newMVar ()\n\nkeyName :: KeyCode -> ByteString\nkeyName c = unsafeDupablePerformIO $ bracket_\n (takeMVar keyNameGuard)\n (putMVar keyNameGuard ())\n $ sdlCall \"SDL_GetKeyName\" (sDLGetKeyName $ fromEnum c) (not . B.null)\n where {#fun unsafe SDL_GetKeyName as ^\n {`Int'} -> `ByteString' packCString* #}\n\nkeyFromName :: ByteString -> KeyCode\nkeyFromName c = unsafeDupablePerformIO $ sdlCall \"SDL_GetKeyFromName\"\n (toEnum <$> sDLGetKeyFromName c) (\/= SdlkUnknown)\n where {#fun unsafe SDL_GetKeyFromName as ^\n {useAsCString* `ByteString'} -> `Int' #}\n\n-- Unlike 'keyName', this is thread-safe\nscancodeName :: ScanCode -> ByteString\nscancodeName c = unsafeDupablePerformIO $\n sdlCall \"SDL_GetScancodeName\" (sDLGetScancodeName $ fromEnum c) (not . B.null)\n where {#fun unsafe SDL_GetScancodeName as ^\n {`Int'} -> `ByteString' unsafePackCString* #}\n\nscancodeFromName :: ByteString -> ScanCode\nscancodeFromName c = unsafeDupablePerformIO $ sdlCall \"SDL_GetScancodeFromName\"\n (toEnum <$> sDLGetScancodeFromName c) (\/= SdlScancodeUnknown)\n where {#fun unsafe SDL_GetScancodeFromName as ^\n {useAsCString* `ByteString'} -> `Int' #}\n\nscancodeFromKey :: MonadSDLVideo m => KeyCode -> m ScanCode\nscancodeFromKey = liftBase . liftM toEnum . sDLGetScancodeFromKey . fromEnum\n where {#fun unsafe SDL_GetScancodeFromKey as ^\n {`Int'} -> `Int' #}\n\nkeyFromScancode :: MonadSDLVideo m => ScanCode -> m KeyCode\nkeyFromScancode = liftBase . liftM toEnum . sDLGetKeyFromScancode . fromEnum\n where {#fun unsafe SDL_GetKeyFromScancode as ^\n {`Int'} -> `Int' #}\n\nstartTextInput :: MonadSDLVideo m => m ()\nstartTextInput = liftBase {#call unsafe SDL_StartTextInput as ^ #}\n\nstopTextInput :: MonadSDLVideo m => m ()\nstopTextInput = liftBase {#call unsafe SDL_StopTextInput as ^ #}\n\nsetTextInputRect :: MonadSDLVideo m => Rect -> m ()\nsetTextInputRect r = liftBase $ withCRect r {#call unsafe SDL_SetTextInputRect as ^ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"513e17c3772b3ece99dcae5a8f018c4570658138","subject":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members","message":"gstreamer: M.S.G.Core.Iterator: export IteratorResult members\n\ndarcs-hash:20081017155227-21862-09c60af5d3ea126ef69e10829d9843059afbc4aa.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Iterator.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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult(..),\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\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.Iterator (\n \n Iterator,\n Iterable,\n IteratorFilter,\n IteratorFoldFunction,\n IteratorResult,\n \n iteratorNext,\n iteratorResync,\n iteratorFilter,\n iteratorFold,\n iteratorForeach,\n iteratorFind\n \n ) where\n\n{#import Media.Streaming.GStreamer.Core.Types#}\n\nimport Data.Maybe (fromJust)\nimport System.Glib.FFI\n{#import System.Glib.GValue#}\nimport Data.IORef\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\niteratorNext :: Iterable a\n => Iterator a\n -> IO (IteratorResult, Maybe a)\niteratorNext (Iterator iterator) =\n alloca $ \\elemPtr ->\n do result <- {# call iterator_next #} iterator elemPtr\n obj <- peek elemPtr >>= maybePeek peekIterable\n return (toEnum $ fromIntegral result, obj)\n\niteratorResync :: Iterator a\n -> IO ()\niteratorResync (Iterator iterator) =\n {# call iterator_resync #} iterator\n\ntype CIteratorFilter = {# type gpointer #}\n -> {# type gpointer #}\n -> IO {# type gint #}\nmarshalIteratorFilter :: Iterable a\n => IteratorFilter a\n -> IO {# type GCompareFunc #}\nmarshalIteratorFilter iteratorFilter =\n makeIteratorFilter cIteratorFilter\n where cIteratorFilter elementPtr _ =\n do include <- peekIterable elementPtr >>= iteratorFilter\n return $ if include then 1 else 0\nforeign import ccall \"wrapper\"\n makeIteratorFilter :: CIteratorFilter\n -> IO {# type GCompareFunc #}\n\niteratorFilter :: Iterable a\n => Iterator a\n -> IteratorFilter a\n -> IO (Iterator a)\niteratorFilter (Iterator iterator) filter =\n do cFilter <- marshalIteratorFilter filter\n {# call iterator_filter #} iterator cFilter nullPtr >>=\n takeIterator\n\n{- type IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Maybe accumT) -}\ntype CIteratorFoldFunction = {# type gpointer #}\n -> GValue\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalIteratorFoldFunction :: Iterable itemT\n => IteratorFoldFunction itemT accumT\n -> IORef accumT\n -> IO {# type GstIteratorFoldFunction #}\nmarshalIteratorFoldFunction iteratorFoldFunction accumRef =\n makeIteratorFoldFunction cIteratorFoldFunction\n where cIteratorFoldFunction :: CIteratorFoldFunction\n cIteratorFoldFunction itemPtr _ _ =\n do item <- peekIterable itemPtr\n accum <- readIORef accumRef\n (continue, accum') <- iteratorFoldFunction item accum\n writeIORef accumRef accum'\n return $ fromBool continue\nforeign import ccall \"wrapper\"\n makeIteratorFoldFunction :: CIteratorFoldFunction\n -> IO {# type GstIteratorFoldFunction #}\n\niteratorFold :: Iterable itemT\n => Iterator itemT\n -> accumT\n -> IteratorFoldFunction itemT accumT\n -> IO (IteratorResult, accumT)\niteratorFold (Iterator iterator) init func =\n do accumRef <- newIORef init\n func' <- marshalIteratorFoldFunction func accumRef\n result <- {# call iterator_fold #} iterator\n func'\n (GValue nullPtr)\n nullPtr\n freeHaskellFunPtr func'\n accum <- readIORef accumRef\n return (toEnum $ fromIntegral result, accum)\n\niteratorForeach :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO ())\n -> IO IteratorResult\niteratorForeach iterator func =\n do (result, _) <- iteratorFold iterator () $ \\item _ ->\n func item >> return (True, ())\n return result\n\niteratorFind :: Iterable itemT\n => Iterator itemT\n -> (itemT -> IO Bool)\n -> IO (IteratorResult, Maybe itemT)\niteratorFind iterator pred =\n iteratorFold iterator Nothing $ \\item accum ->\n do found <- pred item\n if found\n then return (False, Just item)\n else return (True, accum)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"77f9bbb3f1e275be44da98b519dcb1f404ec566a","subject":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO","message":"gio: System.GIO.File: add more functions; make the functions that do no IO use unsafePerformIO","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-- \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 ) 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\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\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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"aa27441d6ea3a30d8a5348b712aa95321dcb3fc8","subject":"Fixes","message":"Fixes\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\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 if res == 0\n then fmap (Right . Repository) $ peek pprepo\n else return . Left . toEnum . fromIntegral $ res\n\n{-\ndo\n let repo = nullPtr\n pstr <- newCString path\n res <- {#call git_repository_open#} repo pstr\n return $ case res of\n 0 -> Right $ Repository repo\n n -> Left . toEnum . fromIntegral $ n\n-}\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\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.Primitive\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype Ptr2Int = Ptr () -> IO CInt\n\nnewtype ObjDB = ObjDB { unODB :: Ptr () }\nnewtype Repository = Repository { unRepository :: Ptr () }\nnewtype Index = Index { unIndex :: Ptr () }\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\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = do\n pstr <- newCString path\n res <- {#call git_repository_open#} nullPtr pstr\n return $ case res of\n 0 -> Right repo\n n -> Left . toEnum . fromIntegral $ n\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = undefined -- git_repository_open2\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir db idxFile workTree = undefined -- git_repository_open3\n\n-- TODO: size? GIT_EXTERN(int) git_repository_discover(char *repository_path, size_t size, const char *start_path, int across_fs, const char *ceiling_dirs);\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = undefined -- git_repository_discover\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex repo = undefined -- git_repository_index\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> Either GitError Repository\ninit path isBare = undefined -- git_repository_init\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 = return . undefined =<< {#call git_repository_path#} r (fromIntegral $ fromEnum pathID)\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ecd6e1d52531e1d5e94022e8443592e9f3ecbe0e","subject":"refs #8: add clCreateImage3D","message":"refs #8: add clCreateImage3D\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(..),\n -- * Memory Functions\n clCreateBuffer, clRetainMemObject, clReleaseMemObject, clGetMemType, \n clGetMemFlags, clGetMemSize, clGetMemHostPtr, clGetMemMapCount, \n clGetMemReferenceCount, clGetMemContext,\n -- * Image Functions\n clCreateImage2D, clCreateImage3D,\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, getEnumCL, bitmaskFromFlags, \n 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\n--foreign 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} #}\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} #}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\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#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,\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, getEnumCL, bitmaskFromFlags, \n 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\n--foreign 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\n--foreign 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} #}\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} #}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\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#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":"010502e0888b6ed524d2feeb0d745c5cde0e882b","subject":"Add function `documentGetAttachments`","message":"Add function `documentGetAttachments`\n","repos":"wavewave\/poppler,gtk2hs\/poppler","old_file":"Graphics\/UI\/Gtk\/Poppler\/Document.chs","new_file":"Graphics\/UI\/Gtk\/Poppler\/Document.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Document (\n-- * Details\n--\n-- | The PopplerDocument is an object used to refer to a main document.\n\n-- * Types\n Document,\n\n-- * Methods\n documentNewFromFile, \n documentNewFromData,\n documentSave,\n documentGetNPages,\n documentGetPage,\n documentGetPageByLabel,\n documentFindDest,\n documentHasAttachments,\n documentGetAttachments,\n documentGetFormField,\n\n psFileNew,\n psFileSetPaperSize,\n psFileSetDuplex,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GList\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\n{#import Graphics.UI.Gtk.Poppler.Types#}\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Creates a new PopplerDocument. If 'Nothing' is returned, then error will be set. Possible errors include\n-- those in the PopplerError and GFileError domains.\ndocumentNewFromFile :: \n String -- ^ @uri@ uri of the file to load \n -> Maybe String -- ^ @password@ password to unlock the file with, or 'Nothing' \n -> IO (Maybe Document) -- ^ returns A newly created PopplerDocument, or 'Nothing' \ndocumentNewFromFile uri password = \n maybeNull (makeNewGObject mkDocument) $\n withUTFString uri $ \\ uriPtr -> \n maybeWith withUTFString password $ \\ passwordPtr -> \n propagateGError ({# call poppler_document_new_from_file #} \n uriPtr\n passwordPtr)\n\n-- | Creates a new PopplerDocument. If 'Nothing' is returned, then error will be set. Possible errors include\n-- those in the PopplerError and GFileError domains.\ndocumentNewFromData :: \n String -- ^ @data@ the pdf data contained in a char array \n -> Maybe String -- ^ @password@ password to unlock the file with, or 'Nothing' \n -> IO (Maybe Document) -- ^ returns A newly created PopplerDocument, or 'Nothing' \ndocumentNewFromData dat password = \n maybeNull (makeNewGObject mkDocument) $\n withUTFString dat $ \\ datPtr -> \n maybeWith withUTFString password $ \\ passwordPtr -> \n propagateGError ({#call poppler_document_new_from_data #}\n datPtr\n (fromIntegral (length dat))\n passwordPtr)\n\n-- | Saves document. Any change made in the document such as form fields filled by the user will be\n-- saved. If error is set, 'False' will be returned. Possible errors include those in the GFileError\n-- domain.\ndocumentSave :: DocumentClass doc => doc \n -> String -- ^ @uri@ uri of file to save \n -> IO Bool -- ^ returns 'True', if the document was successfully saved \ndocumentSave doc uri = \n liftM toBool $\n withUTFString uri $ \\ uriPtr -> \n propagateGError ({#call poppler_document_save #}\n (toDocument doc)\n uriPtr)\n\n-- | Returns the number of pages in a loaded document.\ndocumentGetNPages :: DocumentClass doc => doc\n -> IO Int -- ^ returns Number of pages \ndocumentGetNPages doc = \n liftM fromIntegral $ \n {#call poppler_document_get_n_pages #} (toDocument doc)\n\n-- | Returns the PopplerPage indexed at index. This object is owned by the caller.\n-- | PopplerPages are indexed starting at 0.\ndocumentGetPage :: DocumentClass doc => doc\n -> Int -- ^ @index@ a page index \n -> IO Page -- ^ returns The PopplerPage at index \ndocumentGetPage doc index = \n makeNewGObject mkPage $ \n {#call poppler_document_get_page#} (toDocument doc) (fromIntegral index)\n \n-- | Returns the PopplerPage reference by label. This object is owned by the caller. label is a\n-- human-readable string representation of the page number, and can be document specific. Typically, it\n-- is a value such as \"iii\" or \"3\".\n-- \n-- By default, \"1\" refers to the first page.\ndocumentGetPageByLabel :: DocumentClass doc => doc\n -> String -- ^ @label@ a page label \n -> IO Page -- ^ returns The PopplerPage referenced by label \ndocumentGetPageByLabel doc label = \n makeNewGObject mkPage $ \n withUTFString label $ \\ labelPtr -> \n {#call poppler_document_get_page_by_label #} (toDocument doc) labelPtr\n\n-- | Finds named destination @linkName@ in document\ndocumentFindDest :: DocumentClass doc => doc \n -> String -- ^ @linkName@ a named destination\n -> IO (Maybe Dest) -- ^ returns The PopplerDest destination or 'Nothing' if @linkName@ is not a destination. \ndocumentFindDest doc linkName = \n withUTFString linkName $ \\ linkNamePtr -> do\n destPtr <- {#call poppler_document_find_dest #}\n (toDocument doc)\n linkNamePtr\n if destPtr == nullPtr\n then return Nothing\n else do\n dest <- makeNewGObject mkDest $ return destPtr\n {#call unsafe poppler_dest_free #} dest\n return $ Just dest\n \n-- | Returns 'True' of document has any attachments.\ndocumentHasAttachments :: DocumentClass doc => doc\n -> IO Bool -- ^ returns 'True', if document has attachments. \ndocumentHasAttachments doc = \n liftM toBool $\n {#call poppler_document_has_attachments #} (toDocument doc)\n\n-- | Returns the PopplerFormField for the given id.\ndocumentGetFormField :: DocumentClass doc => doc\n -> Int -- ^ @id@ an id of a PopplerFormField \n -> IO (Maybe FormField)\ndocumentGetFormField doc id = \n maybeNull (makeNewGObject mkFormField) $\n {#call poppler_document_get_form_field #} \n (toDocument doc) \n (fromIntegral id)\n\n-- | Create a new postscript file to render to\npsFileNew :: DocumentClass doc => doc\n -> String -- ^ @filename@ the path of the output filename \n -> Int -- ^ @firstPage@ the first page to print \n -> Int -- ^ @nPages@ the number of pages to print \n -> IO PSFile\npsFileNew doc filename firstPage nPages = \n makeNewGObject mkPSFile $ \n withUTFString filename $ \\ filenamePtr -> \n {#call poppler_ps_file_new #}\n (toDocument doc)\n filenamePtr\n (fromIntegral firstPage)\n (fromIntegral nPages)\n \n-- | Set the output paper size. These values will end up in the DocumentMedia, the BoundingBox DSC\n-- comments and other places in the generated PostScript.\npsFileSetPaperSize :: PSFileClass file => \n file -- ^ @psFile@ a PopplerPSFile which was not yet printed to. \n -> Double -- ^ @width@ the paper width in 1\/72 inch \n -> Double -- ^ @height@ the paper height in 1\/72 inch \n -> IO () \npsFileSetPaperSize psFile width height = \n {#call poppler_ps_file_set_paper_size #}\n (toPSFile psFile)\n (realToFrac width)\n (realToFrac height)\n\n-- | Enable or disable Duplex printing.\npsFileSetDuplex :: PSFileClass file => \n file -- ^ @psFile@ a PopplerPSFile which was not yet printed to \n -> Bool -- ^ @duplex@ whether to force duplex printing (on printers which support this)\n -> IO ()\npsFileSetDuplex psFile duplex =\n {#call poppler_ps_file_set_duplex#}\n (toPSFile psFile)\n (fromBool duplex)\n\n-- | Returns a GList containing PopplerAttachments.\ndocumentGetAttachments :: DocumentClass doc => doc\n -> IO [Attachment]\ndocumentGetAttachments doc = do\n glistPtr <- {#call poppler_document_get_attachments #} (toDocument doc)\n list <- fromGList glistPtr\n attachs <- mapM (makeNewGObject mkAttachment . return) list\n {#call unsafe g_list_free #} glistPtr\n return attachs\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to poppler -*-haskell-*-\n--\n-- Author : Andy Stewart\n-- Created: 18-Jun-2010\n--\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-- POPPLER, 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 POPPLER documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Graphics.UI.Gtk.Poppler.Document (\n-- * Details\n--\n-- | The PopplerDocument is an object used to refer to a main document.\n\n-- * Types\n Document,\n\n-- * Methods\n documentNewFromFile, \n documentNewFromData,\n documentSave,\n documentGetNPages,\n documentGetPage,\n documentGetPageByLabel,\n documentFindDest,\n documentHasAttachments,\n documentGetFormField,\n\n psFileNew,\n psFileSetPaperSize,\n psFileSetDuplex,\n ) where\n\nimport Control.Monad\nimport Data.Typeable\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.GObject\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Poppler.Enums\n{#import Graphics.UI.Gtk.Poppler.Types#}\n\n{# context lib=\"poppler\" prefix=\"poppler\" #}\n\n-- | Creates a new PopplerDocument. If 'Nothing' is returned, then error will be set. Possible errors include\n-- those in the PopplerError and GFileError domains.\ndocumentNewFromFile :: \n String -- ^ @uri@ uri of the file to load \n -> Maybe String -- ^ @password@ password to unlock the file with, or 'Nothing' \n -> IO (Maybe Document) -- ^ returns A newly created PopplerDocument, or 'Nothing' \ndocumentNewFromFile uri password = \n maybeNull (makeNewGObject mkDocument) $\n withUTFString uri $ \\ uriPtr -> \n maybeWith withUTFString password $ \\ passwordPtr -> \n propagateGError ({# call poppler_document_new_from_file #} \n uriPtr\n passwordPtr)\n\n-- | Creates a new PopplerDocument. If 'Nothing' is returned, then error will be set. Possible errors include\n-- those in the PopplerError and GFileError domains.\ndocumentNewFromData :: \n String -- ^ @data@ the pdf data contained in a char array \n -> Maybe String -- ^ @password@ password to unlock the file with, or 'Nothing' \n -> IO (Maybe Document) -- ^ returns A newly created PopplerDocument, or 'Nothing' \ndocumentNewFromData dat password = \n maybeNull (makeNewGObject mkDocument) $\n withUTFString dat $ \\ datPtr -> \n maybeWith withUTFString password $ \\ passwordPtr -> \n propagateGError ({#call poppler_document_new_from_data #}\n datPtr\n (fromIntegral (length dat))\n passwordPtr)\n\n-- | Saves document. Any change made in the document such as form fields filled by the user will be\n-- saved. If error is set, 'False' will be returned. Possible errors include those in the GFileError\n-- domain.\ndocumentSave :: DocumentClass doc => doc \n -> String -- ^ @uri@ uri of file to save \n -> IO Bool -- ^ returns 'True', if the document was successfully saved \ndocumentSave doc uri = \n liftM toBool $\n withUTFString uri $ \\ uriPtr -> \n propagateGError ({#call poppler_document_save #}\n (toDocument doc)\n uriPtr)\n\n-- | Returns the number of pages in a loaded document.\ndocumentGetNPages :: DocumentClass doc => doc\n -> IO Int -- ^ returns Number of pages \ndocumentGetNPages doc = \n liftM fromIntegral $ \n {#call poppler_document_get_n_pages #} (toDocument doc)\n\n-- | Returns the PopplerPage indexed at index. This object is owned by the caller.\n-- | PopplerPages are indexed starting at 0.\ndocumentGetPage :: DocumentClass doc => doc\n -> Int -- ^ @index@ a page index \n -> IO Page -- ^ returns The PopplerPage at index \ndocumentGetPage doc index = \n makeNewGObject mkPage $ \n {#call poppler_document_get_page#} (toDocument doc) (fromIntegral index)\n \n-- | Returns the PopplerPage reference by label. This object is owned by the caller. label is a\n-- human-readable string representation of the page number, and can be document specific. Typically, it\n-- is a value such as \"iii\" or \"3\".\n-- \n-- By default, \"1\" refers to the first page.\ndocumentGetPageByLabel :: DocumentClass doc => doc\n -> String -- ^ @label@ a page label \n -> IO Page -- ^ returns The PopplerPage referenced by label \ndocumentGetPageByLabel doc label = \n makeNewGObject mkPage $ \n withUTFString label $ \\ labelPtr -> \n {#call poppler_document_get_page_by_label #} (toDocument doc) labelPtr\n\n-- | Finds named destination @linkName@ in document\ndocumentFindDest :: DocumentClass doc => doc \n -> String -- ^ @linkName@ a named destination\n -> IO (Maybe Dest) -- ^ returns The PopplerDest destination or 'Nothing' if @linkName@ is not a destination. \ndocumentFindDest doc linkName = \n withUTFString linkName $ \\ linkNamePtr -> do\n destPtr <- {#call poppler_document_find_dest #}\n (toDocument doc)\n linkNamePtr\n if destPtr == nullPtr\n then return Nothing\n else do\n dest <- makeNewGObject mkDest $ return destPtr\n {#call unsafe poppler_dest_free #} dest\n return $ Just dest\n \n-- | Returns 'True' of document has any attachments.\ndocumentHasAttachments :: DocumentClass doc => doc\n -> IO Bool -- ^ returns 'True', if document has attachments. \ndocumentHasAttachments doc = \n liftM toBool $\n {#call poppler_document_has_attachments #} (toDocument doc)\n\n-- | Returns the PopplerFormField for the given id.\ndocumentGetFormField :: DocumentClass doc => doc\n -> Int -- ^ @id@ an id of a PopplerFormField \n -> IO (Maybe FormField)\ndocumentGetFormField doc id = \n maybeNull (makeNewGObject mkFormField) $\n {#call poppler_document_get_form_field #} \n (toDocument doc) \n (fromIntegral id)\n\n-- | Create a new postscript file to render to\npsFileNew :: DocumentClass doc => doc\n -> String -- ^ @filename@ the path of the output filename \n -> Int -- ^ @firstPage@ the first page to print \n -> Int -- ^ @nPages@ the number of pages to print \n -> IO PSFile\npsFileNew doc filename firstPage nPages = \n makeNewGObject mkPSFile $ \n withUTFString filename $ \\ filenamePtr -> \n {#call poppler_ps_file_new #}\n (toDocument doc)\n filenamePtr\n (fromIntegral firstPage)\n (fromIntegral nPages)\n \n-- | Set the output paper size. These values will end up in the DocumentMedia, the BoundingBox DSC\n-- comments and other places in the generated PostScript.\npsFileSetPaperSize :: PSFileClass file => \n file -- ^ @psFile@ a PopplerPSFile which was not yet printed to. \n -> Double -- ^ @width@ the paper width in 1\/72 inch \n -> Double -- ^ @height@ the paper height in 1\/72 inch \n -> IO () \npsFileSetPaperSize psFile width height = \n {#call poppler_ps_file_set_paper_size #}\n (toPSFile psFile)\n (realToFrac width)\n (realToFrac height)\n\n-- | Enable or disable Duplex printing.\npsFileSetDuplex :: PSFileClass file => \n file -- ^ @psFile@ a PopplerPSFile which was not yet printed to \n -> Bool -- ^ @duplex@ whether to force duplex printing (on printers which support this)\n -> IO ()\npsFileSetDuplex psFile duplex =\n {#call poppler_ps_file_set_duplex#}\n (toPSFile psFile)\n (fromBool duplex)","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7d60d96b99a600aa1c06bcb4b9233da1a61c92ed","subject":"Fix docu.","message":"Fix docu.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'keyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b835636a14b2182d803fe81e30c8a4afa2992bb2","subject":"storable instance for CInMemoryBuffer","message":"storable instance for CInMemoryBuffer\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface,\n EmptyDataDecls\n #-}\nmodule Network.LibRSync.Internal where\n\nimport Control.Applicative((<$>),(<*>))\nimport Control.Monad\n\nimport Data.ByteString\nimport Data.Conduit\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\nimport Foreign.Marshal.Alloc\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \"internal.h\"\n\n-- #include \"..\/..\/..\/c_src\/internal.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ndata CInMemoryBuffer = CInMemoryBuffer (Ptr CChar) CSize CSize\n\n{#pointer *inMemoryBuffer_t as CInMemoryBufferPtr -> CInMemoryBuffer #}\n\ninstance Storable CInMemoryBuffer where\n sizeOf = const {#sizeof inMemoryBuffer_t #}\n alignment = const 4\n peek p = CInMemoryBuffer\n <$> {#get inMemoryBuffer_t->buffer #} p\n <*> liftM fromIntegral ({#get inMemoryBuffer_t->size #} p)\n <*> liftM fromIntegral ({#get inMemoryBuffer_t->inUse #} p)\n poke = undefined\n\n\n\ngetData :: CInMemoryBuffer -> IO ByteString\ngetData (CInMemoryBuffer xs _ s) = packCStringLen (xs,fromIntegral s)\n\n\n\n\n\n\n-- data CRSFileBuf = CRSFileBuf (Ptr CFile) CSize\n\n-- {#pointer *rs_filebuf_t as CRSFileBufPtr -> CRSFileBuf #}\n\ndata CJob\ndata CBuffers\ndata CRSFileBuf\n\ndata CRSyncSourceState = CRSyncSourceState { f :: Ptr CFile\n , job :: Ptr CJob\n , buf :: Ptr CBuffers\n , inBuf :: Ptr CRSFileBuf\n , outputBuf :: CInMemoryBufferPtr\n }\n\ninstance Storable CRSyncSourceState where\n sizeOf = const {#sizeof rsyncSourceState_t #}\n alignment = const 4\n peek = undefined\n poke = undefined\n\n\n{#pointer *rsyncSourceState_t as CRSyncSourceStatePtr -> CRSyncSourceState #}\n\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype RSyncSourceState = CRSyncSourceStatePtr\n\ntype Signature = ByteString\n\n\nstartSignature :: FilePath -> IO RSyncSourceState\nstartSignature path = do\n state <- malloc :: IO (Ptr CRSyncSourceState)\n rsres <- cStartSignature path state\n return state\n -- TODO: check what to do with rsres\n -- case rsres of\n -- RsDone ->\n\nendSignature :: RSyncSourceState -> IO ()\nendSignature state = cEndSignature state >> free state\n\nsignatureSource :: MonadResource m => RSyncSourceState -> Source m Signature\nsignatureSource state = undefined -- do\n -- (CInMemoryBuffer xs size inUse) <- {#get inMemorybuffer->outputBuf-> state\n\n\n\n\n\n\n\n{#fun unsafe startSignature as cStartSignature\n { `String' -- FilePath\n , id `CRSyncSourceStatePtr'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe signatureChunk as cSignatureChunk\n { id `CRSyncSourceStatePtr'\n , `Bool'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe endSignature as cEndSignature\n { id `CRSyncSourceStatePtr'\n } -> `()'\n #}\n\n\n-- type Signature = ByteString\n\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface,\n EmptyDataDecls\n #-}\nmodule Network.LibRSync.Internal where\n\nimport Data.ByteString\nimport Data.Conduit\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\nimport Foreign.Marshal.Alloc\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \"internal.h\"\n\n-- #include \"..\/..\/..\/c_src\/internal.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ndata CInMemoryBuffer = CInMemoryBuffer (Ptr Char) CSize CSize\n\n{#pointer *inMemoryBuffer_t as CInMemoryBufferPtr -> CInMemoryBuffer #}\n\n\ngetData :: CInMemoryBuffer -> IO ByteString\ngetData (CInMemoryBuffer xs _ s) = packCStringLen (xs,s)\n\n\n\n\n-- data CRSFileBuf = CRSFileBuf (Ptr CFile) CSize\n\n-- {#pointer *rs_filebuf_t as CRSFileBufPtr -> CRSFileBuf #}\n\ndata CJob\ndata CBuffers\ndata CRSFileBuf\n\ndata CRSyncSourceState = CRSyncSourceState { f :: Ptr CFile\n , job :: Ptr CJob\n , buf :: Ptr CBuffers\n , inBuf :: Ptr CRSFileBuf\n , outputBuf :: CInMemoryBufferPtr\n }\n\ninstance Storable CRSyncSourceState where\n sizeOf _ = {#sizeof rsyncSourceState_t #}\n alignment = undefined\n peek = undefined\n poke = undefined\n\n\n{#pointer *rsyncSourceState_t as CRSyncSourceStatePtr -> CRSyncSourceState #}\n\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype RSyncSourceState = CRSyncSourceStatePtr\n\ntype Signature = ByteString\n\n\nstartSignature :: FilePath -> IO RSyncSourceState\nstartSignature path = do\n state <- malloc :: IO (Ptr CRSyncSourceState)\n rsres <- cStartSignature path state\n return state\n -- TODO: check what to do with rsres\n -- case rsres of\n -- RsDone ->\n\nendSignature :: RSyncSourceState -> IO ()\nendSignature state = cEndSignature state >> free state\n\nsignatureSource :: MonadResource m => RSyncSourceState -> Source m Signature\nsignatureSource state = undefined -- do\n -- (CInMemoryBuffer xs size inUse) <- {#get inMemorybuffer->outputBuf-> state\n\n\n\n\n\n\n\n{#fun unsafe startSignature as cStartSignature\n { `String' -- FilePath\n , id `CRSyncSourceStatePtr'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe signatureChunk as cSignatureChunk\n { id `CRSyncSourceStatePtr'\n , `Bool'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe endSignature as cEndSignature\n { id `CRSyncSourceStatePtr'\n } -> `()'\n #}\n\n\n-- type Signature = ByteString\n\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"3356e9e8859eb210b52b2f7db5866df8b0aeb45c","subject":"Fix docu.","message":"Fix docu.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/Widget.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'keyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Widget\n--\n-- Author : Axel Simon\n--\n-- Created: 27 April 2001\n--\n-- Copyright (C) 2001-2008 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-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- The base class for all widgets.\n--\nmodule Graphics.UI.Gtk.Abstract.Widget (\n\n-- * Detail\n--\n-- | The base class for all widgets. While a widget cannot be created directly,\n-- this module contains many useful methods common to all widgets. In\n-- particular, these functions are needed to add functionality to\n-- blank widgets such as 'DrawingArea' or 'Layout'.\n--\n-- 'Widget' introduces style properties - these are basically object\n-- properties that are stored not on the object, but in the style object\n-- associated to the widget. Style properties are set in resource files. This\n-- mechanism is used for configuring such things as the location of the\n-- scrollbar arrows through the theme, giving theme authors more control over\n-- the look of applications without the need to write a theme engine in C.\n--\n-- Widgets receive events, that is, signals that indicate some low-level\n-- user iteraction. The signal handlers for all these events have to\n-- return @True@ if the signal has been dealt with and @False@ if other\n-- signal handlers should be run.\n\n-- * Class Hierarchy\n--\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----Widget\n-- | +----\/too many to list\/\n-- @\n\n-- * Types\n Widget,\n WidgetClass,\n castToWidget, gTypeWidget,\n toWidget,\n EventMask(..),\n ExtensionMode(..),\n GType,\n KeyVal,\n Region,\n Bitmap,\n Requisition(..),\n Rectangle(..),\n Color,\n IconSize(..),\n StateType(..),\n TextDirection(..),\n AccelFlags(..),\n DirectionType(..),\n StockId,\n WidgetHelpType(..),\n\n-- * Methods\n widgetShow,\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\n widgetQueueResize,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetQueueResizeNoRedraw,\n#endif\n widgetSizeRequest,\n widgetGetChildRequisition,\n widgetSizeAllocate,\n widgetAddAccelerator,\n widgetRemoveAccelerator,\n widgetSetAccelPath,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetCanActivateAccel,\n#endif\n widgetActivate,\n widgetIntersect,\n widgetHasIntersection,\n widgetGetIsFocus,\n widgetGrabFocus,\n widgetGrabDefault,\n widgetSetName,\n widgetGetName,\n widgetSetSensitive,\n widgetSetSensitivity,\n widgetGetParentWindow,\n widgetGetDrawWindow,\n widgetDelEvents,\n widgetAddEvents,\n widgetGetEvents,\n widgetSetEvents,\n widgetSetExtensionEvents,\n widgetGetExtensionEvents,\n widgetGetToplevel,\n widgetGetAncestor,\n widgetGetColormap,\n widgetSetColormap,\n widgetGetPointer,\n widgetIsAncestor,\n widgetTranslateCoordinates,\n widgetSetStyle,\n widgetGetStyle,\n widgetPushColormap,\n widgetPopColormap,\n widgetSetDefaultColormap,\n widgetGetDefaultStyle,\n widgetGetDefaultColormap,\n widgetSetDirection,\n widgetGetDirection,\n widgetSetDefaultDirection,\n widgetGetDefaultDirection,\n widgetShapeCombineMask,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetInputShapeCombineMask,\n#endif\n widgetPath,\n widgetClassPath,\n widgetGetCompositeName,\n widgetModifyStyle,\n widgetGetModifierStyle,\n widgetModifyFg,\n widgetModifyBg,\n widgetModifyText,\n widgetModifyBase,\n widgetModifyFont,\n widgetCreatePangoContext,\n widgetGetPangoContext,\n widgetCreateLayout,\n widgetRenderIcon,\n widgetQueueDrawArea,\n widgetResetShapes,\n widgetSetAppPaintable,\n widgetSetDoubleBuffered,\n widgetSetRedrawOnAllocate,\n widgetSetCompositeName,\n widgetSetScrollAdjustments,\n widgetRegionIntersect,\n widgetGetAccessible,\n widgetChildFocus,\n widgetGetChildVisible,\n widgetGetParent,\n widgetGetSettings,\n#if GTK_CHECK_VERSION(2,2,0)\n --widgetGetClipboard,\n widgetGetDisplay,\n widgetGetRootWindow,\n widgetGetScreen,\n widgetHasScreen,\n#endif\n widgetGetSizeRequest,\n widgetSetChildVisible,\n widgetSetSizeRequest,\n#if GTK_CHECK_VERSION(2,4,0)\n widgetSetNoShowAll,\n widgetGetNoShowAll,\n widgetListMnemonicLabels,\n widgetAddMnemonicLabel,\n widgetRemoveMnemonicLabel,\n#if GTK_CHECK_VERSION(2,10,0)\n widgetGetAction,\n widgetIsComposited,\n#endif\n#endif\n widgetReparent,\n#if GTK_CHECK_VERSION(2,18,0)\n widgetGetCanFocus,\n widgetSetCanFocus,\n widgetGetAllocation,\n#endif\n widgetGetState,\n widgetGetSavedState,\n widgetGetSize,\n\n-- * Attributes\n widgetName,\n widgetParent,\n widgetWidthRequest,\n widgetHeightRequest,\n widgetVisible,\n widgetSensitive,\n widgetAppPaintable,\n widgetCanFocus,\n widgetHasFocus,\n widgetIsFocus,\n widgetCanDefault,\n widgetHasDefault,\n widgetReceivesDefault,\n widgetCompositeChild,\n widgetStyle,\n widgetEvents,\n widgetExtensionEvents,\n widgetNoShowAll,\n widgetChildVisible,\n widgetColormap,\n widgetCompositeName,\n widgetDirection,\n\n-- * Signals\n realize,\n unrealize,\n mapSignal,\n unmapSignal,\n sizeRequest,\n sizeAllocate,\n showSignal,\n hideSignal,\n focus,\n stateChanged,\n parentSet,\n hierarchyChanged,\n styleSet,\n directionChanged,\n grabNotify,\n popupMenuSignal,\n showHelp,\n accelClosuresChanged,\n screenChanged,\n\n-- * Events\n buttonPressEvent,\n buttonReleaseEvent,\n configureEvent,\n deleteEvent,\n destroyEvent,\n enterNotifyEvent,\n exposeEvent,\n focusInEvent,\n focusOutEvent,\n#if GTK_CHECK_VERSION(2,8,0)\n grabBrokenEvent,\n#endif\n keyPressEvent,\n keyReleaseEvent,\n leaveNotifyEvent,\n mapEvent,\n motionNotifyEvent,\n noExposeEvent,\n proximityInEvent,\n proximityOutEvent,\n scrollEvent,\n unmapEvent,\n visibilityNotifyEvent,\n windowStateEvent,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\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 onExposeRect,\n afterExposeRect,\n onFocus,\n afterFocus,\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 onRealize,\n afterRealize,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n#endif\n ) where\n\nimport Control.Monad\t(liftM, unless)\nimport Data.Maybe\t(fromMaybe)\n\nimport Data.Bits ((.&.), complement)\nimport System.Glib.FFI\nimport System.Glib.Flags\t\t(fromFlags, toFlags)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\nimport System.Glib.GType (GType)\nimport System.Glib.GList (GList, fromGList)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.Gdk.Enums\t(EventMask(..), ExtensionMode(..))\nimport Graphics.UI.Gtk.Gdk.Keys (KeyVal)\n{#import Graphics.UI.Gtk.Gdk.Region#}\t(Region(..), makeNewRegion)\n{#import Graphics.UI.Gtk.Gdk.Pixmap#} (Bitmap)\nimport Graphics.UI.Gtk.General.Structs\t(Allocation, Rectangle(..)\n\t\t\t\t\t,Requisition(..), Color, IconSize(..)\n\t\t\t\t\t,widgetGetState, widgetGetSavedState\n\t\t\t\t\t,widgetGetDrawWindow, widgetGetSize)\nimport Graphics.UI.Gtk.Gdk.Events\t(Event(..), marshalEvent,\n marshExposeRect,\n EventButton,\n EventScroll,\n EventMotion,\n EventExpose,\n EventKey,\n EventConfigure,\n EventCrossing,\n EventFocus,\n EventProperty,\n EventProximity,\n EventVisibility,\n EventWindowState,\n EventGrabBroken)\nimport Graphics.UI.Gtk.Gdk.EventM\t(EventM,\n EventM,\n EAny,\n EKey,\n EButton,\n EScroll,\n EMotion,\n EExpose,\n EVisibility,\n ECrossing,\n EFocus,\n EConfigure,\n EProperty,\n EProximity,\n EWindowState,\n#if GTK_CHECK_VERSION(2,6,0)\n EOwnerChange,\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n EGrabBroken,\n#endif\n )\nimport Graphics.UI.Gtk.General.Enums\t(StateType(..), TextDirection(..),\n\t\t\t\t\t AccelFlags(..), DirectionType(..), Modifier)\n{#import Graphics.Rendering.Pango.Types#} \n{#import Graphics.Rendering.Pango.BasicTypes#}\t(FontDescription(FontDescription),\n\t\t\t\t\t PangoLayout(PangoLayout), makeNewPangoString )\nimport Graphics.UI.Gtk.General.StockItems (StockId)\nimport Data.IORef ( newIORef )\nimport Control.Monad.Reader ( runReaderT )\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n--------------------\n-- Methods\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 'widgetShowAll' on the container, instead of\n-- individually showing the widgets.\n--\n-- Remember that you have to show the containers containing a widget, in\n-- addition to the widget itself, before it will appear onscreen.\n--\n-- When a toplevel container is shown, it is immediately realized and\n-- mapped; other shown widgets are realized and mapped when their toplevel\n-- container is realized and mapped.\n--\nwidgetShow :: WidgetClass self => self -> IO ()\nwidgetShow self =\n {# call widget_show #}\n (toWidget self)\n\n-- | Shows a widget. If the widget is an unmapped toplevel widget (i.e. a\n-- 'Window' that has not yet been shown), enter the main loop and wait for the\n-- window to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass self => self -> IO ()\nwidgetShowNow self =\n {# call widget_show_now #}\n (toWidget self)\n\n-- | Reverses the effects of 'widgetShow', causing the widget to be hidden\n-- (invisible to the user).\n--\nwidgetHide :: WidgetClass self => self -> IO ()\nwidgetHide self =\n {# call widget_hide #}\n (toWidget self)\n\n-- | Recursively shows a widget, and any child widgets (if the widget is a\n-- container).\n--\nwidgetShowAll :: WidgetClass self => self -> IO ()\nwidgetShowAll self =\n {# call widget_show_all #}\n (toWidget self)\n\n-- | Recursively hides a widget and any child widgets.\n--\nwidgetHideAll :: WidgetClass self => self -> IO ()\nwidgetHideAll self =\n {# call widget_hide_all #}\n (toWidget self)\n\n-- | Destroys a widget. Equivalent to\n-- 'Graphics.UI.Gtk.Abstract.Object.objectDestroy'.\n--\n-- When a widget is destroyed it will be removed from the screen and\n-- unrealized. When a widget is destroyed, it will break any references it\n-- holds to other objects.If the widget is inside a container, the widget will\n-- be removed from the container. The widget will be garbage collected\n-- (finalized) time after your last reference to the widget dissapears.\n--\n-- In most cases, only toplevel widgets (windows) require explicit\n-- destruction, because when you destroy a toplevel its children will be\n-- destroyed as well.\n--\nwidgetDestroy :: WidgetClass self => self -> IO ()\nwidgetDestroy self =\n {# call widget_destroy #}\n (toWidget self)\n\n-- * Functions to be used with 'Graphics.UI.Gtk.Misc.DrawingArea' or\n-- container implementations.\n\n-- | Send a redraw request to a widget. Equivalent to calling\n-- 'widgetQueueDrawArea' for the entire area of a widget.\n--\nwidgetQueueDraw :: WidgetClass self => self -> IO ()\nwidgetQueueDraw self =\n {# call widget_queue_draw #}\n (toWidget self)\n\n-- | This function is only for use in widget implementations. Flags a widget\n-- to have its size renegotiated; should be called when a widget for some\n-- reason has a new size request. For example, when you change the text in a\n-- 'Graphics.UI.Gtk.Display.Label.Label',\n-- 'Graphics.UI.Gtk.Display.Label.Label' queues a resize to ensure there's\n-- enough space for the new text.\n--\nwidgetQueueResize :: WidgetClass self => self -> IO ()\nwidgetQueueResize self =\n {# call widget_queue_resize #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | This function works like 'widgetQueueResize', except that the widget is\n-- not invalidated.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetQueueResizeNoRedraw :: WidgetClass self => self -> IO ()\nwidgetQueueResizeNoRedraw self =\n {# call widget_queue_resize_no_redraw #}\n (toWidget self)\n#endif\n\n-- | This function is typically used when implementing a\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclass. Obtains the preferred size\n-- of a widget. The container uses this information to arrange its child\n-- widgets and decide what size allocations to give them with\n-- 'widgetSizeAllocate'.\n--\n-- You can also call this function from an application, with some caveats.\n-- Most notably, getting a size request requires the widget to be associated\n-- with a screen, because font information may be needed. Multihead-aware\n-- applications should keep this in mind.\n--\n-- Also remember that the size request is not necessarily the size a widget\n-- will actually be allocated.\n--\nwidgetSizeRequest :: WidgetClass self => self -> IO Requisition\nwidgetSizeRequest self = alloca $ \\reqPtr -> do\n {#call widget_size_request #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only for use in widget implementations. Obtains the\n-- chached requisition information in the widget, unless someone has forced a\n-- particular geometry on the widget (e.g. with 'widgetSetUsize'), in which\n-- case it returns that geometry instead of the widget's requisition.\n--\n-- This function differs from 'widgetSizeRequest' in that it retrieves the\n-- last size request value stored in the widget, while 'widgetSizeRequest'\n-- actually emits the 'sizeRequest' signal on the widget to compute the size\n-- request (which updates the widget's requisition information).\n--\n-- Since this function does not emit the 'sizeRequest' signal, it can only be\n-- used when you know that the widget's requisition is up-to-date, that is,\n-- 'widgetSizeRequest' has been called since the last time a resize was\n-- queued. In general, only container implementations have this information;\n-- applications should use 'widgetSizeRequest'.\n--\nwidgetGetChildRequisition :: WidgetClass self => self -> IO Requisition\nwidgetGetChildRequisition self = alloca $ \\reqPtr -> do\n {#call widget_get_child_requisition #} (toWidget self) (castPtr reqPtr)\n peek reqPtr\n\n-- | This function is only used by\n-- 'Graphics.UI.Gtk.Abstract.Container.Container' subclasses, to assign a\n-- size and position to their child widgets.\n--\nwidgetSizeAllocate :: WidgetClass self => self\n -> Allocation -- ^ The @x@ and @y@ values of the rectangle determine the\n -- the position of the widget's area relative to its parent\n -- allocation.\n -> IO ()\nwidgetSizeAllocate self rect = with rect $ \\rectPtr ->\n {#call widget_size_allocate#} (toWidget self) (castPtr rectPtr)\n\n-- %hash c:1e14 d:53c5\n-- | Installs an accelerator for this @widget@ in @accelGroup@ that causes\n-- @accelSignal@ to be emitted if the accelerator is activated. The\n-- @accelGroup@ needs to be added to the widget's toplevel via\n-- 'windowAddAccelGroup', and the signal must be of type @G_RUN_ACTION@.\n-- Accelerators added through this function are not user changeable during\n-- runtime. If you want to support accelerators that can be changed by the\n-- user, use 'accelMapAddEntry' and 'widgetSetAccelPath' or\n-- 'menuItemSetAccelPath' instead.\n--\nwidgetAddAccelerator :: WidgetClass self => self\n -> String -- ^ @accelSignal@ - widget signal to emit on accelerator\n -- activation\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget, added to\n -- its toplevel\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> [AccelFlags] -- ^ @accelFlags@ - flag accelerators, e.g. 'AccelVisible'\n -> IO ()\nwidgetAddAccelerator self accelSignal accelGroup accelKey accelMods accelFlags =\n withUTFString accelSignal $ \\accelSignalPtr ->\n {# call gtk_widget_add_accelerator #}\n (toWidget self)\n accelSignalPtr\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n ((fromIntegral . fromFlags) accelFlags)\n\n-- %hash c:3442 d:dfe8\n-- | Removes an accelerator from @widget@, previously installed with\n-- 'widgetAddAccelerator'.\n--\nwidgetRemoveAccelerator :: WidgetClass self => self\n -> AccelGroup -- ^ @accelGroup@ - accel group for this widget\n -> KeyVal -- ^ @accelKey@ - the key of the accelerator\n -> [Modifier] -- ^ @accelMods@ - modifier key combination of the\n -- accelerator\n -> IO Bool -- ^ returns whether an accelerator was installed and could\n -- be removed\nwidgetRemoveAccelerator self accelGroup accelKey accelMods =\n liftM toBool $\n {# call gtk_widget_remove_accelerator #}\n (toWidget self)\n accelGroup\n (fromIntegral accelKey)\n ((fromIntegral . fromFlags) accelMods)\n\n-- %hash c:f8d4 d:bd7f\n-- | Given an accelerator group, @accelGroup@, and an accelerator path,\n-- @accelPath@, sets up an accelerator in @accelGroup@ so whenever the key\n-- binding that is defined for @accelPath@ is pressed, @widget@ will be\n-- activated. This removes any accelerators (for any accelerator group)\n-- installed by previous calls to 'widgetSetAccelPath'. Associating\n-- accelerators with paths allows them to be modified by the user and the\n-- modifications to be saved for future use. (See 'accelMapSave'.)\n--\n-- This function is a low level function that would most likely be used by a\n-- menu creation system like 'ItemFactory'. If you use 'ItemFactory', setting\n-- up accelerator paths will be done automatically.\n--\n-- Even when you you aren't using 'ItemFactory', if you only want to set up\n-- accelerators on menu items 'menuItemSetAccelPath' provides a somewhat more\n-- convenient interface.\n--\nwidgetSetAccelPath :: WidgetClass self => self\n -> String -- ^ @accelPath@ - path used to look up the accelerator\n -> AccelGroup -- ^ @accelGroup@ - a 'AccelGroup'.\n -> IO ()\nwidgetSetAccelPath self accelPath accelGroup =\n withUTFString accelPath $ \\accelPathPtr ->\n {# call gtk_widget_set_accel_path #}\n (toWidget self)\n accelPathPtr\n accelGroup\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:157e d:82ae\n-- | Determines whether an accelerator that activates the signal identified by\n-- @signalId@ can currently be activated. This is done by emitting the\n-- 'canActivateAccel' signal on the widget the signal is attached to; if the\n-- signal isn't overridden by a handler or in a derived widget, then the\n-- default check is that the widget must be sensitive, and the widget and all\n-- its ancestors mapped.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetCanActivateAccel :: WidgetClass self =>\n (ConnectId self) -- ^ @signalId@ - the ID of a signal installed on @widget@\n -> IO Bool -- ^ returns @True@ if the accelerator can be activated.\nwidgetCanActivateAccel (ConnectId signalId self) =\n liftM toBool $\n {# call gtk_widget_can_activate_accel #}\n (toWidget self)\n (fromIntegral signalId)\n#endif\n\n-- | For widgets that can be \\\"activated\\\" (buttons, menu items, etc.) this\n-- function activates them. Activation is what happens when you press Enter on\n-- a widget during key navigation. If @widget@ isn't activatable, the function\n-- returns @False@.\n--\nwidgetActivate :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget was activatable\nwidgetActivate self =\n liftM toBool $\n {# call widget_activate #}\n (toWidget self)\n\n-- | Computes the intersection of a widget's area and @area@, returning the\n-- intersection, and returns @Nothing@ if there was no intersection.\n--\nwidgetIntersect :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO (Maybe Rectangle) -- ^ returns the intersection or @Nothing@\nwidgetIntersect self area =\n with area $ \\areaPtr ->\n alloca $ \\intersectionPtr -> do\n hasIntersection <- {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr intersectionPtr)\n if (toBool hasIntersection)\n then liftM Just $ peek intersectionPtr\n else return Nothing\n\n-- | Check if the widget intersects with a given area.\n--\nwidgetHasIntersection :: WidgetClass self => self\n -> Rectangle -- ^ @area@ - a rectangle\n -> IO Bool -- ^ returns @True@ if there was an intersection\nwidgetHasIntersection self area = \n liftM toBool $\n with area $ \\areaPtr ->\n {# call unsafe widget_intersect #}\n (toWidget self)\n (castPtr areaPtr)\n (castPtr nullPtr)\n\n-- %hash d:1cab\n-- | Determines if the widget is the focus widget within its toplevel. (This\n-- does not mean that the 'widgetHasFocus' attribute is necessarily set;\n-- 'widgetHasFocus' will only be set if the toplevel widget additionally has\n-- the global input focus.)\n--\nwidgetGetIsFocus :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is the focus widget.\nwidgetGetIsFocus self =\n liftM toBool $\n {# call unsafe widget_is_focus #}\n (toWidget self)\n\n-- %hash d:e1e\n-- | Causes @widget@ to have the keyboard focus for the 'Window' it's inside.\n-- @widget@ must be a focusable widget, such as a\n-- 'Graphics.UI.Gtk.Entry.Entry'; something like\n-- 'Graphics.UI.Gtk.Ornaments.Frame' won't work. (More precisely, it must have\n-- the 'widgetCanFocus' flag set.)\n--\nwidgetGrabFocus :: WidgetClass self => self -> IO ()\nwidgetGrabFocus self =\n {# call widget_grab_focus #}\n (toWidget self)\n\n-- %hash c:e5e9 d:412a\n-- | Causes @widget@ to become the default widget. @widget@ must have the\n-- 'canDefault' flag set. The default widget is\n-- activated when the user presses Enter in a window. Default widgets must be\n-- activatable, that is, 'widgetActivate' should affect them.\n--\nwidgetGrabDefault :: WidgetClass self => self -> IO ()\nwidgetGrabDefault self =\n {# call gtk_widget_grab_default #}\n (toWidget self)\n\n-- %hash c:4f62 d:d05a\n-- | Widgets can be named, which allows you to refer to them from a gtkrc\n-- file. You can apply a style to widgets with a particular name in the gtkrc\n-- file. See the documentation for gtkrc files.\n--\n-- Note that widget names are separated by periods in paths (see\n-- 'widgetPath'), so names with embedded periods may cause confusion.\n--\nwidgetSetName :: WidgetClass self => self\n -> String -- ^ @name@ - name for the widget\n -> IO ()\nwidgetSetName self name =\n withUTFString name $ \\namePtr ->\n {# call widget_set_name #}\n (toWidget self)\n namePtr\n\n-- | Retrieves the name of a widget. See 'widgetSetName' for the significance\n-- of widget names.\n--\nwidgetGetName :: WidgetClass self => self -> IO String\nwidgetGetName self =\n {# call unsafe widget_get_name #}\n (toWidget self)\n >>= peekUTFString\n\n-- %hash c:25b1 d:f898\n-- | Sets the sensitivity of a widget. A widget is sensitive if the user can\n-- interact with it. Insensitive widgets are \\\"grayed out\\\" and the user can't\n-- interact with them. Insensitive widgets are known as \\\"inactive\\\",\n-- \\\"disabled\\\", or \\\"ghosted\\\" in some other toolkits.\n--\nwidgetSetSensitive :: WidgetClass self => self\n -> Bool -- ^ @sensitive@ - @True@ to make the widget sensitive\n -> IO ()\nwidgetSetSensitive self sensitive =\n {# call gtk_widget_set_sensitive #}\n (toWidget self)\n (fromBool sensitive)\n \n-- bad spelling backwards compatability definition\nwidgetSetSensitivity :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetSensitivity = widgetSetSensitive\n\n-- | Gets the widget's parent window.\n--\nwidgetGetParentWindow :: WidgetClass self => self -> IO DrawWindow\nwidgetGetParentWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_parent_window #}\n (toWidget self)\n\n-- | Disable event signals.\n--\n-- * Remove events from the 'EventMask' of this widget. The event mask\n-- determines which events a widget will receive. Events are signals\n-- that return an 'Event' data type. On connecting to a such a signal,\n-- the event mask is automatically adjusted so that he signal is emitted.\n-- This function is useful to disable the reception of the signal. It\n-- should be called whenever all signals receiving an 'Event'\n-- have been disconected. \n--\nwidgetDelEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetDelEvents self events = do\n mask <- {#call unsafe widget_get_events#} (toWidget self)\n let mask' = mask .&. (complement (fromIntegral $ fromFlags events))\n {#call unsafe widget_set_events#} (toWidget self) mask'\n\n-- | Enable event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetAddEvents :: WidgetClass self => self -> [EventMask] -> IO ()\nwidgetAddEvents self [] = return ()\n -- special [] case to work around a GTK+ bug, see:\n -- http:\/\/bugzilla.gnome.org\/show_bug.cgi?id=316702\nwidgetAddEvents self events =\n {# call unsafe widget_add_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- | Get enabled event signals.\n--\n-- * See 'widgetDelEvents'.\n--\nwidgetGetEvents :: WidgetClass self => self -> IO [EventMask]\nwidgetGetEvents self =\n liftM (toFlags . fromIntegral) $\n {# call unsafe widget_get_events #}\n (toWidget self)\n\n-- %hash c:468a d:49a0\n-- | Sets the event mask (see 'EventMask') for a widget. The event mask\n-- determines which events a widget will receive. Keep in mind that different\n-- widgets have different default event masks, and by changing the event mask\n-- you may disrupt a widget's functionality, so be careful. This function must\n-- be called while a widget is unrealized. Consider 'widgetAddEvents' for\n-- widgets that are already realized, or if you want to preserve the existing\n-- event mask. This function can't be used with 'NoWindow' widgets; to get\n-- events on those widgets, place them inside a\n-- 'Graphics.UI.Gtk.Misc.EventBox' and receive events on the event box.\n--\nwidgetSetEvents :: WidgetClass self => self\n -> [EventMask] -- ^ @events@ - event mask\n -> IO ()\nwidgetSetEvents self events =\n {# call unsafe widget_set_events #}\n (toWidget self)\n (fromIntegral $ fromFlags events)\n\n-- %hash c:4f2c d:781\n-- | Sets the extension events mask to @mode@. See 'ExtensionMode' and\n-- 'inputSetExtensionEvents'.\n--\nwidgetSetExtensionEvents :: WidgetClass self => self\n -> [ExtensionMode]\n -> IO ()\nwidgetSetExtensionEvents self mode =\n {# call widget_set_extension_events #}\n (toWidget self)\n ((fromIntegral . fromFlags) mode)\n\n-- %hash c:c824 d:e611\n-- | Retrieves the extension events the widget will receive; see\n-- 'widgetSetExtensionEvents'.\n--\nwidgetGetExtensionEvents :: WidgetClass self => self\n -> IO [ExtensionMode]\nwidgetGetExtensionEvents self =\n liftM (toFlags . fromIntegral) $\n {# call widget_get_extension_events #}\n (toWidget self)\n\n-- %hash c:270b d:8877\n-- | This function returns the topmost widget in the container hierarchy\n-- @widget@ is a part of. If @widget@ has no parent widgets, it will be\n-- returned as the topmost widget.\n--\nwidgetGetToplevel :: WidgetClass self => \n self -- ^ @widget@ - the widget in question\n -> IO Widget -- ^ returns the topmost ancestor of @widget@, or @widget@\n -- itself if there's no ancestor.\nwidgetGetToplevel self =\n makeNewObject mkWidget $\n {# call unsafe widget_get_toplevel #}\n (toWidget self)\n\n-- %hash c:17bc d:f8f9\n-- | Gets the first ancestor of @widget@ with type @widgetType@. For example,\n-- @widgetGetAncestor widget gTypeBox@ gets the first 'Box' that's\n-- an ancestor of @widget@. See note about checking for a toplevel\n-- 'Window' in the docs for 'widgetGetToplevel'.\n--\n-- Note that unlike 'widgetIsAncestor', 'widgetGetAncestor' considers\n-- @widget@ to be an ancestor of itself.\n--\nwidgetGetAncestor :: WidgetClass self => self\n -> GType -- ^ @widgetType@ - ancestor type\n -> IO (Maybe Widget) -- ^ returns the ancestor widget, or @Nothing@ if not found\nwidgetGetAncestor self widgetType = do\n ptr <- {# call gtk_widget_get_ancestor #}\n (toWidget self)\n widgetType\n if ptr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return ptr)\n\n\n-- %hash c:bd95 d:eb94\n-- | Gets the colormap that will be used to render @widget@.\n--\nwidgetGetColormap :: WidgetClass self => self\n -> IO Colormap -- ^ returns the colormap used by @widget@\nwidgetGetColormap self =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_colormap #}\n (toWidget self)\n\n-- %hash c:cba1 d:ffeb\n-- | Sets the colormap for the widget to the given value. Widget must not have\n-- been previously realized. This probably should only be used from an 'init'\n-- function (i.e. from the constructor for the widget).\n--\nwidgetSetColormap :: WidgetClass self => self\n -> Colormap -- ^ @colormap@ - a colormap\n -> IO ()\nwidgetSetColormap self colormap =\n {# call gtk_widget_set_colormap #}\n (toWidget self)\n colormap\n\n-- %hash c:3522 d:5637\n-- | Obtains the location of the mouse pointer in widget coordinates. Widget\n-- coordinates are a bit odd; for historical reasons, they are defined as\n-- 'widgetGetParentWindow' coordinates for widgets that are not 'NoWindow' widgets,\n-- and are relative to the widget's allocation's (x,y) for\n-- widgets that are 'NoWindow' widgets.\n--\nwidgetGetPointer :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(x, y)@ - X Y coordinate\nwidgetGetPointer self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr ->\n {# call gtk_widget_get_pointer #}\n (toWidget self)\n xPtr\n yPtr\n >>\n peek xPtr >>= \\x ->\n peek yPtr >>= \\y ->\n return (fromIntegral x, fromIntegral y)\n\n-- %hash c:499d\n-- | Determines whether @widget@ is somewhere inside @ancestor@, possibly with\n-- intermediate containers.\n--\nwidgetIsAncestor :: (WidgetClass self, WidgetClass ancestor) =>\n self -- ^ @widget@ - the widget in question\n -> ancestor -- ^ @ancestor@ - another 'Widget'\n -> IO Bool -- ^ returns @True@ if @ancestor@ contains @widget@ as a child,\n -- grandchild, great grandchild, etc.\nwidgetIsAncestor self ancestor =\n liftM toBool $\n {# call unsafe widget_is_ancestor #}\n (toWidget self)\n (toWidget ancestor)\n\n-- %hash c:8661\n-- | Translate coordinates relative to @srcWidget@'s allocation to coordinates\n-- relative to @destWidget@'s allocations. In order to perform this operation,\n-- both widgets must be realized, and must share a common toplevel.\n--\nwidgetTranslateCoordinates :: (WidgetClass self, WidgetClass destWidget) =>\n self -- ^ @srcWidget@ - a 'Widget'\n -> destWidget -- ^ @destWidget@ - a 'Widget'\n -> Int -- ^ @srcX@ - X position relative to @srcWidget@\n -> Int -- ^ @srcY@ - Y position relative to @srcWidget@\n -> IO (Maybe (Int, Int)) -- ^ @Just (destX, destY)@ - X and Y position\n -- relative to @destWidget@. Returns @Nothing@ if\n -- either widget was not realized, or there was no\n -- common ancestor.\nwidgetTranslateCoordinates self destWidget srcX srcY =\n alloca $ \\destXPtr ->\n alloca $ \\destYPtr -> do\n worked <- {# call gtk_widget_translate_coordinates #}\n (toWidget self)\n (toWidget destWidget)\n (fromIntegral srcX)\n (fromIntegral srcY)\n destXPtr\n destYPtr\n if (toBool worked)\n then do destX <- peek destXPtr\n destY <- peek destYPtr\n return (Just (fromIntegral destX, fromIntegral destY))\n else return Nothing\n\n-- %hash c:596c d:b7e5\n-- | Sets the 'Style' for a widget. You probably don't want\n-- to use this function; it interacts badly with themes, because themes work by\n-- replacing the 'Style'. Instead, use 'widgetModifyStyle'.\n--\nwidgetSetStyle :: WidgetClass self => self\n -> Maybe Style -- ^ @style@ - a 'Style', or @Nothing@ to remove the effect of a previous\n -- 'widgetSetStyle' and go back to the default style\n -> IO ()\nwidgetSetStyle self style =\n {# call gtk_widget_set_style #}\n (toWidget self)\n (fromMaybe (Style nullForeignPtr) style)\n\n-- | Retrieve the 'Style' associated with the widget.\n--\nwidgetGetStyle :: WidgetClass widget => widget -> IO Style\nwidgetGetStyle widget = do\n {# call gtk_widget_ensure_style #} (toWidget widget)\n makeNewGObject mkStyle $ {# call gtk_widget_get_style #} (toWidget widget)\n\n-- %hash c:d5ed d:dc10\n-- | Pushes @cmap@ onto a global stack of colormaps; the topmost colormap on\n-- the stack will be used to create all widgets. Remove @cmap@ with\n-- 'widgetPopColormap'. There's little reason to use this function.\n--\nwidgetPushColormap ::\n Colormap -- ^ @cmap@ - a 'Colormap'\n -> IO ()\nwidgetPushColormap cmap =\n {# call gtk_widget_push_colormap #}\n cmap\n\n-- %hash c:7300 d:2920\n-- | Removes a colormap pushed with 'widgetPushColormap'.\n--\nwidgetPopColormap :: IO ()\nwidgetPopColormap =\n {# call gtk_widget_pop_colormap #}\n\n-- %hash c:1f73 d:590e\n-- | Sets the default colormap to use when creating widgets.\n-- 'widgetPushColormap' is a better function to use if you only want to affect\n-- a few widgets, rather than all widgets.\n--\nwidgetSetDefaultColormap ::\n Colormap -- ^ @colormap@ - a 'Colormap'\n -> IO ()\nwidgetSetDefaultColormap colormap =\n {# call gtk_widget_set_default_colormap #}\n colormap\n\n-- %hash c:e71b d:72c2\n-- | Returns the default style used by all widgets initially.\n--\nwidgetGetDefaultStyle ::\n IO Style -- ^ returns the default style. This 'Style' object is owned by\n -- Gtk and should not be modified.\nwidgetGetDefaultStyle =\n makeNewGObject mkStyle $\n {# call gtk_widget_get_default_style #}\n\n-- %hash c:d731 d:52bf\n-- | Obtains the default colormap used to create widgets.\n--\nwidgetGetDefaultColormap ::\n IO Colormap -- ^ returns default widget colormap\nwidgetGetDefaultColormap =\n makeNewGObject mkColormap $\n {# call gtk_widget_get_default_colormap #}\n\n-- | Sets the reading direction on a particular widget. This direction\n-- controls the primary direction for widgets containing text, and also the\n-- direction in which the children of a container are packed. The ability to\n-- set the direction is present in order so that correct localization into\n-- languages with right-to-left reading directions can be done. Generally,\n-- applications will let the default reading direction present, except for\n-- containers where the containers are arranged in an order that is explicitely\n-- visual rather than logical (such as buttons for text justification).\n--\n-- If the direction is set to 'TextDirNone', then the value set by\n-- 'widgetSetDefaultDirection' will be used.\n--\nwidgetSetDirection :: WidgetClass self => self -> TextDirection -> IO ()\nwidgetSetDirection self dir =\n {# call widget_set_direction #}\n (toWidget self)\n ((fromIntegral . fromEnum) dir)\n\n-- | Gets the reading direction for a particular widget. See\n-- 'widgetSetDirection'.\n--\nwidgetGetDirection :: WidgetClass self => self -> IO TextDirection\nwidgetGetDirection self =\n liftM (toEnum . fromIntegral) $\n {# call widget_get_direction #}\n (toWidget self)\n\n-- %hash c:ff9a\n-- | Sets the default reading direction for widgets where the direction has\n-- not been explicitly set by 'widgetSetDirection'.\n--\nwidgetSetDefaultDirection :: \n TextDirection -- ^ @dir@ - the new default direction. This cannot be\n -- 'TextDirNone'.\n -> IO ()\nwidgetSetDefaultDirection dir =\n {# call gtk_widget_set_default_direction #}\n ((fromIntegral . fromEnum) dir)\n\n-- | Obtains the current default reading direction. See\n-- 'widgetSetDefaultDirection'.\n--\nwidgetGetDefaultDirection :: IO TextDirection\nwidgetGetDefaultDirection =\n liftM (toEnum . fromIntegral) $\n {# call gtk_widget_get_default_direction #}\n\n-- %hash c:c7ba d:3a9c\n-- | Sets a shape for this widget's 'DrawWindow'. This allows for transparent\n-- windows etc., see 'windowShapeCombineMask' for more information.\n--\nwidgetShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:3c29 d:68e2\n-- | Sets an input shape for this widget's GDK window. This allows for windows\n-- which react to mouse click in a nonrectangular region, see\n-- 'windowInputShapeCombineMask' for more information.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetInputShapeCombineMask :: WidgetClass self => self\n -> Maybe Bitmap -- ^ @shapeMask@ - shape to be added, or @Nothint@ to remove an\n -- existing shape.\n -> Int -- ^ @offsetX@ - X position of shape mask with respect to @window@.\n -> Int -- ^ @offsetY@ - Y position of shape mask with respect to @window@.\n -> IO ()\nwidgetInputShapeCombineMask self shapeMask offsetX offsetY =\n case (fromMaybe (Pixmap nullForeignPtr) shapeMask) of\n Pixmap fPtr -> withForeignPtr fPtr $ \\bitmapPtr ->\n {# call gtk_widget_input_shape_combine_mask #}\n (toWidget self)\n (castPtr bitmapPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n#endif\n\n-- %hash c:7e36 d:616f\n-- | Obtains the full path to @widget@. The path is simply the name of a\n-- widget and all its parents in the container hierarchy, separated by periods.\n-- The name of a widget comes from 'widgetGetName'. Paths are used to apply\n-- styles to a widget in gtkrc configuration files. Widget names are the type\n-- of the widget by default (e.g. \\\"GtkButton\\\") or can be set to an\n-- application-specific value with 'widgetSetName'. By setting the name of a\n-- widget, you allow users or theme authors to apply styles to that specific\n-- widget in their gtkrc file. Also returns the path in reverse\n-- order, i.e. starting with the widget's name instead of starting with the\n-- name of the widget's outermost ancestor.\n--\nwidgetPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:d4a6\n-- | Same as 'widgetPath', but always uses the name of a widget's type, never\n-- uses a custom name set with 'widgetSetName'.\n--\nwidgetClassPath :: WidgetClass self => self\n -> IO (Int, String, String) -- ^ @(pathLength, path, pathReversed)@ - length\n -- of the path, path string and reverse path\n -- string\nwidgetClassPath self =\n alloca $ \\pathLengthPtr ->\n alloca $ \\pathPtr ->\n alloca $ \\pathReversedPtr ->\n {# call gtk_widget_class_path #}\n (toWidget self)\n pathLengthPtr\n pathPtr\n pathReversedPtr\n >>\n peek pathLengthPtr >>= \\pathLength ->\n peek pathPtr >>= readUTFString >>= \\path ->\n peek pathReversedPtr >>= readUTFString >>= \\pathReversed ->\n return (fromIntegral pathLength, path, pathReversed)\n\n-- %hash c:769e\n-- | Obtains the composite name of a widget.\n--\nwidgetGetCompositeName :: WidgetClass self => self\n -> IO (Maybe String) -- ^ returns the composite name of @widget@, or\n -- @Nothing@ if @widget@ is not a composite child.\nwidgetGetCompositeName self =\n {# call gtk_widget_get_composite_name #}\n (toWidget self)\n >>= maybePeek peekUTFString\n\n-- | Modifies style values on the widget. Modifications made using this\n-- technique take precedence over style values set via an RC file, however,\n-- they will be overriden if a style is explicitely set on the widget using\n-- 'widgetSetStyle'. The 'RcStyle' structure is designed so each field can\n-- either be set or unset, so it is possible, using this function, to modify\n-- some style values and leave the others unchanged.\n--\n-- Note that modifications made with this function are not cumulative with\n-- previous calls to 'widgetModifyStyle' or with such functions as\n-- 'widgetModifyFg'. If you wish to retain previous values, you must first call\n-- 'widgetGetModifierStyle', make your modifications to the returned style,\n-- then call 'widgetModifyStyle' with that style. On the other hand, if you\n-- first call 'widgetModifyStyle', subsequent calls to such functions\n-- 'widgetModifyFg' will have a cumulative effect with the initial\n-- modifications.\n--\nwidgetModifyStyle :: (WidgetClass self, RcStyleClass style) => self\n -> style -- ^ @style@ - the 'RcStyle' holding the style modifications\n -> IO ()\nwidgetModifyStyle self style =\n {# call gtk_widget_modify_style #}\n (toWidget self)\n (toRcStyle style)\n\n-- | Returns the current modifier style for the widget. (As set by\n-- 'widgetModifyStyle'.) If no style has previously set, a new 'RcStyle' will\n-- be created with all values unset, and set as the modifier style for the\n-- widget. If you make changes to this rc style, you must call\n-- 'widgetModifyStyle', passing in the returned rc style, to make sure that\n-- your changes take effect.\n--\n-- Caution: passing the style back to 'widgetModifyStyle' will normally end\n-- up destroying it, because 'widgetModifyStyle' copies the passed-in style and\n-- sets the copy as the new modifier style, thus dropping any reference to the\n-- old modifier style. Add a reference to the modifier style if you want to\n-- keep it alive.\n--\nwidgetGetModifierStyle :: WidgetClass self => self -> IO RcStyle\nwidgetGetModifierStyle self =\n makeNewGObject mkRcStyle $\n {# call gtk_widget_get_modifier_style #}\n (toWidget self)\n\n-- %hash c:5550\n-- | Sets the foreground color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the foreground color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyFg'.\n -> IO ()\nwidgetModifyFg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_fg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:2c5\n-- | Sets the background color for a widget in a particular state. All other\n-- style values are left untouched. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the background color on their parent; if you\n-- want to set the background of a rectangular area around a label, try placing\n-- the label in a 'EventBox' widget and setting the background color on that.\n--\nwidgetModifyBg :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the background color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBg'.\n -> IO ()\nwidgetModifyBg self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_bg #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:d2ba\n-- | Sets the text color for a widget in a particular state. All other style\n-- values are left untouched. The text color is the foreground color used along\n-- with the base color (see 'widgetModifyBase') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\nwidgetModifyText :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the text color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyText'.\n -> IO ()\nwidgetModifyText self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_text #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:ac08\n-- | Sets the base color for a widget in a particular state. All other style\n-- values are left untouched. The base color is the background color used along\n-- with the text color (see 'widgetModifyText') for widgets such as 'Entry' and\n-- 'TextView'. See also 'widgetModifyStyle'.\n--\n-- Note that \\\"no window\\\" widgets (which have the 'NoWindow' flag set) draw\n-- on their parent container's window and thus may not draw any background\n-- themselves. This is the case for e.g. 'Label'. To modify the background of\n-- such widgets, you have to set the base color on their parent; if you want to\n-- set the background of a rectangular area around a label, try placing the\n-- label in a 'EventBox' widget and setting the base color on that.\n--\nwidgetModifyBase :: WidgetClass self => self\n -> StateType -- ^ @state@ - the state for which to set the base color.\n -> Color -- ^ @color@ - the color to assign (does not need to be\n -- allocated), or @Nothing@ to undo the effect of previous calls\n -- to of 'widgetModifyBase'.\n -> IO ()\nwidgetModifyBase self state color =\n with color $ \\colorPtr ->\n {# call gtk_widget_modify_base #}\n (toWidget self)\n ((fromIntegral . fromEnum) state)\n (castPtr colorPtr)\n\n-- %hash c:38d7\n-- | Sets the font to use for a widget. All other style values are left\n-- untouched. See also 'widgetModifyStyle'.\n--\nwidgetModifyFont :: WidgetClass self => self\n -> Maybe FontDescription -- ^ @fontDesc@ - the font description to use, or\n -- @Nothing@ to undo the effect of previous calls to\n -- 'widgetModifyFont'.\n -> IO ()\nwidgetModifyFont self fontDesc =\n {# call gtk_widget_modify_font #}\n (toWidget self)\n (fromMaybe (FontDescription nullForeignPtr) fontDesc)\n\n-- | Creates a new 'PangoContext' with the appropriate colormap, font description,\n-- and base direction for drawing text for this widget. See also\n-- 'widgetGetPangoContext'.\n--\nwidgetCreatePangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the new 'PangoContext'\nwidgetCreatePangoContext self =\n constructNewGObject mkPangoContext $\n {# call gtk_widget_create_pango_context #}\n (toWidget self)\n\n-- | Gets a 'PangoContext' with the appropriate font description and base\n-- direction for this widget. Unlike the context returned by\n-- 'widgetCreatePangoContext', this context is owned by the widget (it can be\n-- used until the screen for the widget changes or the widget is removed from\n-- its toplevel), and will be updated to match any changes to the widget's\n-- attributes.\n--\n-- If you create and keep a 'PangoLayout' using this context, you must deal\n-- with changes to the context by calling\n-- 'layoutContextChanged' on the layout\n-- in response to the 'onStyleChanged' and 'onDirectionChanged' signals for the\n-- widget.\n--\nwidgetGetPangoContext :: WidgetClass self => self\n -> IO PangoContext -- ^ returns the 'PangoContext' for the widget.\nwidgetGetPangoContext self =\n makeNewGObject mkPangoContext $\n {# call gtk_widget_get_pango_context #}\n (toWidget self)\n\n-- | Prepare text for display.\n--\n-- The 'PangoLayout' represents the rendered text. It can be shown on screen\n-- by calling 'drawLayout'.\n--\n-- The returned 'PangoLayout' shares the same font information ('PangoContext') as this\n-- widget. If this information changes, the 'PangoLayout' should change. The\n-- following code ensures that the displayed text always reflects the widget's\n-- settings:\n--\n-- > l <- widgetCreateLayout w \"My Text.\"\n-- > let update = do\n-- > layoutContextChanged l\n-- > \t\t -- update the Drawables which show this layout\n-- > w `onDirectionChanged` update\n-- > w `onStyleChanged` update\n--\nwidgetCreateLayout :: WidgetClass self => self\n -> String -- ^ @text@ - text to set on the layout\n -> IO PangoLayout\nwidgetCreateLayout self text = do\n pl <- constructNewGObject mkPangoLayoutRaw $\n withUTFString text $ \\textPtr ->\n {# call unsafe widget_create_pango_layout #}\n (toWidget self)\n textPtr\n ps <- makeNewPangoString text\n psRef <- newIORef ps\n return (PangoLayout psRef pl)\n\n-- %hash c:cee d:1d29\n-- | A convenience function that uses the theme engine and RC file settings\n-- for @widget@ to look up the stock icon and render it to a\n-- 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf'.\n-- The icon should be one of the stock id constants such as\n-- 'Graphics.UI.Gtk.General.StockItems.stockOpen'. @size@ should be a\n-- size such as 'Graphics.UI.Gtk.General.IconFactory.IconSizeMenu'.\n-- @detail@ should be a string that identifies the\n-- widget or code doing the rendering, so that theme engines can special-case\n-- rendering for that widget or code.\n--\n-- The pixels in the returned 'Graphics.UI.Gtk.Gdk.Pixbuf.Pixbuf' are\n-- shared with the rest of the\n-- application and should not be modified.\n--\nwidgetRenderIcon :: WidgetClass self => self\n -> String -- ^ @stockId@ - a stock ID\n -> IconSize -- ^ @size@ - a stock size\n -> String -- ^ @detail@ - render detail to pass to theme engine\n -> IO (Maybe Pixbuf) -- ^ returns a new pixbuf, or @Nothing@ if the stock ID\n -- wasn't known\nwidgetRenderIcon self stockId size detail =\n maybeNull (makeNewGObject mkPixbuf) $\n withUTFString detail $ \\detailPtr ->\n withUTFString stockId $ \\stockIdPtr ->\n {# call gtk_widget_render_icon #}\n (toWidget self)\n stockIdPtr\n ((fromIntegral . fromEnum) size)\n detailPtr\n\n-- %hash c:62f d:1863\n-- | Invalidates the rectangular area of @widget@ defined by @x@, @y@, @width@\n-- and @height@ by calling\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' on the widget's\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawWindow' and all its child windows. Once\n-- the main loop becomes idle (after the current batch of events has been\n-- processed, roughly), the window will receive expose events for the union of\n-- all regions that have been invalidated.\n--\n-- Normally you would only use this function in widget implementations. In\n-- particular, you might use it, or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowInvalidateRect' directly, to\n-- schedule a redraw of a 'Graphics.UI.Gtk.Gdk.DrawWindow.DrawingArea' or some\n-- portion thereof.\n--\n-- Frequently you can just call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRect' or\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.windowInvalidateRegion' instead of this\n-- function. Those functions will invalidate only a single window, instead of\n-- the widget and all its children.\n--\n-- The advantage of adding to the invalidated region compared to simply\n-- drawing immediately is efficiency; using an invalid region ensures that you\n-- only have to redraw one time.\n--\nwidgetQueueDrawArea :: WidgetClass self => self\n -> Int -- ^ @x@ - x coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @y@ - y coordinate of upper-left corner of rectangle to redraw\n -> Int -- ^ @width@ - width of region to draw\n -> Int -- ^ @height@ - height of region to draw\n -> IO ()\nwidgetQueueDrawArea self x y width height =\n {# call gtk_widget_queue_draw_area #}\n (toWidget self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- %hash c:5ffb d:3e1a\n-- | Recursively resets the shape on this widget and its descendants.\n--\nwidgetResetShapes :: WidgetClass self => self -> IO ()\nwidgetResetShapes self =\n {# call gtk_widget_reset_shapes #}\n (toWidget self)\n\n-- | Sets whether the application intends to draw on the widget in response\n-- to an 'onExpose' signal.\n--\n-- * This is a hint to the widget and does not affect the behavior of the\n-- GTK+ core; many widgets ignore this flag entirely. For widgets that do\n-- pay attention to the flag, such as 'EventBox' and 'Window', the effect\n-- is to suppress default themed drawing of the widget's background.\n-- (Children of the widget will still be drawn.) The application is then\n-- entirely responsible for drawing the widget background.\n--\nwidgetSetAppPaintable :: WidgetClass self => self\n -> Bool -- ^ @appPaintable@ - @True@ if the application will paint on the\n -- widget\n -> IO ()\nwidgetSetAppPaintable self appPaintable =\n {# call widget_set_app_paintable #}\n (toWidget self)\n (fromBool appPaintable)\n\n-- %hash c:89b2 d:e14d\n-- | Widgets are double buffered by default; you can use this function to turn\n-- off the buffering. \\\"Double buffered\\\" simply means that\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint' are called automatically\n-- around expose events sent to the widget.\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaintRegion' diverts all\n-- drawing to a widget's window to an offscreen buffer, and\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowEndPaint'\n-- draws the buffer to the screen. The result is that users see the window\n-- update in one smooth step, and don't see individual graphics primitives\n-- being rendered.\n--\n-- In very simple terms, double buffered widgets don't flicker, so you would\n-- only use this function to turn off double buffering if you had special needs\n-- and really knew what you were doing.\n--\n-- Note: if you turn off double-buffering, you have to handle expose events,\n-- since even the clearing to the background color or pixmap will not happen\n-- automatically (as it is done in\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowBeginPaint').\n--\nwidgetSetDoubleBuffered :: WidgetClass self => self\n -> Bool -- ^ @doubleBuffered@ - @True@ to double-buffer a widget\n -> IO ()\nwidgetSetDoubleBuffered self doubleBuffered =\n {# call gtk_widget_set_double_buffered #}\n (toWidget self)\n (fromBool doubleBuffered)\n\n-- %hash c:d61 d:ac24\n-- | Sets whether the entire widget is queued for drawing when its size\n-- allocation changes. By default, this setting is @True@ and the entire widget\n-- is redrawn on every size change. If your widget leaves the upper left\n-- unchanged when made bigger, turning this setting on will improve\n-- performance.\n--\n-- Note that for \\\"no window\\\" widgets setting this flag to @False@ turns off\n-- all allocation on resizing: the widget will not even redraw if its position\n-- changes; this is to allow containers that don't draw anything to avoid\n-- excess invalidations. If you set this flag on a \\\"no window\\\" widget that\n-- \/does\/ draw its window, you are responsible for invalidating both\n-- the old and new allocation of the widget when the widget is moved and\n-- responsible for invalidating regions newly when the widget increases size.\n--\nwidgetSetRedrawOnAllocate :: WidgetClass self => self\n -> Bool -- ^ @redrawOnAllocate@ - if @True@, the entire widget will be\n -- redrawn when it is allocated to a new size. Otherwise, only the\n -- new portion of the widget will be redrawn.\n -> IO ()\nwidgetSetRedrawOnAllocate self redrawOnAllocate =\n {# call gtk_widget_set_redraw_on_allocate #}\n (toWidget self)\n (fromBool redrawOnAllocate)\n\n-- | Sets a widgets composite name. A child widget of a container is\n-- composite if it serves as an internal widget and, thus, is not\n-- added by the user.\n--\nwidgetSetCompositeName :: WidgetClass self => self\n -> String -- ^ @name@ - the name to set.\n -> IO ()\nwidgetSetCompositeName self name =\n withUTFString name $ \\namePtr ->\n {# call gtk_widget_set_composite_name #}\n (toWidget self)\n namePtr\n\n-- %hash c:5c58 d:6895\n-- | For widgets that support scrolling, sets the scroll adjustments and\n-- returns @True@. For widgets that don't support scrolling, does nothing and\n-- returns @False@. Widgets that don't support scrolling can be scrolled by\n-- placing them in a 'Viewport', which does support scrolling.\n--\nwidgetSetScrollAdjustments :: WidgetClass self => self\n -> Maybe Adjustment -- ^ @hadjustment@ - an adjustment for horizontal scrolling, or\n -- @Nothing@\n -> Maybe Adjustment -- ^ @vadjustment@ - an adjustment for vertical scrolling, or\n -- @Nothing@\n -> IO Bool -- ^ returns @True@ if the widget supports scrolling\nwidgetSetScrollAdjustments self hadjustment vadjustment =\n liftM toBool $\n {# call gtk_widget_set_scroll_adjustments #}\n (toWidget self)\n (fromMaybe (Adjustment nullForeignPtr) hadjustment)\n (fromMaybe (Adjustment nullForeignPtr) vadjustment)\n\n-- | Computes the intersection of a widget's area and @region@, returning\n-- the intersection. The result may be empty, use\n-- 'Graphics.UI.Gtk.Gdk.Region.regionEmpty' to check.\n--\nwidgetRegionIntersect :: WidgetClass self => self\n -> Region -- ^ @region@ - a 'Region' in the same coordinate system as the\n -- widget's allocation. That is, relative to the widget's\n -- 'DrawWindow' for 'NoWindow' widgets; relative to the parent\n -- 'DrawWindow' of the widget's 'DrawWindow' for widgets with\n -- their own 'DrawWindow'.\n -> IO Region -- ^ returns A region holding the intersection of the widget and\n -- @region@. The coordinates of the return value are relative to\n -- the widget's 'DrawWindow', if it has one, otherwise\n -- it is relative to the parent's 'DrawWindow'.\nwidgetRegionIntersect self region = do\n intersectionPtr <- {# call gtk_widget_region_intersect #}\n (toWidget self)\n region\n makeNewRegion intersectionPtr\n\n-- %hash c:3c94 d:cdb6\n-- | Returns the accessible object that describes the widget to an assistive\n-- technology.\n--\n-- If no accessibility library is loaded (i.e. no ATK implementation library\n-- is loaded via GTK_MODULES or via another application library, such as\n-- libgnome), then this 'Object' instance may be a no-op. Likewise, if no\n-- class-specific 'Object' implementation is available for the widget instance\n-- in question, it will inherit an 'Object' implementation from the first\n-- ancestor class for which such an implementation is defined.\n--\n-- The documentation of the ATK library contains more information about\n-- accessible objects and their uses.\n--\nwidgetGetAccessible :: WidgetClass self => self\n -> IO Object -- ^ returns the 'Object' associated with @widget@\nwidgetGetAccessible self =\n makeNewGObject mkObject $\n liftM castPtr $\n {# call gtk_widget_get_accessible #}\n (toWidget self)\n\n-- %hash c:713d d:c4fc\n-- | This function is used by custom widget implementations; if you\\'re\n-- writing an app, you\\'d use 'widgetGrabFocus' to move the focus to a\n-- particular widget, and 'containerSetFocusChain' to change the focus tab\n-- order. So you may want to investigate those functions instead.\n--\n-- The \\\"focus\\\" default handler for a widget should return @True@ if moving\n-- in @direction@ left the focus on a focusable location inside that widget,\n-- and @False@ if moving in @direction@ moved the focus outside the widget. If\n-- returning @True@, widgets normally call 'widgetGrabFocus' to place the focus\n-- accordingly; if returning @False@, they don't modify the current focus\n-- location.\n--\nwidgetChildFocus :: WidgetClass self => self\n -> DirectionType -- ^ @direction@ - direction of focus movement\n -> IO Bool -- ^ returns @True@ if focus ended up inside @widget@\nwidgetChildFocus self direction =\n liftM toBool $\n {# call gtk_widget_child_focus #}\n (toWidget self)\n ((fromIntegral . fromEnum) direction)\n\n-- %hash c:de20 d:5300\n-- | Gets the value set with 'widgetSetChildVisible'. If you feel a need to\n-- use this function, your code probably needs reorganization.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetGetChildVisible :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget is mapped with the parent.\nwidgetGetChildVisible self =\n liftM toBool $\n {# call gtk_widget_get_child_visible #}\n (toWidget self)\n\n-- %hash c:9320 d:367\n-- | Returns the parent container of @widget@.\n--\n-- * Returns the parent container of @widget@ if it has one.\n--\nwidgetGetParent :: WidgetClass self => self\n -> IO (Maybe Widget) \nwidgetGetParent self = do\n parentPtr <- {# call gtk_widget_get_parent #} (toWidget self)\n if parentPtr==nullPtr then return Nothing else\n liftM Just $ makeNewObject mkWidget (return parentPtr)\n\n-- %hash c:85e3 d:a962\n-- | Gets the settings object holding the settings (global property settings,\n-- RC file information, etc) used for this widget.\n--\n-- Note that this function can only be called when the 'Widget' is attached\n-- to a toplevel, since the settings object is specific to a particular\n-- 'Screen'.\n--\nwidgetGetSettings :: WidgetClass self => self\n -> IO Settings -- ^ returns the relevant 'Settings' object\nwidgetGetSettings self =\n makeNewGObject mkSettings $\n {# call gtk_widget_get_settings #}\n (toWidget self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\n-- %hash c:45ed d:52ef\n-- | Get the 'Display' for the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create display specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetDisplay :: WidgetClass self => self\n -> IO Display -- ^ returns the 'Display' for the toplevel for this widget.\nwidgetGetDisplay self =\n makeNewGObject mkDisplay $\n {# call gtk_widget_get_display #}\n (toWidget self)\n\n-- %hash c:8e4e d:252b\n-- | Get the root window where this widget is located. This function can only\n-- be called after the widget has been added to a widget heirarchy with\n-- 'Window' at the top.\n--\n-- The root window is useful for such purposes as creating a popup\n-- 'DrawWindow' associated with the window. In general, you should only create\n-- display specific resources when a widget has been realized, and you should\n-- free those resources when the widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetRootWindow :: WidgetClass self => self\n -> IO DrawWindow -- ^ returns the 'DrawWindow' root window for the toplevel\n -- for this widget.\nwidgetGetRootWindow self =\n makeNewGObject mkDrawWindow $\n {# call gtk_widget_get_root_window #}\n (toWidget self)\n\n-- %hash c:b929 d:67f0\n-- | Get the 'Screen' from the toplevel window associated with this widget.\n-- This function can only be called after the widget has been added to a widget\n-- hierarchy with a 'Window' at the top.\n--\n-- In general, you should only create screen specific resources when a\n-- widget has been realized, and you should free those resources when the\n-- widget is unrealized.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetGetScreen :: WidgetClass self => self\n -> IO Screen -- ^ returns the 'Screen' for the toplevel for this widget.\nwidgetGetScreen self =\n makeNewGObject mkScreen $\n {# call gtk_widget_get_screen #}\n (toWidget self)\n\n-- %hash c:4fab d:aae2\n-- | Checks whether there is a 'Screen' is associated with this widget. All\n-- toplevel widgets have an associated screen, and all widgets added into a\n-- heirarchy with a toplevel window at the top.\n--\n-- * Available since Gtk+ version 2.2\n--\nwidgetHasScreen :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if there is a 'Screen' associcated with the\n -- widget.\nwidgetHasScreen self =\n liftM toBool $\n {# call gtk_widget_has_screen #}\n (toWidget self)\n#endif\n\n-- %hash c:dabc d:8275\n-- | Gets the size request that was explicitly set for the widget using\n-- 'widgetSetSizeRequest'. A value of -1 for @width@ or @height@\n-- indicates that that dimension has not been set explicitly and the natural\n-- requisition of the widget will be used intead. See 'widgetSetSizeRequest'.\n-- To get the size a widget will actually use, call 'widgetSizeRequest' instead\n-- of this function.\n--\nwidgetGetSizeRequest :: WidgetClass self => self\n -> IO (Int, Int) -- ^ @(width, height)@\nwidgetGetSizeRequest self =\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call gtk_widget_get_size_request #}\n (toWidget self)\n widthPtr\n heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n-- %hash c:546d d:3c7f\n-- | Sets whether @widget@ should be mapped along with its when its parent is\n-- mapped and @widget@ has been shown with 'widgetShow'.\n--\n-- The child visibility can be set for widget before it is added to a\n-- container with 'widgetSetParent', to avoid mapping children unnecessary\n-- before immediately unmapping them. However it will be reset to its default\n-- state of @True@ when the widget is removed from a container.\n--\n-- Note that changing the child visibility of a widget does not queue a\n-- resize on the widget. Most of the time, the size of a widget is computed\n-- from all visible children, whether or not they are mapped. If this is not\n-- the case, the container can queue a resize itself.\n--\n-- This function is only useful for container implementations and never\n-- should be called by an application.\n--\nwidgetSetChildVisible :: WidgetClass self => self\n -> Bool -- ^ @isVisible@ - if @True@, @widget@ should be mapped along with\n -- its parent.\n -> IO ()\nwidgetSetChildVisible self isVisible =\n {# call gtk_widget_set_child_visible #}\n (toWidget self)\n (fromBool isVisible)\n\n-- | Sets the minimum size of a widget; that is, the widget's size request\n-- will be @width@ by @height@. You can use this function to force a widget to\n-- be either larger or smaller than it normally would be.\n--\n-- In most cases, 'Graphics.UI.Gtk.Windows.Window.windowSetDefaultSize'\n-- is a better choice for toplevel\n-- windows than this function; setting the default size will still allow users\n-- to shrink the window. Setting the size request will force them to leave the\n-- window at least as large as the size request. When dealing with window\n-- sizes, 'Graphics.UI.Gtk.Windows.Window.windowSetGeometryHints' can be a\n-- useful function as well.\n--\n-- Note the inherent danger of setting any fixed size - themes, translations\n-- into other languages, different fonts, and user action can all change the\n-- appropriate size for a given widget. So, it's basically impossible to\n-- hardcode a size that will always be correct.\n--\n-- The size request of a widget is the smallest size a widget can accept\n-- while still functioning well and drawing itself correctly. However in some\n-- strange cases a widget may be allocated less than its requested size, and in\n-- many cases a widget may be allocated more space than it requested.\n--\n-- If the size request in a given direction is -1 (unset), then the\n-- \\\"natural\\\" size request of the widget will be used instead.\n--\n-- Widgets can't actually be allocated a size less than 1 by 1, but you can\n-- pass 0,0 to this function to mean \\\"as small as possible.\\\"\n--\nwidgetSetSizeRequest :: WidgetClass self => self\n -> Int -- ^ @width@ - width @widget@ should request, or -1 to unset\n -> Int -- ^ @height@ - height @widget@ should request, or -1 to unset\n -> IO ()\nwidgetSetSizeRequest self width height =\n {# call widget_set_size_request #}\n (toWidget self)\n (fromIntegral width)\n (fromIntegral height)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:83c3 d:e6f1\n-- | Sets the 'noShowAll' property, which determines whether calls to\n-- 'widgetShowAll' and 'widgetHideAll' will affect this widget.\n--\n-- This is mostly for use in constructing widget hierarchies with externally\n-- controlled visibility, see 'UIManager'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetSetNoShowAll :: WidgetClass self => self\n -> Bool -- ^ @noShowAll@ - the new value for the 'noShowAll' property\n -> IO ()\nwidgetSetNoShowAll self noShowAll =\n {# call gtk_widget_set_no_show_all #}\n (toWidget self)\n (fromBool noShowAll)\n\n-- %hash c:218d d:e07e\n-- | Returns the current value of the 'noShowAll' property, which\n-- determines whether calls to 'widgetShowAll' and 'widgetHideAll' will affect\n-- this widget.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetGetNoShowAll :: WidgetClass self => self\n -> IO Bool -- ^ returns the current value of the \\\"no_show_all\\\" property.\nwidgetGetNoShowAll self =\n liftM toBool $\n {# call gtk_widget_get_no_show_all #}\n (toWidget self)\n\n-- %hash c:205b d:c518\n-- | Returns a list of the widgets, normally labels, for which\n-- this widget is a the target of a mnemonic (see for example,\n-- 'labelSetMnemonicWidget').\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetListMnemonicLabels :: WidgetClass self => self\n -> IO [Widget] -- ^ returns the list of mnemonic labels\nwidgetListMnemonicLabels self =\n {# call gtk_widget_list_mnemonic_labels #}\n (toWidget self)\n >>= fromGList\n >>= mapM (makeNewGObject mkWidget . return)\n\n-- %hash c:eb76 d:28a2\n-- | Adds a widget to the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). Note the list of mnemonic labels for the widget\n-- is cleared when the widget is destroyed, so the caller must make sure to\n-- update its internal state at this point as well, by using a connection to\n-- the 'destroy' signal or a weak notifier.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetAddMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that acts as a mnemonic label for\n -- @widget@.\n -> IO ()\nwidgetAddMnemonicLabel self label =\n {# call gtk_widget_add_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n-- %hash c:7831 d:d10b\n-- | Removes a widget from the list of mnemonic labels for this widget. (See\n-- 'widgetListMnemonicLabels'). The widget must have previously been added to\n-- the list with 'widgetAddMnemonicLabel'.\n--\n-- * Available since Gtk+ version 2.4\n--\nwidgetRemoveMnemonicLabel :: (WidgetClass self, WidgetClass label) => self\n -> label -- ^ @label@ - a 'Widget' that was previously set as a mnemnic label\n -- for @widget@ with 'widgetAddMnemonicLabel'.\n -> IO ()\nwidgetRemoveMnemonicLabel self label =\n {# call gtk_widget_remove_mnemonic_label #}\n (toWidget self)\n (toWidget label)\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:5c70 d:cbf9\n-- | Returns the 'Action' that @widget@ is a proxy for. See also\n-- 'actionGetProxies'.\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetGetAction :: WidgetClass self => self\n -> IO (Maybe Action)\n -- ^ returns the action that a widget is a proxy for, or\n -- @Nothing@, if it is not attached to an action.\nwidgetGetAction self = do\n ptr <- {# call gtk_widget_get_action #} (toWidget self)\n if ptr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkAction (return ptr)\n\n-- %hash c:7ea0 d:2560\n-- | Whether @widget@ can rely on having its alpha channel drawn correctly. On\n-- X11 this function returns whether a compositing manager is running for\n-- @widget@'s screen\n--\n-- * Available since Gtk+ version 2.10\n--\nwidgetIsComposited :: WidgetClass self => self\n -> IO Bool -- ^ returns @True@ if the widget can rely on its alpha channel\n -- being drawn correctly.\nwidgetIsComposited self =\n liftM toBool $\n {# call gtk_widget_is_composited #}\n (toWidget self)\n#endif\n#endif\n\n-- | Moves a widget from one 'Container' to another.\n--\nwidgetReparent :: (WidgetClass self, WidgetClass newParent) => self\n -> newParent -- ^ @newParent@ - a 'Container' to move the widget into\n -> IO ()\nwidgetReparent self newParent =\n {# call widget_reparent #}\n (toWidget self)\n (toWidget newParent)\n\n#if GTK_CHECK_VERSION(2,18,0)\n-- | Set if this widget can receive keyboard input.\n--\n-- * To use the 'onKeyPress' event, the widget must be allowed\n-- to get the input focus. Once it has the input focus all keyboard\n-- input is directed to this widget.\n--\nwidgetSetCanFocus :: WidgetClass self => self -> Bool -> IO ()\nwidgetSetCanFocus = objectSetPropertyBool \"can_focus\"\n\n-- | Check if this widget can receive keyboard input.\n--\nwidgetGetCanFocus :: WidgetClass self => self -> IO Bool\nwidgetGetCanFocus = objectGetPropertyBool \"can_focus\"\n\n-- | Retrieves the widget's allocation.\n--\n-- * Available since Gtk+ version 2.18\n--\nwidgetGetAllocation :: WidgetClass self => self -> IO Allocation\nwidgetGetAllocation widget =\n alloca $ \\ allocationPtr -> do \n {#call widget_get_allocation#} (toWidget widget) (castPtr allocationPtr)\n peek allocationPtr\n#endif\n\n--------------------\n-- Attributes\n\n-- %hash c:6f7f d:9384\n-- | The name of the widget.\n--\n-- Default value: @Nothing@\n--\nwidgetName :: WidgetClass self => Attr self (Maybe String)\nwidgetName = newAttrFromMaybeStringProperty \"name\"\n\n-- %hash c:1533 d:3213\n-- | The parent widget of this widget. Must be a Container widget.\n--\nwidgetParent :: (WidgetClass self, ContainerClass container) => ReadWriteAttr self (Maybe Container) (Maybe container)\nwidgetParent = newAttrFromMaybeObjectProperty \"parent\" gTypeContainer\n\n-- %hash c:2b4c d:3c31\n-- | Override for width request of the widget, or -1 if natural request should\n-- be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetWidthRequest :: WidgetClass self => Attr self Int\nwidgetWidthRequest = newAttrFromIntProperty \"width-request\"\n\n-- %hash c:fa97 d:172a\n-- | Override for height request of the widget, or -1 if natural request\n-- should be used.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\nwidgetHeightRequest :: WidgetClass self => Attr self Int\nwidgetHeightRequest = newAttrFromIntProperty \"height-request\"\n\n-- %hash c:70d0 d:e8e2\n-- | Whether the widget is visible.\n--\n-- Default value: @False@\n--\nwidgetVisible :: WidgetClass self => Attr self Bool\nwidgetVisible = newAttrFromBoolProperty \"visible\"\n\n-- %hash c:4dd4 d:594e\n-- | Whether the widget responds to input.\n--\n-- Default value: @True@\n--\nwidgetSensitive :: WidgetClass self => Attr self Bool\nwidgetSensitive = newAttrFromBoolProperty \"sensitive\"\n\n-- %hash c:7506 d:1dde\n-- | Whether the application will paint directly on the widget.\n--\n-- Default value: @False@\n--\nwidgetAppPaintable :: WidgetClass self => Attr self Bool\nwidgetAppPaintable = newAttrFromBoolProperty \"app-paintable\"\n\n-- %hash c:6289 d:72ab\n-- | Whether the widget can accept the input focus.\n--\n-- Default value: @False@\n--\nwidgetCanFocus :: WidgetClass self => Attr self Bool\nwidgetCanFocus = newAttrFromBoolProperty \"can-focus\"\n\n-- %hash c:8e7 d:2645\n-- | Whether the widget has the input focus.\n--\n-- Default value: @False@\n--\nwidgetHasFocus :: WidgetClass self => Attr self Bool\nwidgetHasFocus = newAttrFromBoolProperty \"has-focus\"\n\n-- %hash c:7547 d:1d78\n-- | Whether the widget is the focus widget within the toplevel.\n--\n-- Default value: @False@\n--\nwidgetIsFocus :: WidgetClass self => Attr self Bool\nwidgetIsFocus = newAttrFromBoolProperty \"is-focus\"\n\n-- %hash c:f2d8 d:1cbb\n-- | Whether the widget can be the default widget.\n--\n-- Default value: @False@\n--\nwidgetCanDefault :: WidgetClass self => Attr self Bool\nwidgetCanDefault = newAttrFromBoolProperty \"can-default\"\n\n-- %hash c:836 d:4cbe\n-- | Whether the widget is the default widget.\n--\n-- Default value: @False@\n--\nwidgetHasDefault :: WidgetClass self => Attr self Bool\nwidgetHasDefault = newAttrFromBoolProperty \"has-default\"\n\n-- %hash c:f964 d:b62f\n-- | If @True@, the widget will receive the default action when it is focused.\n--\n-- Default value: @False@\n--\nwidgetReceivesDefault :: WidgetClass self => Attr self Bool\nwidgetReceivesDefault = newAttrFromBoolProperty \"receives-default\"\n\n-- %hash c:2ca6 d:cad8\n-- | Whether the widget is part of a composite widget.\n--\n-- Default value: @False@\n--\nwidgetCompositeChild :: WidgetClass self => ReadAttr self Bool\nwidgetCompositeChild = readAttrFromBoolProperty \"composite-child\"\n\n-- %hash c:4f01 d:bd3\n-- | The style of the widget, which contains information about how it will\n-- look (colors etc).\n--\nwidgetStyle :: WidgetClass self => Attr self Style\nwidgetStyle = newAttrFromObjectProperty \"style\" gTypeStyle\n\n-- %hash c:e2a4 d:9296\n-- | The event mask that decides what kind of GdkEvents this widget gets.\n--\n-- Default value: 'StructureMask'\n--\nwidgetEvents :: WidgetClass self => Attr self [EventMask]\nwidgetEvents = newAttrFromFlagsProperty \"events\"\n {# call pure unsafe gdk_event_mask_get_type #}\n\n-- %hash c:ba80\n-- | The mask that decides what kind of extension events this widget gets.\n--\n-- Default value: 'ExtensionEventsNone'\n--\nwidgetExtensionEvents :: WidgetClass self => Attr self [ExtensionMode]\nwidgetExtensionEvents = newAttr\n widgetGetExtensionEvents\n widgetSetExtensionEvents\n\n-- %hash c:1605 d:48ea\n-- | Whether 'widgetShowAll' should not affect this widget.\n--\n-- Default value: @False@\n--\nwidgetNoShowAll :: WidgetClass self => Attr self Bool\nwidgetNoShowAll = newAttrFromBoolProperty \"no-show-all\"\n\n-- %hash c:cd8d d:59b2\n-- | \\'childVisible\\' property. See 'widgetGetChildVisible' and\n-- 'widgetSetChildVisible'\n--\nwidgetChildVisible :: WidgetClass self => Attr self Bool\nwidgetChildVisible = newAttr\n widgetGetChildVisible\n widgetSetChildVisible\n\n-- %hash c:a20a d:646f\n-- | \\'colormap\\' property. See 'widgetGetColormap' and 'widgetSetColormap'\n--\nwidgetColormap :: WidgetClass self => Attr self Colormap\nwidgetColormap = newAttr\n widgetGetColormap\n widgetSetColormap\n\n-- %hash c:a7fd d:55b8\n-- | \\'compositeName\\' property. See 'widgetGetCompositeName' and\n-- 'widgetSetCompositeName'\n--\nwidgetCompositeName :: WidgetClass self => ReadWriteAttr self (Maybe String) String\nwidgetCompositeName = newAttr\n widgetGetCompositeName\n widgetSetCompositeName\n\n-- %hash c:6c03 d:ce3b\n-- | \\'direction\\' property. See 'widgetGetDirection' and 'widgetSetDirection'\n--\nwidgetDirection :: WidgetClass self => Attr self TextDirection\nwidgetDirection = newAttr\n widgetGetDirection\n widgetSetDirection\n\n--------------------\n-- Signals\n\n\n-- %hash c:4cf5 d:af3f\n-- | The widget appears on screen.\n--\nmapSignal :: WidgetClass self => Signal self (IO ())\nmapSignal = Signal (connect_NONE__NONE \"map\")\n\n-- %hash c:e33e d:af3f\n-- | The widget disappears from the screen.\n--\nunmapSignal :: WidgetClass self => Signal self (IO ())\nunmapSignal = Signal (connect_NONE__NONE \"unmap\")\n\n-- %hash c:1f7f d:af3f\n-- | The widget should allocate any resources needed, in particular, the\n-- widget's 'DrawWindow' is created. If you connect to this signal and\n-- you rely on some of these resources to be present, you have to use\n-- 'System.Glib.Signals.after'.\n--\nrealize :: WidgetClass self => Signal self (IO ())\nrealize = Signal (connect_NONE__NONE \"realize\")\n\n-- %hash c:7948 d:af3f\n-- | The widget should deallocate any resources. This signal is emitted before\n-- the widget is destroyed.\n--\nunrealize :: WidgetClass self => Signal self (IO ())\nunrealize = Signal (connect_NONE__NONE \"unrealize\")\n\n-- %hash c:9f6f d:af3f\n-- | 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--\nsizeRequest :: WidgetClass self => Signal self (IO Requisition)\nsizeRequest = Signal (\\after w fun ->\n connect_PTR__NONE \"size_request\" after w\n (\\rqPtr -> fun >>= \\req -> unless (rqPtr==nullPtr) $ poke rqPtr req))\n\n-- %hash c:8ec5 d:af3f\n-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"sizeRequest\\\"@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nsizeAllocate :: WidgetClass self => Signal self (Allocation -> IO ())\nsizeAllocate = Signal (connect_BOXED__NONE \"size_allocate\" peek)\n\n-- %hash c:ae3e d:af3f\n-- | The widget is shown.\n--\nshowSignal :: WidgetClass self => Signal self (IO ())\nshowSignal = Signal (connect_NONE__NONE \"show\")\n\n-- %hash c:f589 d:af3f\n-- | The widget is hidden.\n--\nhideSignal :: WidgetClass self => Signal self (IO ())\nhideSignal = Signal (connect_NONE__NONE \"hide\")\n\n-- %hash c:a285 d:af3f\n-- | The widget gains focus via the given user action.\n--\nfocus :: WidgetClass self => Signal self (DirectionType -> IO Bool)\nfocus = Signal (connect_ENUM__BOOL \"focus\")\n\n-- %hash c:78ae d:af3f\n-- | The state of the widget (input focus, insensitive, etc.) has changed.\n--\nstateChanged :: WidgetClass self => Signal self (StateType -> IO ())\nstateChanged = Signal (connect_ENUM__NONE \"state_changed\")\n\n-- %hash c:bef2 d:1d66\n-- | The parent-set signal is emitted when a new parent has been set on a\n-- widget. The parameter is the new parent.\n--\nparentSet :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nparentSet = Signal (connect_MOBJECT__NONE \"parent_set\")\n\n-- %hash c:7e2b d:4049\n-- | Emitted when there is a change in the hierarchy to which a widget belong.\n-- More precisely, a widget is anchored when its toplevel ancestor is a\n-- 'Window'. This signal is emitted when a widget changes from un-anchored to\n-- anchored or vice-versa.\n--\nhierarchyChanged :: WidgetClass self => Signal self (Maybe Widget -> IO ())\nhierarchyChanged = Signal (connect_MOBJECT__NONE \"hierarchy_changed\")\n\n-- %hash c:5894 d:ba10\n-- | The style-set signal is emitted when a new style has been set on a\n-- widget. Note that style-modifying functions like 'widgetModifyBase' also\n-- cause this signal to be emitted.\n--\nstyleSet :: WidgetClass self => Signal self (Style -> IO ())\nstyleSet = Signal (connect_OBJECT__NONE \"style_set\")\n\n-- %hash c:6bb1 d:af3f\n-- | The default direction of text writing has changed.\n--\ndirectionChanged :: WidgetClass self => Signal self (TextDirection -> IO ())\ndirectionChanged = Signal (connect_ENUM__NONE \"direction_changed\")\n\n-- %hash c:c28c d:d116\n-- | The 'grabNotify' signal is emitted when a widget becomes shadowed by a\n-- Gtk+ grab (not a pointer or keyboard grab) on another widget, or when it\n-- becomes unshadowed due to a grab being removed.\n--\n-- A widget is shadowed by a 'grabAdd' when the topmost grab widget in the\n-- grab stack of its window group is not its ancestor.\n--\ngrabNotify :: WidgetClass self => Signal self (Bool -> IO ())\ngrabNotify = Signal (connect_BOOL__NONE \"grab_notify\")\n\n-- %hash c:e06c d:a681\n-- | This signal gets emitted whenever a widget should pop up a\n-- context-sensitive menu. This usually happens through the standard key\n-- binding mechanism; by pressing a certain key while a widget is focused, the\n-- user can cause the widget to pop up a menu. For example, the 'Entry' widget\n-- creates a menu with clipboard commands.\n--\npopupMenuSignal :: WidgetClass self => Signal self (IO Bool)\npopupMenuSignal = Signal (connect_NONE__BOOL \"popup_menu\")\n\n-- | Specify what kind of help the user wants.\n{#enum GtkWidgetHelpType as WidgetHelpType {underscoreToCase} deriving (Eq,Show) #}\n\n-- %hash c:b18e d:af3f\n-- | Tell the widget to show an explanatory help text. Should return @True@\n-- if help has been shown.\n--\nshowHelp :: WidgetClass self => Signal self (WidgetHelpType -> IO Bool)\nshowHelp = Signal (connect_ENUM__BOOL \"show_help\")\n\n-- %hash c:6a8f d:af3f\n-- | The set of keyboard accelerators has changed.\n--\naccelClosuresChanged :: WidgetClass self => Signal self (IO ())\naccelClosuresChanged = Signal (connect_NONE__NONE \"accel_closures_changed\")\n\n-- %hash c:5ca d:af3f\n-- | The widget moved to a new screen.\n--\nscreenChanged :: WidgetClass self => Signal self (Screen -> IO ())\nscreenChanged = Signal (connect_OBJECT__NONE \"screen_changed\")\n\n-- * Events\n--\n-- An event is a signal that indicates that some low-level interaction like a\n-- button or key press, mouse movement, etc. has occurred. In particular,\n-- events relate to operations on 'DrawWindow's which are a concept of the\n-- underlying OS rather than the logical widget concept. Some widgets have no\n-- window and use their parent to receive these events. Widgets normally\n-- synthesize more sophistiacted signals from events. For instance, the\n-- 'focusIn' and a 'focusOut' signal indicate that the widget gains or looses\n-- the input focus. From these events a 'focus' signal is synthesized that\n-- indicates what maneuver lead to the input focus change (i.e. a tab or\n-- shift-tab key press).\n--\n-- For applications it is often sufficient to connect to the high-level\n-- signals rather than the low-level events. Only in cases where a custom\n-- widget is built based on the 'DarwingArea' skeleton, the functionality of\n-- such an application-specific widget needs to be implemented using events.\n--\n-- Every event is passed an 'Event' structure that contains the data of the\n-- event. The return value should be @True@ if the handler has dealt with the\n-- event and @False@ if the event should be propagated further. For instance,\n-- if a key press event that isn't meaningful in the widget, the handler can\n-- return @False@ such that the key is handled by the other widgets (the main\n-- menu, for instance).\n--\n\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.\n\n\neventM :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (EventM t Bool) -> IO (ConnectId w)\neventM name eMask after obj fun = do\n id <- connect_PTR__BOOL name after obj (runReaderT fun)\n widgetAddEvents obj eMask\n return id\n\n-- %hash c:6cc d:af3f\n-- | A mouse button has been depressed while the mouse pointer was within the\n-- widget area. Sets the widget's 'ButtonPressMask' flag.\n--\nbuttonPressEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonPressEvent = Signal (eventM \"button_press_event\" [ButtonPressMask])\n\n-- %hash c:62e8 d:af3f\n-- | A mouse button has been released. Sets the widget's 'ButtonReleaseMask'\n-- flag.\n--\nbuttonReleaseEvent :: WidgetClass self => Signal self (EventM EButton Bool)\nbuttonReleaseEvent = Signal (eventM \"button_release_event\" [ButtonReleaseMask])\n\n-- %hash c:23e5 d:af3f\n-- | The scroll wheel of the mouse has been used. Sets the widget's\n-- 'ScrollMask' flag.\n--\nscrollEvent :: WidgetClass self => Signal self (EventM EScroll Bool)\nscrollEvent = Signal (eventM \"scroll_event\" [ScrollMask])\n\n-- %hash c:ee92 d:af3f\n-- | The mouse pointer has moved. Since receiving all mouse movements is\n-- expensive, it is necessary to specify exactly what mouse motions are\n-- required by calling 'widgetAddEvents' on this widget with one or more of\n-- the following flags:\n--\n-- * 'PointerMotionMask': Track all movements.\n-- * 'ButtonMotionMask': Only track movements if a button is depressed.\n-- * 'Button1MotionMask': Only track movments if the left button is depressed.\n-- * 'Button2MotionMask': Only track movments if the middle button is depressed.\n-- * 'Button3MotionMask': Only track movments if the right button is depressed.\n--\n-- If the application cannot respond quickly enough to all mouse motions,\n-- it is possible to only receive motion signals on request. In this case,\n-- you need to add 'PointerMotionHintMask' to the flags above and call\n-- 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer' each time a\n-- motion even is received. Motion events will then be delayed until the\n-- function is called.\n--\nmotionNotifyEvent :: WidgetClass self => Signal self (EventM EMotion Bool)\nmotionNotifyEvent = Signal (eventM \"motion_notify_event\" [])\n\n-- %hash c:8783 d:3e27\n-- | The 'deleteEvent' signal is emitted if a user requests that a toplevel\n-- window is closed. The default handler for this signal destroys the window.\n-- Calling 'widgetHide' and returning @True@ on reception of this signal will\n-- cause the window to be hidden instead, so that it can later be shown again\n-- without reconstructing it.\n--\ndeleteEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndeleteEvent = Signal (eventM \"delete_event\" [])\n\n-- %hash c:c408 d:5514\n-- | The 'destroyEvent' signal is emitted when a 'DrawWindow' is destroyed.\n-- You rarely get this signal, because most widgets disconnect themselves from\n-- their window before they destroy it, so no widget owns the window at\n-- destroy time. However, you might want to connect to the 'objectDestroy'\n-- signal of 'Object'.\n--\ndestroyEvent :: WidgetClass self => Signal self (EventM EAny Bool)\ndestroyEvent = Signal (eventM \"destroy_event\" [])\n\n-- %hash c:c79e d:af3f\n\n-- | Instructs the widget to redraw.\n--\n-- * The 'DrawWindow' that needs to be redrawn is available via\n-- 'eventWindow'.\n--\n-- * The part that needs to be redrawn is available via 'eventArea' and\n-- 'eventRegion'. The options are, in order of efficiency: (a) redraw the\n-- entire window, (b) ask for the 'eventArea' and redraw that rectangle, (c)\n-- ask for the 'eventRegion' and redraw each of those rectangles.\n--\n-- Only the exposed region will be updated; see also\n-- 'drawWindowBeginPaintRegion'.\n\nexposeEvent :: WidgetClass self => Signal self (EventM EExpose Bool)\nexposeEvent = Signal (eventM \"expose_event\" [])\n\n-- %hash c:5ccd d:af3f\n-- | A key has been depressed. Sets the widget's 'KeyPressMask' flag.\n--\nkeyPressEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyPressEvent = Signal (eventM \"key_press_event\" [KeyPressMask])\n\n-- %hash c:bd29 d:af3f\n-- | A key has been released. Sets the widget's 'KeyReleaseMask' flag.\n--\nkeyReleaseEvent :: WidgetClass self => Signal self (EventM EKey Bool)\nkeyReleaseEvent = Signal (eventM \"key_release_event\" [KeyReleaseMask])\n\n-- %hash c:602e d:af3f\n-- | The mouse pointer has entered the widget. Sets the widget's\n-- 'EnterNotifyMask' flag.\n--\nenterNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nenterNotifyEvent = Signal (eventM \"enter_notify_event\" [EnterNotifyMask])\n\n-- %hash c:3bfb d:af3f\n-- | The mouse pointer has left the widget. Sets the widget's\n-- 'LeaveNotifyMask' flag.\n--\nleaveNotifyEvent :: WidgetClass self => Signal self (EventM ECrossing Bool)\nleaveNotifyEvent = Signal (eventM \"leave_notify_event\" [LeaveNotifyMask])\n\n-- %hash c:2b64 d:af3f\n-- | The size of the window has changed.\n--\nconfigureEvent :: WidgetClass self => Signal self (EventM EConfigure Bool)\nconfigureEvent = Signal (eventM \"configure_event\" [])\n\n-- %hash c:427e d:af3f\n-- | The widget gets the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusInEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusInEvent = Signal (eventM \"focus_in_event\" [FocusChangeMask])\n\n-- %hash c:5281 d:af3f\n-- | The widget lost the input focus. Sets the widget's 'FocusChangeMask' flag.\n--\nfocusOutEvent :: WidgetClass self => Signal self (EventM EFocus Bool)\nfocusOutEvent = Signal (eventM \"focus_out_event\" [FocusChangeMask])\n\n-- %hash c:63c4 d:af3f\n-- | The window is put onto the screen.\n--\nmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nmapEvent = Signal (eventM \"map_event\" [])\n\n-- %hash c:342d d:af3f\n-- | The window is taken off the screen.\n--\nunmapEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nunmapEvent = Signal (eventM \"unmap_event\" [])\n\n-- %hash c:a1dd d:af3f\n-- | A 'DrawWindow' may be associated with a set of properties that are\n-- identified by a 'PropertyTag'. This event is triggered if a property is\n-- changed or deleted. Sets the widget's 'PropertyChangeMask' flag.\n--\npropertyNotifyEvent :: WidgetClass self => Signal self (EventM EProperty Bool)\npropertyNotifyEvent = Signal (eventM \"property_notify_event\" [PropertyChangeMask])\n{- not sure if these are useful\n-- %hash c:58cc d:af3f\n-- | \n--\nselectionClearEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionClearEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_clear_event\")\n\n-- %hash c:4f92 d:af3f\n-- |\n--\nselectionRequestEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionRequestEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_request_event\")\n\n-- %hash c:b842 d:af3f\n-- |\n--\nselectionNotifyEvent :: WidgetClass self => Signal self ({-GdkEventSelection*-} Bool)\nselectionNotifyEvent = Signal (connect_{-GdkEventSelection*-}__BOOL \"selection_notify_event\")\n-}\n\n-- %hash c:b027 d:af3f\n-- | The pen of a graphics tablet was put down. Sets the widget's\n-- 'ProximityInMask' flag.\n--\nproximityInEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityInEvent = Signal (eventM \"proximity_in_event\" [ProximityInMask])\n\n-- %hash c:faca d:af3f\n-- | The pen of a graphics tablet was lifted off the tablet. Sets the widget's\n-- 'ProximityOutMask' flag.\n--\nproximityOutEvent :: WidgetClass self => Signal self (EventM EProximity Bool)\nproximityOutEvent = Signal (eventM \"proximity_out_event\" [ProximityOutMask])\n\n-- %hash c:db2c d:af3f\n-- | Emitted when the window visibility status has changed. Sets the widget's\n-- 'VisibilityNotifyMask' flag.\n--\nvisibilityNotifyEvent :: WidgetClass self => Signal self (EventM EVisibility Bool)\nvisibilityNotifyEvent = Signal (eventM \"visibility_notify_event\" [VisibilityNotifyMask])\n{-\n-- %hash c:3f5 d:af3f\n-- |\n--\nclientEvent :: WidgetClass self => Signal self ({-GdkEventClient*-} Bool)\nclientEvent = Signal (connect_{-GdkEventClient*-}__BOOL \"client_event\")\n-}\n\n-- %hash c:643c d:af3f\n-- | Generated when the area of a 'Drawable' being copied using, e.g.\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawDrawable', is completely available.\n--\nnoExposeEvent :: WidgetClass self => Signal self (EventM EAny Bool)\nnoExposeEvent = Signal (eventM \"no_expose_event\" [])\n\n-- %hash c:63b6 d:af3f\n-- | Emitted when the state of the window changes, i.e. when it is minimized,\n-- moved to the top, etc.\n--\nwindowStateEvent :: WidgetClass self => Signal self (EventM EWindowState Bool)\nwindowStateEvent = Signal (eventM \"window_state_event\" [])\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:502a d:e47a\n-- | Emitted when a pointer or keyboard grab on a window belonging to @widget@\n-- gets broken.\n--\n-- On X11, this happens when the grab window becomes unviewable (i.e. it or\n-- one of its ancestors is unmapped), or if the same application grabs the\n-- pointer or keyboard again.\n--\n-- * Available since Gtk+ version 2.8\n--\ngrabBrokenEvent :: WidgetClass self => Signal self (EventM EGrabBroken Bool)\ngrabBrokenEvent = Signal (eventM \"grab_broken_event\" [])\n#endif\n \n--------------------\n-- Deprecated Signals and Events\n\n#ifndef DISABLE_DEPRECATED\n\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-- | 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 'Graphics.UI.Gtk.Gdk.Events.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-- | A Button 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-- | \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-- | 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-- | This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @\\\"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-- | 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-- | 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-- | Mouse cursor entered widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Mouse cursor leaves widget.\n--\n-- * Contains a 'Crossing' event.\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-- | Instructs the widget to redraw.\n--\n-- * This event is useful for the 'DrawingArea'. On receiving this signal\n-- the content of the passed Rectangle or Region needs to be redrawn.\n-- The return value should be 'True' if the region was completely redrawn\n-- and 'False' if other handlers in the chain should be invoked.\n-- If a client will redraw the whole area and is not interested in the\n-- extra information in 'Expose', it is more efficient\n-- to use 'onExposeRect'.\n--\n-- * Widgets that are very expensive to re-render, such as an image editor,\n-- may prefer to use the 'onExpose' call back which delivers a\n-- 'Region' in addition to a 'Rectangle'. A 'Region' consists of several\n-- rectangles that need redrawing. The simpler 'onExposeRect' event encodes\n-- the area to be redrawn as a bounding rectangle which might be easier\n-- to deal with in a particular application.\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-- | Expose event delivering a 'Rectangle'.\n--\nonExposeRect, afterExposeRect ::\n WidgetClass w => w -> (Rectangle -> IO ()) -> IO (ConnectId w)\nonExposeRect w act = connect_BOXED__BOOL \"expose_event\"\n marshExposeRect False w (\\r -> act r >> return True)\nafterExposeRect w act = connect_BOXED__BOOL \"expose_event\" \n marshExposeRect True w (\\r -> act r >> return True)\n\n-- | This signal is called if the widget receives the input focus.\n--\nonFocus, afterFocus :: WidgetClass w => w -> (DirectionType -> IO Bool) ->\n IO (ConnectId w)\nonFocus = connect_ENUM__BOOL \"focus\" False\nafterFocus = connect_ENUM__BOOL \"focus\" True\n\n-- | 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-- | 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-- | 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-- '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-- | 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-- | The widget was asked to hide itself.\n--\n-- * This signal is emitted each time 'widgetHide' is called. Use\n-- 'onUnmap' 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-- | 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-- | 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-- | 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-- | \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-- | Track mouse movements.\n--\n-- * If @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 @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 'Graphics.UI.Gtk.Gdk.DrawWindow.drawWindowGetPointer'.\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 [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionMask, PointerMotionHintMask]\n else [PointerMotionMask]) True w\n\n-- | \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-- | \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-- | 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-- | 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-- | This widget's drawing area is about to be\n-- destroyed.\n--\nonRealize, afterRealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonRealize = connect_NONE__NONE \"realize\" False\nafterRealize = connect_NONE__NONE \"realize\" True\n\n-- | The mouse wheel has turned.\n--\n-- * The 'Event' is always '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-- | The widget was asked to show itself.\n--\n-- * This signal is emitted each time 'widgetShow' is called. Use\n-- 'onMap' 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-- | Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @\\\"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-- | 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-- | \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-- | 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-- | 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-- | \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-- | \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#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"28be677d50f096292dcee60b61d893dc44c26b51","subject":"Update SourceLanguage.chs to 2.10.4","message":"Update SourceLanguage.chs to 2.10.4\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguage.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceLanguage (\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n sourceLanguageGetStyleName,\n sourceLanguageGetStyleIds,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguage\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguage \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguage \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguage \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or empty if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the mime types or empty if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Returns the name of the style with ID @styleId@ defined by this language.\nsourceLanguageGetStyleName :: SourceLanguage \n -> String -- ^ @styleId@ a style ID\n -> IO String -- ^ returns the name of the style with ID @styleId@ defined by this language or empty if the style has no name or there is no style with ID @styleId@ defined by this language. The returned string is owned by the language and must not be modified.\nsourceLanguageGetStyleName sl styleId =\n withUTFString styleId $ \\styleIdPtr ->\n {#call gtk_source_language_get_style_name#}\n sl\n styleIdPtr\n >>= peekUTFString\n\n-- | Returns the ids of the styles defined by this language.\nsourceLanguageGetStyleIds :: SourceLanguage \n -> IO [String] -- ^ returns an array containing ids of the styles defined by this language or empty if no style is defined. \nsourceLanguageGetStyleIds sl = do\n globsArray <- {#call gtk_source_language_get_style_ids#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceLanguage (\n-- * Types\n SourceLanguage,\n SourceLanguageClass,\n\n-- * Methods\n castToSourceLanguage,\n sourceLanguageGetId,\n sourceLanguageGetName,\n sourceLanguageGetSection,\n sourceLanguageGetHidden,\n sourceLanguageGetMetadata,\n sourceLanguageGetMimeTypes,\n sourceLanguageGetGlobs,\n\n-- * Attributes\n sourceLanguageHidden,\n sourceLanguageId,\n sourceLanguageName,\n sourceLanguageSection\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n\n-- methods\n\n-- | Returns the ID of the language. The ID is not locale-dependent.\n--\nsourceLanguageGetId :: SourceLanguage\n -> IO String -- ^ returns the ID of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetId sl =\n {#call unsafe source_language_get_id#} sl >>= peekUTFString\n\n-- | Returns the localized name of the language.\n--\nsourceLanguageGetName :: SourceLanguage \n -> IO String -- ^ returns the name of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetName sl =\n {#call unsafe source_language_get_name#} sl >>= peekUTFString\n\n-- | Returns the localized section of the language. Each language belong to a section (ex. HTML belogs to\n-- the Markup section).\n--\nsourceLanguageGetSection :: SourceLanguage \n -> IO String -- ^ returns the section of language. The returned string is owned by language and should not be freed or modified.\nsourceLanguageGetSection sl =\n {#call unsafe source_language_get_section#} sl >>= peekUTFString\n\n-- | Returns whether the language should be hidden from the user.\n--\nsourceLanguageGetHidden :: SourceLanguage \n -> IO Bool -- ^ returns 'True' if the language should be hidden, 'False' otherwise. \nsourceLanguageGetHidden sl = liftM toBool $\n {#call unsafe source_language_get_hidden#} sl\n\n-- |\n--\nsourceLanguageGetMetadata :: SourceLanguage \n -> String -- ^ @name@ metadata property name.\n -> IO String -- ^ returns value of property name stored in the metadata of language or emtpy if language doesn't contain that metadata\nsourceLanguageGetMetadata sl name = do\n withUTFString name ({#call unsafe source_language_get_metadata#} sl) >>= peekUTFString\n\n-- | Returns the mime types associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata ' to retrieve the \"mimetypes\" metadata property and split it into\n-- an array.\n--\nsourceLanguageGetMimeTypes :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the mime types or emtpy if no mime types are found. The \nsourceLanguageGetMimeTypes sl = do\n mimeTypesArray <- {#call unsafe source_language_get_mime_types#} sl\n mimeTypes <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 mimeTypesArray\n {# call g_strfreev #} mimeTypesArray\n return mimeTypes\n\n-- | Returns the globs associated to this language. This is just an utility wrapper around\n-- 'sourceLanguageGetMetadata' to retrieve the \"globs\" metadata property and split it into an\n-- array.\n--\nsourceLanguageGetGlobs :: SourceLanguage \n -> IO [String] -- ^ returns an array containing the globs or empty if no globs are found. \nsourceLanguageGetGlobs sl = do\n globsArray <- {#call unsafe source_language_get_globs#} sl\n globs <- liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 globsArray\n {# call g_strfreev #} globsArray\n return globs\n\n-- | Whether the language should be hidden from the user.\n-- \n-- Default value: 'False'\n--\nsourceLanguageHidden :: ReadAttr SourceLanguage Bool\nsourceLanguageHidden = readAttrFromBoolProperty \"hidden\"\n\n-- | Language id.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageId :: ReadAttr SourceLanguage String\nsourceLanguageId = readAttrFromStringProperty \"id\"\n\n-- | Language name.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageName :: ReadAttr SourceLanguage String\nsourceLanguageName = readAttrFromStringProperty \"name\"\n\n-- | Language section.\n-- \n-- Default value: \\\"\\\"\n--\nsourceLanguageSection :: ReadAttr SourceLanguage String\nsourceLanguageSection = readAttrFromStringProperty \"section\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"aaa80834686f83509a168e8d48ae5e0d6586e9a1","subject":"Added function to read status out of the future","message":"Added function to read status out of the future\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_file":"src\/Control\/Parallel\/MPI\/Serializable.chs","new_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , getFutureStatus\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\ngetFutureStatus :: Future a -> IO Status\ngetFutureStatus = readMVar . futureStatus\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\n#ifdef MPICH2\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n#else\nwait request =\n alloca $ \\statusPtr -> do\n checkError $ Internal.wait (castPtr request) (castPtr statusPtr)\n peek statusPtr\n#endif\n","old_contents":"{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n\nmodule Control.Parallel.MPI.Serializable\n ( module Datatype\n , module Comm\n , module Status\n , module Tag\n , module Rank\n , mpi\n , init\n , finalize\n , commSize\n , commRank\n , probe\n , send\n , sendBS\n , recv\n , recvBS\n , iSend\n , iSendBS\n , Future\n , cancelFuture\n , pollFuture\n , waitFuture\n , recvFuture\n , bcast\n , barrier\n , wait\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Control.Concurrent (forkOS, forkIO, ThreadId, killThread)\nimport Control.Concurrent.MVar (MVar, newEmptyMVar, tryTakeMVar, readMVar, putMVar)\nimport Data.ByteString.Unsafe as BS\nimport qualified Data.ByteString as BS\nimport Data.Serialize (encode, decode, Serialize)\nimport qualified Control.Parallel.MPI.Internal as Internal \nimport Control.Parallel.MPI.Datatype as Datatype\nimport Control.Parallel.MPI.Comm as Comm\nimport Control.Parallel.MPI.Request as Request\nimport Control.Parallel.MPI.Status as Status\nimport Control.Parallel.MPI.Utils (checkError)\nimport Control.Parallel.MPI.Tag as Tag\nimport Control.Parallel.MPI.Rank as Rank\n\n#include \n\nmpi :: IO () -> IO ()\nmpi action = init >> action >> finalize\n\ninit :: IO ()\ninit = checkError Internal.init\n\nfinalize :: IO ()\nfinalize = checkError Internal.finalize\n\ncommSize :: Comm -> IO Int\ncommSize comm = do\n alloca $ \\ptr -> do\n checkError $ Internal.commSize comm ptr\n size <- peek ptr\n return $ cIntConv size\n\ncommRank :: Comm -> IO Rank\ncommRank comm =\n alloca $ \\ptr -> do\n checkError $ Internal.commRank comm ptr\n rank <- peek ptr\n return $ toRank rank\n\nprobe :: Rank -> Tag -> Comm -> IO Status\nprobe rank tag comm = do\n let cSource = fromRank rank\n cTag = fromTag tag\n alloca $ \\statusPtr -> do\n checkError $ Internal.probe cSource cTag comm $ castPtr statusPtr\n peek statusPtr\n\nsend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO ()\nsend = sendBS . encode\n\nsendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO ()\nsendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n unsafeUseAsCString bs $ \\cString ->\n checkError $ Internal.send (castPtr cString) cCount byte cRank cTag comm\n\nrecv :: Serialize msg => Rank -> Tag -> Comm -> IO (Status, msg)\nrecv rank tag comm = do\n (status, bs) <- recvBS rank tag comm\n case decode bs of\n Left e -> fail e\n Right val -> return (status, val)\n\nrecvBS :: Rank -> Tag -> Comm -> IO (Status, BS.ByteString)\nrecvBS rank tag comm = do\n probeStatus <- probe rank tag comm\n let count = status_count probeStatus\n cSource = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv count\n allocaBytes count\n (\\bufferPtr ->\n alloca $ \\statusPtr -> do\n checkError $ Internal.recv bufferPtr cCount byte cSource cTag comm $ castPtr statusPtr\n recvStatus <- peek statusPtr\n message <- BS.packCStringLen (castPtr bufferPtr, count)\n return (recvStatus, message))\n\niSend :: Serialize msg => msg -> Rank -> Tag -> Comm -> IO Request\niSend = iSendBS . encode\n\niSendBS :: BS.ByteString -> Rank -> Tag -> Comm -> IO Request\niSendBS bs rank tag comm = do\n let cRank = fromRank rank\n cTag = fromTag tag\n cCount = cIntConv $ BS.length bs\n alloca $ \\requestPtr ->\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.iSend (castPtr cString) cCount byte cRank cTag comm requestPtr\n peek requestPtr\n\ndata Future a =\n Future\n { futureThread :: ThreadId\n , futureStatus :: MVar Status\n , futureVal :: MVar a\n }\n\nwaitFuture :: Future a -> IO a\nwaitFuture = readMVar . futureVal\n\npollFuture :: Future a -> IO (Maybe a)\npollFuture = tryTakeMVar . futureVal\n\n-- May want to stop people from waiting on Futures which are killed...\ncancelFuture :: Future a -> IO ()\ncancelFuture = killThread . futureThread\n\nrecvFuture :: Serialize msg => Rank -> Tag -> Comm -> IO (Future msg)\nrecvFuture rank tag comm = do\n valRef <- newEmptyMVar\n statusRef <- newEmptyMVar\n -- is forkIO acceptable here? Depends on thread local stateness of MPI.\n -- threadId <- forkOS $ do\n threadId <- forkIO $ do\n -- do a synchronous recv in another thread\n (status, msg) <- recv rank tag comm\n putMVar valRef msg\n putMVar statusRef status\n return $ Future { futureThread = threadId, futureStatus = statusRef, futureVal = valRef }\n\n{- Broadcast is tricky because the receiver doesn't know how much memory to allocate.\n The C interface assumes the sender and receiver agree on the size in advance, but\n this is not useful for the Haskell interface (where we want to send arbitrary sized\n values) because the sender is the only process which has the actual data available\n\n The work around is for the sender to send two messages. The first says how much data\n is coming. The second message sends the actual data. We rely on the two messages being\n sent and received in this order. Conversely the receiver gets two messages. The first is\n the size of memory to allocate and the second in the actual message.\n\n The obvious downside of this approach is that it requires two broadcasts for one\n payload. Communication costs can be expensive.\n\n The idea for this scheme was inspired by the Ocaml bindings. Therefore there is\n some precedent for doing it this way.\n-}\n\nbcast :: Serialize msg => msg -> Rank -> Comm -> IO msg\nbcast msg rootRank comm = do\n myRank <- commRank comm\n let cRank = fromRank rootRank\n if myRank == rootRank\n then do\n let bs = encode msg\n cCount = cIntConv $ BS.length bs\n -- broadcast the size of the message first\n alloca $ \\ptr -> do\n poke ptr cCount\n let numberOfInts = 1::CInt\n checkError $ Internal.bcast (castPtr ptr) numberOfInts int cRank comm\n -- then broadcast the actual message\n unsafeUseAsCString bs $ \\cString -> do\n checkError $ Internal.bcast (castPtr cString) cCount byte cRank comm\n return msg\n else do\n -- receive the broadcast of the size\n count <- alloca $ \\ptr -> do\n checkError $ Internal.bcast (castPtr ptr) 1 int cRank comm\n peek ptr\n -- receive the broadcast of the message\n allocaBytes count $\n \\bufferPtr -> do\n let cCount = cIntConv count\n checkError $ Internal.bcast bufferPtr cCount byte cRank comm \n bs <- BS.packCStringLen (castPtr bufferPtr, count) \n case decode bs of\n Left e -> fail e\n Right val -> return val\n\nbarrier :: Comm -> IO ()\nbarrier comm = checkError $ Internal.barrier comm\n\nwait :: Request -> IO Status\n#ifdef MPICH2\nwait request =\n alloca $ \\statusPtr ->\n alloca $ \\reqPtr -> do\n poke reqPtr request\n checkError $ Internal.wait reqPtr (castPtr statusPtr)\n peek statusPtr\n#else\nwait request =\n alloca $ \\statusPtr -> do\n checkError $ Internal.wait (castPtr request) (castPtr statusPtr)\n peek statusPtr\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"47be5eccd67f4872141f026853675e70f642e01a","subject":"add get program binaries function","message":"add get program binaries function\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Program.chs","new_file":"src\/System\/GPU\/OpenCL\/Program.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.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram, clGetProgramReferenceCount, \n clGetProgramContext, clGetProgramNumDevices, clGetProgramDevices,\n clGetProgramSource, clGetProgramBinarySizes, clGetProgramBinaries, \n clGetProgramBuildStatus, clGetProgramBuildOptions, clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clGetKernelFunctionName, clGetKernelNumArgs, clGetKernelReferenceCount, \n clGetKernelContext, clGetKernelProgram\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLKernel, CLDeviceID, CLError(..), \n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, wrapPError, \n wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\n--foreign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n-- CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import ccall \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import ccall \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import ccall \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it returns one of the\nfollowing error values:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the program 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.\nclGetProgramReferenceCount :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\nclGetProgramContext :: CLProgram -> IO (Either CLError CLContext)\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\nclGetProgramNumDevices :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\nclGetProgramDevices :: CLProgram -> IO (Either CLError [CLDeviceID])\nclGetProgramDevices prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\nclGetProgramSource :: CLProgram -> IO (Either CLError String)\nclGetProgramSource prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\nclGetProgramBinarySizes :: CLProgram -> IO (Either CLError [CSize])\nclGetProgramBinarySizes prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n-}\nclGetProgramBinaries :: CLProgram -> IO (Either CLError [[Word8]])\nclGetProgramBinaries prg = do\n sval <- clGetProgramBinarySizes prg\n case sval of\n Left err -> return . Left $ err\n Right sizes -> do\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then do\n vals <- zipWithM peekArray (map fromIntegral sizes) buffers\n return . Right $ vals\n else return . Left . toEnum . fromIntegral $ errcode\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO (Either CLError CLBuildStatus)\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildOptions prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildLog prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it returns one of the following error values:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO (Either CLError CLKernel)\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, returns 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, returns 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and returns\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO (Either CLError [CLKernel])\nclCreateKernelsInProgram prg = do\n nks <- alloca $ \\pn -> do\n errcode <- raw_clCreateKernelsInProgram prg 0 nullPtr pn\n if errcode == (getCLValue CL_SUCCESS)\n then peek pn >>= (return . Right)\n else return $ Left errcode\n \n case nks of\n Left err -> return . Left . getEnumCL $ err\n Right n -> allocaArray (fromIntegral n) $ \\pks -> do\n errcode <- raw_clCreateKernelsInProgram prg n pks nullPtr\n if errcode == (getCLValue CL_SUCCESS)\n then peekArray (fromIntegral n) pks >>= (return . Right)\n else return . Left .getEnumCL $ errcode\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO (Either CLError CSize)\ngetKernelInfoSize krn infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetKernelInfo krn infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the kernel function name.\nclGetKernelFunctionName :: CLKernel -> IO (Either CLError String)\nclGetKernelFunctionName krn = do\n sval <- getKernelInfoSize krn infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\nclGetKernelNumArgs :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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.\nclGetKernelReferenceCount :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\nclGetKernelContext :: CLKernel -> IO (Either CLError CLContext)\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\nclGetKernelProgram :: CLKernel -> IO (Either CLError CLProgram)\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\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.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram, clGetProgramReferenceCount, \n clGetProgramContext, clGetProgramNumDevices, clGetProgramDevices,\n clGetProgramSource, clGetProgramBinarySizes, clGetProgramBinaries, \n clGetProgramBuildStatus, clGetProgramBuildOptions, clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clGetKernelFunctionName, clGetKernelNumArgs, clGetKernelReferenceCount, \n clGetKernelContext, clGetKernelProgram\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLProgram, CLContext, CLKernel, CLDeviceID, CLError(..), \n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, wrapPError, \n wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import ccall \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\n--foreign import ccall \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n-- CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import ccall \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import ccall \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import ccall \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import ccall \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import ccall \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import ccall \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import ccall \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import ccall \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it returns one of the\nfollowing error values:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO (Either CLError CLProgram)\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram returns the following errors when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO (Either CLError ())\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n errcode <- raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then return $ Right ()\n else return . Left . toEnum . fromIntegral $ errcode\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the program 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.\nclGetProgramReferenceCount :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\nclGetProgramContext :: CLProgram -> IO (Either CLError CLContext)\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\nclGetProgramNumDevices :: CLProgram -> IO (Either CLError CLuint)\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\nclGetProgramDevices :: CLProgram -> IO (Either CLError [CLDeviceID])\nclGetProgramDevices prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\nclGetProgramSource :: CLProgram -> IO (Either CLError String)\nclGetProgramSource prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\nclGetProgramBinarySizes :: CLProgram -> IO (Either CLError [CSize])\nclGetProgramBinarySizes prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n errcode <- raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekArray (numElems size) buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n-}\n--clGetProgramBinaries :: CLProgram -> IO (Either CLError [[Word8]])\nclGetProgramBinaries prg = do\n sval <- getProgramInfoSize prg infoid\n case sval of\n Left err -> return . Left $ err\n Right size -> allocaArray (numElems size) $ \\(buff :: Ptr (Ptr Word8)) -> do\n print sval\n print buff\n return . Left $ CL_SUCCESS\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::Ptr Word8)\n{-\nCL_PROGRAM_BINARIES\tReturn type: unsigned char *[]\nReturn the program binaries for all devices associated with program. For each device in program, the binary returned can be the binary specified for the device when program is created with clCreateProgramWithBinary or it can be the executable binary generated by clBuildProgram. If program is created with clCreateProgramWithSource, the binary returned is the binary generated by clBuildProgram. The bits returned can be an implementation-specific intermediate representation (a.k.a. IR) or device specific executable bits or both. The decision on which information is returned in the binary is up to the OpenCL implementation.\n\nparam_value points to an array of n pointers where n is the number of devices associated with program. The buffer sizes needed to allocate the memory that these n pointers refer to can be queried using the CL_PROGRAM_BINARY_SIZES query as described in this table.\n\nEach entry in this array is used by the implementation as the location in memory where to copy the program binary for a specific device, if there is a binary available. To find out which device the program binary in the array refers to, use the CL_PROGRAM_DEVICES query to get the list of devices. There is a one-to-one correspondence between the array of n pointers returned by CL_PROGRAM_BINARIES and array of devices returned by CL_PROGRAM_DEVICES.\n-}\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO (Either CLError CSize)\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO (Either CLError CLBuildStatus)\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildOptions prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO (Either CLError String)\nclGetProgramBuildLog prg device = do\n sval <- getProgramBuildInfoSize prg device infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it returns one of the following error values:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO (Either CLError CLKernel)\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, returns 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, returns 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and returns\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO (Either CLError [CLKernel])\nclCreateKernelsInProgram prg = do\n nks <- alloca $ \\pn -> do\n errcode <- raw_clCreateKernelsInProgram prg 0 nullPtr pn\n if errcode == (getCLValue CL_SUCCESS)\n then peek pn >>= (return . Right)\n else return $ Left errcode\n \n case nks of\n Left err -> return . Left . getEnumCL $ err\n Right n -> allocaArray (fromIntegral n) $ \\pks -> do\n errcode <- raw_clCreateKernelsInProgram prg n pks nullPtr\n if errcode == (getCLValue CL_SUCCESS)\n then peekArray (fromIntegral n) pks >>= (return . Right)\n else return . Left .getEnumCL $ errcode\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO (Either CLError CSize)\ngetKernelInfoSize krn infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n errcode <- raw_clGetKernelInfo krn infoid 0 nullPtr value_size\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peek value_size\n else return . Left . toEnum . fromIntegral $ errcode\n \n-- | Return the kernel function name.\nclGetKernelFunctionName :: CLKernel -> IO (Either CLError String)\nclGetKernelFunctionName krn = do\n sval <- getKernelInfoSize krn infoid\n case sval of\n Left err -> return . Left $ err\n Right n -> allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n errcode <- raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS)\n then fmap Right $ peekCString buff\n else return . Left . toEnum . fromIntegral $ errcode\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\nclGetKernelNumArgs :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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.\nclGetKernelReferenceCount :: CLKernel -> IO (Either CLError CLuint)\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\nclGetKernelContext :: CLKernel -> IO (Either CLError CLContext)\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\nclGetKernelProgram :: CLKernel -> IO (Either CLError CLProgram)\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"356e7a94b35a8d08bfed567a85c1897fb189751c","subject":"use the C enum rather than our own #c block","message":"use the C enum rather than our own #c block\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/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\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#if CUDA_VERSION >= 6000\n#c\ntypedef enum CUmemAttachFlags_option_enum {\n CU_MEM_ATTACH_OPTION_GLOBAL = CU_MEM_ATTACH_GLOBAL,\n CU_MEM_ATTACH_OPTION_HOST = CU_MEM_ATTACH_HOST,\n CU_MEM_ATTACH_OPTION_SINGLE = CU_MEM_ATTACH_SINGLE\n} CUmemAttachFlags_option;\n#endc\n#endif\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\n{# enum CUmemAttachFlags_option as AttachFlag\n { underscoreToCase }\n with prefix=\"CU_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 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":"f84cf6f6090986000746735c1fdd9a255edeca3a","subject":"[project @ 2003-11-03 14:21:54 by juhp]","message":"[project @ 2003-11-03 14:21:54 by juhp]\n\nEmacs file variables only work on the first line.\n\ndarcs-hash:20031103142154-f332a-ff4f2bcf438008595aab0ad6a80a7be2aa1c6093.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/multiline\/TextIter.chs","new_file":"gtk\/multiline\/TextIter.chs","new_contents":"{-# OPTIONS -cpp #-} -- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter TextBuffer@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.11 $ from $Date: 2003\/11\/03 14:21:54 $\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-- @ref data 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 @ref data 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 FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (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 (text_iter_free iterPtr)\n\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall unsafe \">k_text_iter_free\"\n text_iter_free' :: FinalizerPtr TextIter\n\ntext_iter_free :: Ptr TextIter -> FinalizerPtr TextIter\ntext_iter_free _ = text_iter_free'\n\n#elif __GLASGOW_HASKELL__>=504\n\nforeign import ccall unsafe \"gtk_text_iter_free\"\n text_iter_free :: Ptr TextIter -> IO ()\n\n#else\n\nforeign import ccall \"gtk_text_iter_free\" unsafe\n text_iter_free :: Ptr TextIter -> IO ()\n\n#endif\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 (text_iter_free iterPtr)\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 (text_iter_free 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref data Pixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe Pixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (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-- @method textIterGetAttributes@ Get the text attributes at the iterator.\n--\n-- * The @ref arg ta@ argument gives the default values if no specific \n-- attributes are set at that specific location.\n--\n-- * The function returns @literal Nothing@ if the text at the iterator has \n-- the same attributes.\ntextIterGetAttributes = undefined\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\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall \"wrapper\" mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#else\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#endif\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 $ withUTFString 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 $ withUTFString 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":"{-# OPTIONS -cpp #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter TextBuffer@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.10 $ from $Date: 2003\/10\/21 21:28:53 $\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-- @ref data 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 @ref data 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 FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (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 (text_iter_free iterPtr)\n\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall unsafe \">k_text_iter_free\"\n text_iter_free' :: FinalizerPtr TextIter\n\ntext_iter_free :: Ptr TextIter -> FinalizerPtr TextIter\ntext_iter_free _ = text_iter_free'\n\n#elif __GLASGOW_HASKELL__>=504\n\nforeign import ccall unsafe \"gtk_text_iter_free\"\n text_iter_free :: Ptr TextIter -> IO ()\n\n#else\n\nforeign import ccall \"gtk_text_iter_free\" unsafe\n text_iter_free :: Ptr TextIter -> IO ()\n\n#endif\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 (text_iter_free iterPtr)\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 (text_iter_free 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString 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 <- peekUTFString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref data Pixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe Pixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (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-- @method textIterGetAttributes@ Get the text attributes at the iterator.\n--\n-- * The @ref arg ta@ argument gives the default values if no specific \n-- attributes are set at that specific location.\n--\n-- * The function returns @literal Nothing@ if the text at the iterator has \n-- the same attributes.\ntextIterGetAttributes = undefined\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\n#if __GLASGOW_HASKELL__>=600\n\nforeign import ccall \"wrapper\" mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#else\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n#endif\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 $ withUTFString 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 $ withUTFString 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":"28ebe9fb9fbfcd8e694b4f6c39e15b34591f1cbb","subject":"Fix SourceMark.chs docs.","message":"Fix SourceMark.chs docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceMark.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts, Andy Stewart\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n-- * Description\n-- | A 'SourceMark' marks a position in the text where you want to display additional info. It is based\n-- on 'TextMark' and thus is still valid after the text has changed though its position may change.\n-- \n-- 'SourceMarks' are organised in categories which you have to set when you create the mark. Each\n-- category can have a pixbuf and a priority associated using @gtkSourceViewSetMarkCategoryPixbuf@\n-- and @gtkSourceViewSetMarkCategoryPriority@. The pixbuf will be displayed in the margin at the\n-- line where the mark residents if the 'showLineMarks' property is set to 'True'. If there are\n-- multiple marks in the same line, the pixbufs will be drawn on top of each other. The mark with the\n-- highest priority will be drawn on top.\n\n-- * Types\n SourceMark,\n\n-- * Methods\n castToSourceMark,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Returns the mark category\n-- \nsourceMarkGetCategory :: SourceMark\n -> IO String -- ^ returns the category of the 'SourceMark' \nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | Returns the next 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If there\n-- is no next mark, 'Nothing' will be returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkNext :: SourceMark \n -> String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO SourceMark -- ^ returns the next 'SourceMark' or 'Nothing' \nsourceMarkNext mark category = makeNewGObject mkSourceMark $\n withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | Returns the previous 'SourceMark' in the buffer or 'Nothing' if the mark was not added to a buffer. If\n-- there is no previous mark, 'Nothing' is returned.\n-- \n-- If category is 'Nothing', looks for marks of any category\n-- \nsourceMarkPrev :: SourceMark \n -> String -- ^ @category@ a string specifying the mark category or 'Nothing' \n -> IO SourceMark -- ^ returns the previous 'SourceMark' or 'Nothing' \nsourceMarkPrev mark category = makeNewGObject mkSourceMark $\n withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceMark\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n--\n-- Created: 26 October 2003\n--\n-- Copyright (C) 2003-2005 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.SourceMark (\n SourceMark,\n castToSourceMark,\n sourceMarkGetCategory,\n sourceMarkNext,\n sourceMarkPrev\n) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(makeNewGObject)\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | \n-- \nsourceMarkGetCategory :: SourceMark -> IO String\nsourceMarkGetCategory mark = do\n strPtr <- {#call unsafe source_mark_get_category#} mark\n markType <- peekUTFString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n return markType\n\n-- | \n-- \nsourceMarkNext :: SourceMark -> String -> IO SourceMark\nsourceMarkNext mark category = makeNewGObject mkSourceMark $\n withUTFString category $ {#call unsafe source_mark_next#} mark\n\n-- | \n-- \nsourceMarkPrev :: SourceMark -> String -> IO SourceMark\nsourceMarkPrev mark category = makeNewGObject mkSourceMark $\n withUTFString category $ {#call unsafe source_mark_prev#} mark\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"201881b7feb199598ef5576782681e09aeb6c601","subject":"refs #10: move withMaybeArray to own function","message":"refs #10: move withMaybeArray to own function\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.chs","new_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.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.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), CLMapFlag(..),\n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\n clEnqueueUnmapMemObject,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clFinish\" raw_clFinish ::\n CLCommandQueue -> IO CLint\n\n-- -----------------------------------------------------------------------------\nwithMaybeArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b\nwithMaybeArray [] = ($ nullPtr)\nwithMaybeArray xs = withArray xs\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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n \n{-| Enqueues a command to unmap a previously mapped region of a memory object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\nReads or writes from the host using the pointer returned by 'clEnqueueMapBuffer'\nor 'clEnqueueMapImage' are considered to be complete.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' increments the mapped count of the\nmemory object. The initial mapped count value of a memory object is\nzero. Multiple calls to 'clEnqueueMapBuffer' or 'clEnqueueMapImage' on the same\nmemory object will increment this mapped count by appropriate number of\ncalls. 'clEnqueueUnmapMemObject' decrements the mapped count of the memory\nobject.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' act as synchronization points for a\nregion of the memory object being mapped.\n\n'clEnqueueUnmapMemObject' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\n\n * CL_INVALID_COMMAND_QUEUE if command_queue is not a valid command-queue.\n\n * CL_INVALID_MEM_OBJECT if memobj is not a valid memory object.\n\n * CL_INVALID_VALUE if mapped_ptr is not a valid pointer returned by\n'clEnqueueMapBuffer' or 'clEnqueueMapImage' for memobj.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n * CL_INVALID_CONTEXT if the context associated with command_queue and memobj\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n-}\nclEnqueueUnmapMemObject :: CLCommandQueue \n -> CLMem -- ^ A valid memory object. The OpenCL\n -- context associated with command_queue and\n -- memobj must be the same.\n -> Ptr () -- ^ The host address returned by a\n -- previous call to 'clEnqueueMapBuffer' or\n -- 'clEnqueueMapImage' for memobj.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before\n -- 'clEnqueueUnmapMemObject' can be\n -- executed. If event_wait_list is\n -- empty, then 'clEnqueueUnmapMemObject'\n -- does not wait on any event to\n -- complete. The events specified in\n -- event_wait_list act as\n -- synchronization points. The context\n -- associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n\n -> IO CLEvent\nclEnqueueUnmapMemObject cq mem pp = clEnqueue (raw_clEnqueueUnmapMemObject cq mem pp)\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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":"{- 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.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), CLMapFlag(..),\n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\n clEnqueueUnmapMemObject,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n \n{-| Enqueues a command to unmap a previously mapped region of a memory object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\nReads or writes from the host using the pointer returned by 'clEnqueueMapBuffer'\nor 'clEnqueueMapImage' are considered to be complete.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' increments the mapped count of the\nmemory object. The initial mapped count value of a memory object is\nzero. Multiple calls to 'clEnqueueMapBuffer' or 'clEnqueueMapImage' on the same\nmemory object will increment this mapped count by appropriate number of\ncalls. 'clEnqueueUnmapMemObject' decrements the mapped count of the memory\nobject.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' act as synchronization points for a\nregion of the memory object being mapped.\n\n'clEnqueueUnmapMemObject' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\n\n * CL_INVALID_COMMAND_QUEUE if command_queue is not a valid command-queue.\n\n * CL_INVALID_MEM_OBJECT if memobj is not a valid memory object.\n\n * CL_INVALID_VALUE if mapped_ptr is not a valid pointer returned by\n'clEnqueueMapBuffer' or 'clEnqueueMapImage' for memobj.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n * CL_INVALID_CONTEXT if the context associated with command_queue and memobj\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n-}\nclEnqueueUnmapMemObject :: CLCommandQueue \n -> CLMem -- ^ A valid memory object. The OpenCL\n -- context associated with command_queue and\n -- memobj must be the same.\n -> Ptr () -- ^ The host address returned by a\n -- previous call to 'clEnqueueMapBuffer' or\n -- 'clEnqueueMapImage' for memobj.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before\n -- 'clEnqueueUnmapMemObject' can be\n -- executed. If event_wait_list is\n -- empty, then 'clEnqueueUnmapMemObject'\n -- does not wait on any event to\n -- complete. The events specified in\n -- event_wait_list act as\n -- synchronization points. The context\n -- associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n\n -> IO CLEvent\nclEnqueueUnmapMemObject cq mem pp = clEnqueue (raw_clEnqueueUnmapMemObject cq mem pp)\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (map fromIntegral lws) $ \\plws -> do\n clEnqueue (raw_clEnqueueNDRangeKernel cq krn num nullPtr pgws plws) events\n where\n num = fromIntegral $ length gws\n withMaybeArray [] = ($ nullPtr)\n withMaybeArray xs = withArray xs\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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2c8f405eba832f713f9b9266a63d30ff03a8e35b","subject":"Fix TextView signals.","message":"Fix TextView signals.\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","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":"6cea5840b241d39bc77c613adac4b4ea917609ea","subject":"[project @ 2005-02-13 16:59:11 by as49] Remove this file which was renamed to Image.chs.pp.","message":"[project @ 2005-02-13 16:59:11 by as49]\nRemove this file which was renamed to Image.chs.pp.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Image.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Display\/Image.chs","new_contents":"","old_contents":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Image\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2005\/02\/13 16:25:56 $\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-- This widget displays an image.\n--\n--\n-- * Because Haskell is not the best language to modify large images directly\n-- only functions are bound that allow loading images from disc or by stock\n-- names.\n--\n-- * Another function for extracting the 'Pixbuf' is added for \n-- 'CellRenderer'.\n--\n-- TODO\n--\n-- * Figure out what other functions are useful within Haskell. Maybe we should\n-- support loading Pixmaps without exposing them.\n--\nmodule Graphics.UI.Gtk.Display.Image (\n Image,\n ImageClass,\n castToImage,\n imageNewFromFile,\n IconSize,\n iconSizeMenu,\n iconSizeSmallToolbar,\n iconSizeLargeToolbar,\n iconSizeButton,\n iconSizeDialog,\n imageNewFromStock,\n imageGetPixbuf,\n imageSetFromPixbuf,\n imageNewFromPixbuf\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(IconSize, iconSizeInvalid, iconSizeMenu,\n\t\t\t\t\t iconSizeSmallToolbar, iconSizeLargeToolbar,\n\t\t\t\t\t iconSizeButton, iconSizeDialog)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create an image by loading a file.\n--\nimageNewFromFile :: FilePath -> IO Image\nimageNewFromFile path = makeNewObject mkImage $ liftM castPtr $ \n\n\n\n withUTFString path {#call unsafe image_new_from_file#}\n\n\n-- | Create a set of images by specifying a stock\n-- object.\n--\nimageNewFromStock :: String -> IconSize -> IO Image\nimageNewFromStock stock ic = withUTFString stock $ \\strPtr -> \n makeNewObject mkImage $ liftM castPtr $ {#call unsafe image_new_from_stock#}\n strPtr (fromIntegral ic)\n\n-- | Extract the Pixbuf from the 'Image'.\n--\nimageGetPixbuf :: Image -> IO Pixbuf\nimageGetPixbuf img = makeNewGObject mkPixbuf $ liftM castPtr $\n throwIfNull \"Image.imageGetPixbuf: The image contains no Pixbuf object.\" $\n {#call unsafe image_get_pixbuf#} img\n\n\n-- | Overwrite the current content of the 'Image' with a new 'Pixbuf'.\n--\nimageSetFromPixbuf :: Image -> Pixbuf -> IO ()\nimageSetFromPixbuf img pb = {#call unsafe gtk_image_set_from_pixbuf#} img pb\n\n-- | Create an 'Image' from a \n-- 'Pixbuf'.\n--\nimageNewFromPixbuf :: Pixbuf -> IO Image\nimageNewFromPixbuf pbuf = makeNewObject mkImage $ liftM castPtr $\n {#call unsafe image_new_from_pixbuf#} pbuf\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"fbf5504c5a5234735d073725efe9c0ad5cf64dbf","subject":"Finished haddock in Internal.chs","message":"Finished haddock in Internal.chs\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(..),\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","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. DONE\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. DONE\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- * Ranks. DONE\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. DONE\n -- ** Tags. DONE\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations. DONE\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations. DONE\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations. DONE\n -- ** One-to-all. DONE\n bcast, scatter, scatterv,\n -- ** All-to-one. DONE\n gather, gatherv, reduce,\n -- ** All-to-all. DONE\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations. DONE\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing. DONE\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\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 -- ^ Major part\n , subversion :: Int -- ^ Minor part\n }\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-- | 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, 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{-| 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 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\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 #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A 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":"16511bebeb47d2026ef16818b2c869eea399afc1","subject":"Fix SourceStyleSchemeManager docs.","message":"Fix SourceStyleSchemeManager docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleSchemeManager.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleSchemeManager.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceStyleSchemeManager (\n-- * Types\n SourceStyleSchemeManager,\n SourceStyleSchemeManagerClass,\n\n-- * Methods \n sourceStyleSchemeManagerNew,\n sourceStyleSchemeManagerGetDefault,\n sourceStyleSchemeManagerSetSearchPath,\n sourceStyleSchemeManagerAppendSearchPath,\n sourceStyleSchemeManagerPrependSearchPath,\n sourceStyleSchemeManagerGetSearchPath,\n sourceStyleSchemeManagerGetSchemeIds,\n sourceStyleSchemeManagerGetScheme,\n sourceStyleSchemeManagerForceRescan,\n\n-- * Attributes\n sourceStyleSchemeManagerStyleIds,\n sourceStyleSchemeManagerSearchPath\n ) where\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\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\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n-- | Creates a new style manager. If you do not need more than one style manager then use\n-- 'sourceStyleSchemeManagerGetDefault' instead.\n--\nsourceStyleSchemeManagerNew :: IO SourceStyleSchemeManager\nsourceStyleSchemeManagerNew = constructNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_new#}\n\n-- | Returns the default 'SourceStyleSchemeManager' instance.\n--\nsourceStyleSchemeManagerGetDefault :: IO SourceStyleSchemeManager -- ^ returns a 'SourceStyleSchemeManager'. Return value is owned by 'SourceView' library and must not be unref'ed.\nsourceStyleSchemeManagerGetDefault = makeNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_get_default#}\n\n-- | Sets the list of directories where the manager looks for style scheme files. If dirs is 'Nothing', the\n-- search path is reset to default.\n--\nsourceStyleSchemeManagerSetSearchPath :: SourceStyleSchemeManager -> Maybe [String] -> IO ()\nsourceStyleSchemeManagerSetSearchPath ssm dirs =\n maybeWith withUTFStringArray0 dirs $ \\dirsPtr -> do\n {#call unsafe source_style_scheme_manager_set_search_path#} ssm dirsPtr\n\n-- | Appends path to the list of directories where the manager looks for style scheme files. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerAppendSearchPath :: SourceStyleSchemeManager \n -> String -- ^ @path@ a directory or a filename. \n -> IO ()\nsourceStyleSchemeManagerAppendSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_append_search_path#} ssm\n\n-- | Prepends path to the list of directories where the manager looks for style scheme files. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerPrependSearchPath :: SourceStyleSchemeManager \n -> String -- ^ @path@ a directory or a filename. \n -> IO ()\nsourceStyleSchemeManagerPrependSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_prepend_search_path#} ssm\n\n-- | Returns the current search path for the manager. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerGetSearchPath :: SourceStyleSchemeManager \n -> IO [String]\nsourceStyleSchemeManagerGetSearchPath ssm = do\n dirsPtr <- {#call unsafe source_style_scheme_manager_get_search_path#} ssm\n peekUTFStringArray0 dirsPtr\n\n-- | Returns the ids of the available style schemes.\n--\nsourceStyleSchemeManagerGetSchemeIds :: SourceStyleSchemeManager -> IO [String]\nsourceStyleSchemeManagerGetSchemeIds ssm = do\n idsPtr <- {#call unsafe source_style_scheme_manager_get_scheme_ids#} ssm\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 idsPtr\n\n-- | Looks up style scheme by id.\n--\nsourceStyleSchemeManagerGetScheme :: SourceStyleSchemeManager \n -> String -- ^ @schemeId@ style scheme id to find\n -> IO SourceStyleScheme\nsourceStyleSchemeManagerGetScheme ssm id = makeNewGObject mkSourceStyleScheme $\n withUTFString id $ {#call unsafe source_style_scheme_manager_get_scheme#} ssm\n\n-- | Mark any currently cached information about the available style scehems as invalid. All the\n-- available style schemes will be reloaded next time the manager is accessed.\n--\nsourceStyleSchemeManagerForceRescan :: SourceStyleSchemeManager -> IO ()\nsourceStyleSchemeManagerForceRescan =\n {#call unsafe source_style_scheme_manager_force_rescan#}\n\n-- | List of the ids of the available style schemes.\n--\nsourceStyleSchemeManagerStyleIds :: ReadAttr SourceStyleSchemeManager [String]\nsourceStyleSchemeManagerStyleIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"style-ids\" {#call pure g_strv_get_type#}\n\n-- | List of directories and files where the style schemes are located.\n--\nsourceStyleSchemeManagerSearchPath :: ReadWriteAttr SourceStyleSchemeManager [String] (Maybe [String])\nsourceStyleSchemeManagerSearchPath =\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\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.SourceStyleSchemeManager (\n SourceStyleSchemeManager,\n SourceStyleSchemeManagerClass,\n sourceStyleSchemeManagerNew,\n sourceStyleSchemeManagerGetDefault,\n sourceStyleSchemeManagerSetSearchPath,\n sourceStyleSchemeManagerAppendSearchPath,\n sourceStyleSchemeManagerPrependSearchPath,\n sourceStyleSchemeManagerGetSearchPath,\n sourceStyleSchemeManagerGetSchemeIds,\n sourceStyleSchemeManagerGetScheme,\n sourceStyleSchemeManagerForceRescan,\n sourceStyleSchemeManagerStyleIds,\n sourceStyleSchemeManagerSearchPath\n ) where\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\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\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n-- |\n--\nsourceStyleSchemeManagerNew :: IO SourceStyleSchemeManager\nsourceStyleSchemeManagerNew = constructNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_new#}\n\n-- |\n--\nsourceStyleSchemeManagerGetDefault :: IO SourceStyleSchemeManager\nsourceStyleSchemeManagerGetDefault = makeNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_get_default#}\n\n-- |\n--\nsourceStyleSchemeManagerSetSearchPath :: SourceStyleSchemeManager -> Maybe [String] -> IO ()\nsourceStyleSchemeManagerSetSearchPath ssm dirs =\n maybeWith withUTFStringArray0 dirs $ \\dirsPtr -> do\n {#call unsafe source_style_scheme_manager_set_search_path#} ssm dirsPtr\n\n-- |\n--\nsourceStyleSchemeManagerAppendSearchPath :: SourceStyleSchemeManager -> String -> IO ()\nsourceStyleSchemeManagerAppendSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_append_search_path#} ssm\n\n-- |\n--\nsourceStyleSchemeManagerPrependSearchPath :: SourceStyleSchemeManager -> String -> IO ()\nsourceStyleSchemeManagerPrependSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_prepend_search_path#} ssm\n\n-- |\n--\nsourceStyleSchemeManagerGetSearchPath :: SourceStyleSchemeManager -> IO [String]\nsourceStyleSchemeManagerGetSearchPath ssm = do\n dirsPtr <- {#call unsafe source_style_scheme_manager_get_search_path#} ssm\n peekUTFStringArray0 dirsPtr\n\n-- |\n--\nsourceStyleSchemeManagerGetSchemeIds :: SourceStyleSchemeManager -> IO [String]\nsourceStyleSchemeManagerGetSchemeIds ssm = do\n idsPtr <- {#call unsafe source_style_scheme_manager_get_scheme_ids#} ssm\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 idsPtr\n\n-- |\n--\nsourceStyleSchemeManagerGetScheme :: SourceStyleSchemeManager -> String -> IO SourceStyleScheme\nsourceStyleSchemeManagerGetScheme ssm id = makeNewGObject mkSourceStyleScheme $\n withUTFString id $ {#call unsafe source_style_scheme_manager_get_scheme#} ssm\n\n-- |\n--\nsourceStyleSchemeManagerForceRescan :: SourceStyleSchemeManager -> IO ()\nsourceStyleSchemeManagerForceRescan =\n {#call unsafe source_style_scheme_manager_force_rescan#}\n\n-- |\n--\nsourceStyleSchemeManagerStyleIds :: ReadAttr SourceStyleSchemeManager [String]\nsourceStyleSchemeManagerStyleIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"style-ids\" {#call pure g_strv_get_type#}\n\n-- |\n--\nsourceStyleSchemeManagerSearchPath :: ReadWriteAttr SourceStyleSchemeManager [String] (Maybe [String])\nsourceStyleSchemeManagerSearchPath =\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":"a8598c417fb7ff4e999757dc5c1a92cdec76f175","subject":"Use SourceStyleSchemeManagerClass replace SourceStyleSchemeManager as function argument.","message":"Use SourceStyleSchemeManagerClass replace SourceStyleSchemeManager as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleSchemeManager.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleSchemeManager.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\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.SourceStyleSchemeManager (\n-- * Types\n SourceStyleSchemeManager,\n SourceStyleSchemeManagerClass,\n\n-- * Methods \n sourceStyleSchemeManagerNew,\n sourceStyleSchemeManagerGetDefault,\n sourceStyleSchemeManagerSetSearchPath,\n sourceStyleSchemeManagerAppendSearchPath,\n sourceStyleSchemeManagerPrependSearchPath,\n sourceStyleSchemeManagerGetSearchPath,\n sourceStyleSchemeManagerGetSchemeIds,\n sourceStyleSchemeManagerGetScheme,\n sourceStyleSchemeManagerForceRescan,\n\n-- * Attributes\n sourceStyleSchemeManagerStyleIds,\n sourceStyleSchemeManagerSearchPath\n ) where\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\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\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n-- | Creates a new style manager. If you do not need more than one style manager then use\n-- 'sourceStyleSchemeManagerGetDefault' instead.\n--\nsourceStyleSchemeManagerNew :: IO SourceStyleSchemeManager\nsourceStyleSchemeManagerNew = constructNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_new#}\n\n-- | Returns the default 'SourceStyleSchemeManager' instance.\n--\nsourceStyleSchemeManagerGetDefault :: IO SourceStyleSchemeManager -- ^ returns a 'SourceStyleSchemeManager'. Return value is owned by 'SourceView' library and must not be unref'ed.\nsourceStyleSchemeManagerGetDefault = makeNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_get_default#}\n\n-- | Sets the list of directories where the manager looks for style scheme files. If dirs is 'Nothing', the\n-- search path is reset to default.\n--\nsourceStyleSchemeManagerSetSearchPath :: SourceStyleSchemeManagerClass sssm => sssm -> Maybe [String] -> IO ()\nsourceStyleSchemeManagerSetSearchPath ssm dirs =\n maybeWith withUTFStringArray0 dirs $ \\dirsPtr -> do\n {#call unsafe source_style_scheme_manager_set_search_path#} (toSourceStyleSchemeManager ssm) dirsPtr\n\n-- | Appends path to the list of directories where the manager looks for style scheme files. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerAppendSearchPath :: SourceStyleSchemeManagerClass sssm => sssm \n -> String -- ^ @path@ a directory or a filename. \n -> IO ()\nsourceStyleSchemeManagerAppendSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_append_search_path#} (toSourceStyleSchemeManager ssm)\n\n-- | Prepends path to the list of directories where the manager looks for style scheme files. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerPrependSearchPath :: SourceStyleSchemeManagerClass sssm => sssm \n -> String -- ^ @path@ a directory or a filename. \n -> IO ()\nsourceStyleSchemeManagerPrependSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_prepend_search_path#} (toSourceStyleSchemeManager ssm)\n\n-- | Returns the current search path for the manager. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerGetSearchPath :: SourceStyleSchemeManagerClass sssm => sssm \n -> IO [String]\nsourceStyleSchemeManagerGetSearchPath ssm = do\n dirsPtr <- {#call unsafe source_style_scheme_manager_get_search_path#} (toSourceStyleSchemeManager ssm)\n peekUTFStringArray0 dirsPtr\n\n-- | Returns the ids of the available style schemes.\n--\nsourceStyleSchemeManagerGetSchemeIds :: SourceStyleSchemeManagerClass sssm => sssm -> IO [String]\nsourceStyleSchemeManagerGetSchemeIds ssm = do\n idsPtr <- {#call unsafe source_style_scheme_manager_get_scheme_ids#} (toSourceStyleSchemeManager ssm)\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 idsPtr\n\n-- | Looks up style scheme by id.\n--\nsourceStyleSchemeManagerGetScheme :: SourceStyleSchemeManagerClass sssm => sssm \n -> String -- ^ @schemeId@ style scheme id to find\n -> IO SourceStyleScheme\nsourceStyleSchemeManagerGetScheme ssm id = makeNewGObject mkSourceStyleScheme $\n withUTFString id $ {#call unsafe source_style_scheme_manager_get_scheme#} (toSourceStyleSchemeManager ssm)\n\n-- | Mark any currently cached information about the available style scehems as invalid. All the\n-- available style schemes will be reloaded next time the manager is accessed.\n--\nsourceStyleSchemeManagerForceRescan :: SourceStyleSchemeManagerClass sssm => sssm -> IO ()\nsourceStyleSchemeManagerForceRescan ssm =\n {#call unsafe source_style_scheme_manager_force_rescan#} (toSourceStyleSchemeManager ssm)\n\n-- | List of the ids of the available style schemes.\n--\nsourceStyleSchemeManagerStyleIds :: SourceStyleSchemeManagerClass sssm => ReadAttr sssm [String]\nsourceStyleSchemeManagerStyleIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"style-ids\" {#call pure g_strv_get_type#}\n\n-- | List of directories and files where the style schemes are located.\n--\nsourceStyleSchemeManagerSearchPath :: SourceStyleSchemeManagerClass sssm => ReadWriteAttr sssm [String] (Maybe [String])\nsourceStyleSchemeManagerSearchPath =\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\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.SourceStyleSchemeManager (\n-- * Types\n SourceStyleSchemeManager,\n SourceStyleSchemeManagerClass,\n\n-- * Methods \n sourceStyleSchemeManagerNew,\n sourceStyleSchemeManagerGetDefault,\n sourceStyleSchemeManagerSetSearchPath,\n sourceStyleSchemeManagerAppendSearchPath,\n sourceStyleSchemeManagerPrependSearchPath,\n sourceStyleSchemeManagerGetSearchPath,\n sourceStyleSchemeManagerGetSchemeIds,\n sourceStyleSchemeManagerGetScheme,\n sourceStyleSchemeManagerForceRescan,\n\n-- * Attributes\n sourceStyleSchemeManagerStyleIds,\n sourceStyleSchemeManagerSearchPath\n ) where\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\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\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.SourceView.SourceStyleScheme#}\n\n-- | Creates a new style manager. If you do not need more than one style manager then use\n-- 'sourceStyleSchemeManagerGetDefault' instead.\n--\nsourceStyleSchemeManagerNew :: IO SourceStyleSchemeManager\nsourceStyleSchemeManagerNew = constructNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_new#}\n\n-- | Returns the default 'SourceStyleSchemeManager' instance.\n--\nsourceStyleSchemeManagerGetDefault :: IO SourceStyleSchemeManager -- ^ returns a 'SourceStyleSchemeManager'. Return value is owned by 'SourceView' library and must not be unref'ed.\nsourceStyleSchemeManagerGetDefault = makeNewGObject mkSourceStyleSchemeManager $ liftM castPtr\n {#call unsafe source_style_scheme_manager_get_default#}\n\n-- | Sets the list of directories where the manager looks for style scheme files. If dirs is 'Nothing', the\n-- search path is reset to default.\n--\nsourceStyleSchemeManagerSetSearchPath :: SourceStyleSchemeManager -> Maybe [String] -> IO ()\nsourceStyleSchemeManagerSetSearchPath ssm dirs =\n maybeWith withUTFStringArray0 dirs $ \\dirsPtr -> do\n {#call unsafe source_style_scheme_manager_set_search_path#} ssm dirsPtr\n\n-- | Appends path to the list of directories where the manager looks for style scheme files. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerAppendSearchPath :: SourceStyleSchemeManager \n -> String -- ^ @path@ a directory or a filename. \n -> IO ()\nsourceStyleSchemeManagerAppendSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_append_search_path#} ssm\n\n-- | Prepends path to the list of directories where the manager looks for style scheme files. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerPrependSearchPath :: SourceStyleSchemeManager \n -> String -- ^ @path@ a directory or a filename. \n -> IO ()\nsourceStyleSchemeManagerPrependSearchPath ssm dir =\n withUTFString dir $ {#call unsafe source_style_scheme_manager_prepend_search_path#} ssm\n\n-- | Returns the current search path for the manager. See\n-- 'sourceStyleSchemeManagerSetSearchPath' for details.\n--\nsourceStyleSchemeManagerGetSearchPath :: SourceStyleSchemeManager \n -> IO [String]\nsourceStyleSchemeManagerGetSearchPath ssm = do\n dirsPtr <- {#call unsafe source_style_scheme_manager_get_search_path#} ssm\n peekUTFStringArray0 dirsPtr\n\n-- | Returns the ids of the available style schemes.\n--\nsourceStyleSchemeManagerGetSchemeIds :: SourceStyleSchemeManager -> IO [String]\nsourceStyleSchemeManagerGetSchemeIds ssm = do\n idsPtr <- {#call unsafe source_style_scheme_manager_get_scheme_ids#} ssm\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 idsPtr\n\n-- | Looks up style scheme by id.\n--\nsourceStyleSchemeManagerGetScheme :: SourceStyleSchemeManager \n -> String -- ^ @schemeId@ style scheme id to find\n -> IO SourceStyleScheme\nsourceStyleSchemeManagerGetScheme ssm id = makeNewGObject mkSourceStyleScheme $\n withUTFString id $ {#call unsafe source_style_scheme_manager_get_scheme#} ssm\n\n-- | Mark any currently cached information about the available style scehems as invalid. All the\n-- available style schemes will be reloaded next time the manager is accessed.\n--\nsourceStyleSchemeManagerForceRescan :: SourceStyleSchemeManager -> IO ()\nsourceStyleSchemeManagerForceRescan =\n {#call unsafe source_style_scheme_manager_force_rescan#}\n\n-- | List of the ids of the available style schemes.\n--\nsourceStyleSchemeManagerStyleIds :: ReadAttr SourceStyleSchemeManager [String]\nsourceStyleSchemeManagerStyleIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"style-ids\" {#call pure g_strv_get_type#}\n\n-- | List of directories and files where the style schemes are located.\n--\nsourceStyleSchemeManagerSearchPath :: ReadWriteAttr SourceStyleSchemeManager [String] (Maybe [String])\nsourceStyleSchemeManagerSearchPath =\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":"68637f5bb1c614a03fa32baf5e9e6c7d96c8335f","subject":"Removed redundant util","message":"Removed redundant util\n","repos":"bneijt\/bluetooth,RyanGlScott\/bluetooth","old_file":"src\/Network\/Bluetooth\/Utils.chs","new_file":"src\/Network\/Bluetooth\/Utils.chs","new_contents":"{-# LANGUAGE CPP, MagicHash, TupleSections #-}\nmodule Network.Bluetooth.Utils\n ( allocaLen\n , byteSwap32\n , cToEnum\n , cFromEnum\n , getFromIntegral\n , getRealToFrac\n , setFromIntegral\n , setRealToFrac\n , peekFromIntegral\n , peekRealToFrac\n , throwSocketErrorIf\n , throwSocketErrorIfNull\n , throwSocketErrorIfNull_\n , unsafePeek\n , unsafePeekFromIntegral\n , unsafePeekRealToFrac\n , with'\n , withCast\n , withCastArray\n , withCastArray0\n , withCastArrayLen\n , withCastArrayLen0\n , withCastLen\n , withCastLenConv\n , withFunWrapper\n , withLen\n , withLenConv\n ) where\n\nimport Control.Monad\n\nimport qualified Data.Word as W\nimport Data.Word (Word32)\n\nimport Foreign.C.Types hiding (CSize)\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\n#if __GLASGOW_HASKELL__ < 708\nimport GHC.Prim\nimport GHC.Word\n#endif\n\nimport Network.Socket.Internal\n\nimport System.IO.Unsafe\n\n#include \n\n-- | Remove this when is resolved\ntype CSize = {#type size_t #}\n\nallocaLen :: Storable a => (Int -> Ptr a -> IO b) -> IO b\nallocaLen = doAllocaLen undefined\n where\n doAllocaLen :: Storable a => a -> (Int -> Ptr a -> IO b) -> IO b\n doAllocaLen dummy f = alloca . f $ sizeOf dummy\n\nbyteSwap32 :: Word32 -> Word32\n#if __GLASGOW_HASKELL__ >= 708\nbyteSwap32 = W.byteSwap32\n#else\nbyteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#))\n#endif\n\n-- TODO: Rename this to something more sensible.\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\n-- TODO: Rename this to something more sensible.\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\ngetFromIntegral :: (Integral i, Num n) => (Ptr a -> IO i) -> Ptr a -> IO n\ngetFromIntegral getter = fmap fromIntegral . getter\n\ngetRealToFrac :: (Real r, Fractional f) => (Ptr a -> IO r) -> Ptr a -> IO f\ngetRealToFrac getter = fmap realToFrac . getter\n\nsetFromIntegral :: (Integral i, Num n) => (Ptr a -> n -> IO ()) -> Ptr a -> i -> IO ()\nsetFromIntegral setter ptr = setter ptr . fromIntegral\n\nsetRealToFrac :: (Real r, Fractional f) => (Ptr a -> f -> IO ()) -> Ptr a -> r -> IO ()\nsetRealToFrac setter ptr = setter ptr . realToFrac\n\npeekFromIntegral :: (Integral a, Storable a, Num b) => Ptr a -> IO b\npeekFromIntegral = fmap fromIntegral . peek\n\npeekRealToFrac :: (Real a, Storable a, Fractional b) => Ptr a -> IO b\npeekRealToFrac = fmap realToFrac . peek\n\nthrowSocketErrorIf :: (a -> Bool) -> String -> IO a -> IO a\nthrowSocketErrorIf p name act = do\n r <- act\n if p r\n then throwSocketError name\n else return r\n\nthrowSocketErrorIfNull :: String -> IO (Ptr a) -> IO (Ptr a)\nthrowSocketErrorIfNull = throwSocketErrorIf (== nullPtr)\n\nthrowSocketErrorIfNull_ :: String -> IO (Ptr a) -> IO ()\nthrowSocketErrorIfNull_ name = void . throwSocketErrorIfNull name\n\nunsafePeek :: Storable a => Ptr a -> a\nunsafePeek = unsafePerformIO . peek\n\nunsafePeekFromIntegral :: (Integral a, Storable a, Num b) => Ptr a -> b\nunsafePeekFromIntegral = fromIntegral . unsafePeek\n\nunsafePeekRealToFrac :: (Real a, Storable a, Fractional b) => Ptr a -> b\nunsafePeekRealToFrac = realToFrac . unsafePeek\n\n-- | Synonym for 'with' to avoid c2hs issues.\n-- See .\nwith' :: Storable s => s -> (Ptr s -> IO a) -> IO a\nwith' = with\n\nwithCast :: Storable s1 => s1 -> (Ptr s2 -> IO a) -> IO a\nwithCast val f = with val $ f . castPtr\n\nwithCastArray :: Storable s1 => [s1] -> (Ptr s2 -> IO a) -> IO a\nwithCastArray vals = withCastArrayLen vals . const\n\nwithCastArrayLen :: Storable s1 => [s1] -> (Int -> Ptr s2 -> IO a) -> IO a\nwithCastArrayLen vals f = withArrayLen vals $ \\len -> f len . castPtr\n\nwithCastArray0 :: Storable s1 => s1 -> [s1] -> (Ptr s2 -> IO a) -> IO a\nwithCastArray0 marker vals = withCastArrayLen0 marker vals . const\n\nwithCastArrayLen0 :: Storable s1 => s1 -> [s1] -> (Int -> Ptr s2 -> IO a) -> IO a\nwithCastArrayLen0 marker vals f = withArrayLen0 marker vals $ \\len -> f len . castPtr\n\nwithCastLen :: Storable s1 => s1 -> ((Ptr s2, CSize) -> IO a) -> IO a\nwithCastLen val f = withLen val $ f . mapFst castPtr\n\nwithCastLenConv :: (Num n, Storable s1) => s1 -> ((Ptr s2, n) -> IO a) -> IO a\nwithCastLenConv val f = withCastLen val $ f . mapSnd fromIntegral\n\nwithFunWrapper :: (a -> IO (FunPtr a)) -> a -> (FunPtr a -> IO b) -> IO b\nwithFunWrapper wrapper hFun f = do\n funPtr <- wrapper hFun\n res <- f funPtr\n freeHaskellFunPtr funPtr\n return res\n\nwithLen :: Storable a => a -> ((Ptr a, CSize) -> IO b) -> IO b\nwithLen val f = with val $ f . (, fromIntegral $ sizeOf val)\n\nwithLenConv :: (Num n, Storable s) => s -> ((Ptr s, n) -> IO a) -> IO a\nwithLenConv val f = withLen val $ f . mapSnd fromIntegral\n\n-------------------------------------------------------------------------------\n\nmapFst :: (a1 -> a2) -> (a1, b) -> (a2, b)\nmapFst f (x, y) = (f x, y)\n\nmapSnd :: (b1 -> b2) -> (a, b1) -> (a, b2)\nmapSnd = fmap\n","old_contents":"{-# LANGUAGE CPP, MagicHash, TupleSections #-}\nmodule Network.Bluetooth.Utils\n ( allocaLen\n , byteSwap32\n , cToEnum\n , cFromEnum\n , getFromIntegral\n , getRealToFrac\n , setFromIntegral\n , setRealToFrac\n , peekFromIntegral\n , peekRealToFrac\n , throwSocketErrorIf\n , throwSocketErrorIfMinus1Retry_\n , throwSocketErrorIfNull\n , throwSocketErrorIfNull_\n , unsafePeek\n , unsafePeekFromIntegral\n , unsafePeekRealToFrac\n , with'\n , withCast\n , withCastArray\n , withCastArray0\n , withCastArrayLen\n , withCastArrayLen0\n , withCastLen\n , withCastLenConv\n , withFunWrapper\n , withLen\n , withLenConv\n ) where\n\nimport Control.Monad\n\nimport qualified Data.Word as W\nimport Data.Word (Word32)\n\nimport Foreign.C.Types hiding (CSize)\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\n#if __GLASGOW_HASKELL__ < 708\nimport GHC.Prim\nimport GHC.Word\n#endif\n\nimport Network.Socket.Internal\n\nimport System.IO.Unsafe\n\n#include \n\n-- | Remove this when is resolved\ntype CSize = {#type size_t #}\n\nallocaLen :: Storable a => (Int -> Ptr a -> IO b) -> IO b\nallocaLen = doAllocaLen undefined\n where\n doAllocaLen :: Storable a => a -> (Int -> Ptr a -> IO b) -> IO b\n doAllocaLen dummy f = alloca . f $ sizeOf dummy\n\nbyteSwap32 :: Word32 -> Word32\n#if __GLASGOW_HASKELL__ >= 708\nbyteSwap32 = W.byteSwap32\n#else\nbyteSwap32 (W32# w#) = W32# (narrow32Word# (byteSwap32# w#))\n#endif\n\n-- TODO: Rename this to something more sensible.\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . fromIntegral\n\n-- TODO: Rename this to something more sensible.\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = fromIntegral . fromEnum\n\ngetFromIntegral :: (Integral i, Num n) => (Ptr a -> IO i) -> Ptr a -> IO n\ngetFromIntegral getter = fmap fromIntegral . getter\n\ngetRealToFrac :: (Real r, Fractional f) => (Ptr a -> IO r) -> Ptr a -> IO f\ngetRealToFrac getter = fmap realToFrac . getter\n\nsetFromIntegral :: (Integral i, Num n) => (Ptr a -> n -> IO ()) -> Ptr a -> i -> IO ()\nsetFromIntegral setter ptr = setter ptr . fromIntegral\n\nsetRealToFrac :: (Real r, Fractional f) => (Ptr a -> f -> IO ()) -> Ptr a -> r -> IO ()\nsetRealToFrac setter ptr = setter ptr . realToFrac\n\npeekFromIntegral :: (Integral a, Storable a, Num b) => Ptr a -> IO b\npeekFromIntegral = fmap fromIntegral . peek\n\npeekRealToFrac :: (Real a, Storable a, Fractional b) => Ptr a -> IO b\npeekRealToFrac = fmap realToFrac . peek\n\nthrowSocketErrorIf :: (a -> Bool) -> String -> IO a -> IO a\nthrowSocketErrorIf p name act = do\n r <- act\n if p r\n then throwSocketError name\n else return r\n\nthrowSocketErrorIfMinus1Retry_ :: (Eq a, Num a) => String -> IO a -> IO ()\nthrowSocketErrorIfMinus1Retry_ name = void . throwSocketErrorIfMinus1Retry name\n\nthrowSocketErrorIfNull :: String -> IO (Ptr a) -> IO (Ptr a)\nthrowSocketErrorIfNull = throwSocketErrorIf (== nullPtr)\n\nthrowSocketErrorIfNull_ :: String -> IO (Ptr a) -> IO ()\nthrowSocketErrorIfNull_ name = void . throwSocketErrorIfNull name\n\nunsafePeek :: Storable a => Ptr a -> a\nunsafePeek = unsafePerformIO . peek\n\nunsafePeekFromIntegral :: (Integral a, Storable a, Num b) => Ptr a -> b\nunsafePeekFromIntegral = fromIntegral . unsafePeek\n\nunsafePeekRealToFrac :: (Real a, Storable a, Fractional b) => Ptr a -> b\nunsafePeekRealToFrac = realToFrac . unsafePeek\n\n-- | Synonym for 'with' to avoid c2hs issues.\n-- See .\nwith' :: Storable s => s -> (Ptr s -> IO a) -> IO a\nwith' = with\n\nwithCast :: Storable s1 => s1 -> (Ptr s2 -> IO a) -> IO a\nwithCast val f = with val $ f . castPtr\n\nwithCastArray :: Storable s1 => [s1] -> (Ptr s2 -> IO a) -> IO a\nwithCastArray vals = withCastArrayLen vals . const\n\nwithCastArrayLen :: Storable s1 => [s1] -> (Int -> Ptr s2 -> IO a) -> IO a\nwithCastArrayLen vals f = withArrayLen vals $ \\len -> f len . castPtr\n\nwithCastArray0 :: Storable s1 => s1 -> [s1] -> (Ptr s2 -> IO a) -> IO a\nwithCastArray0 marker vals = withCastArrayLen0 marker vals . const\n\nwithCastArrayLen0 :: Storable s1 => s1 -> [s1] -> (Int -> Ptr s2 -> IO a) -> IO a\nwithCastArrayLen0 marker vals f = withArrayLen0 marker vals $ \\len -> f len . castPtr\n\nwithCastLen :: Storable s1 => s1 -> ((Ptr s2, CSize) -> IO a) -> IO a\nwithCastLen val f = withLen val $ f . mapFst castPtr\n\nwithCastLenConv :: (Num n, Storable s1) => s1 -> ((Ptr s2, n) -> IO a) -> IO a\nwithCastLenConv val f = withCastLen val $ f . mapSnd fromIntegral\n\nwithFunWrapper :: (a -> IO (FunPtr a)) -> a -> (FunPtr a -> IO b) -> IO b\nwithFunWrapper wrapper hFun f = do\n funPtr <- wrapper hFun\n res <- f funPtr\n freeHaskellFunPtr funPtr\n return res\n\nwithLen :: Storable a => a -> ((Ptr a, CSize) -> IO b) -> IO b\nwithLen val f = with val $ f . (, fromIntegral $ sizeOf val)\n\nwithLenConv :: (Num n, Storable s) => s -> ((Ptr s, n) -> IO a) -> IO a\nwithLenConv val f = withLen val $ f . mapSnd fromIntegral\n\n-------------------------------------------------------------------------------\n\nmapFst :: (a1 -> a2) -> (a1, b) -> (a2, b)\nmapFst f (x, y) = (f x, y)\n\nmapSnd :: (b1 -> b2) -> (a, b1) -> (a, b2)\nmapSnd = fmap","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"cc31131defccfb5cb97fd24d4c1a4250e38b3f0a","subject":"Added connect()","message":"Added connect()\n","repos":"bneijt\/bluetooth,RyanGlScott\/bluetooth","old_file":"src\/Network\/Bluetooth\/Linux\/Socket.chs","new_file":"src\/Network\/Bluetooth\/Linux\/Socket.chs","new_contents":"module Network.Bluetooth.Linux.Socket where\n\nimport Control.Concurrent.MVar\nimport Control.Exception\nimport Control.Monad\n\nimport Data.Either\nimport Data.Word\n\nimport Foreign.C.Error\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Internal\nimport Network.Bluetooth.Utils\nimport Network.Socket\n\n#include \n#include \"wr_l2cap.h\"\n#include \"wr_rfcomm.h\"\n\nbluetoothSocket :: BluetoothProtocol -> IO Socket\nbluetoothSocket proto = do\n let family = AF_BLUETOOTH\n sockType = case proto of\n L2CAP -> SeqPacket\n RFCOMM -> Stream\n fd <- throwErrnoIfMinus1 \"socket\" $ c_socket family sockType proto\n status <- newMVar NotConnected\n return $ MkSocket fd family sockType (cFromEnum proto) status\n\nassignSocket :: (Num n1, Num n2, SockAddrPtr p) =>\n Int\n -> (Ptr p -> n1 -> IO ())\n -> (Ptr p -> Ptr BluetoothAddr -> IO ())\n -> (Ptr p -> n2 -> IO ())\n -> (CInt -> Ptr p -> Int -> IO Int)\n -> String\n -> Socket -> BluetoothAddr -> Int -> IO ()\nassignSocket sockaddrSize familySetter bdaddrSetter portSetter c_assigner name (MkSocket fd _ _ proto sockStatus) bdaddr portNum =\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n name ++ \": can't peform \" ++ name ++ \" on socket in status \" ++ show status\n let protoEnum = cToEnum proto\n btPort <- mkPort protoEnum portNum\n let portNum' = (case protoEnum of\n L2CAP -> c_htobs\n RFCOMM -> id) $ getPort btPort\n allocaBytes sockaddrSize $ \\sockaddrPtr -> with bdaddr $ \\bdaddrPtr -> do\n setFromIntegral familySetter sockaddrPtr $ packFamily AF_BLUETOOTH\n bdaddrSetter sockaddrPtr bdaddrPtr\n setFromIntegral portSetter sockaddrPtr portNum'\n throwErrnoIfMinus1_ name $ c_assigner fd sockaddrPtr sockaddrSize\n return Bound\n\nbluetoothBind :: Socket -> BluetoothAddr -> Int -> IO ()\nbluetoothBind sock@(MkSocket _ _ _ proto _) =\n let bind' = case cToEnum proto of\n L2CAP -> assignSocket {#sizeof sockaddr_l2_t #}\n {#set sockaddr_l2_t.l2_family #}\n c_sockaddr_l2_set_bdaddr\n {#set sockaddr_l2_t.l2_psm #}\n c_bind\n RFCOMM -> assignSocket {#sizeof sockaddr_rc_t #}\n {#set sockaddr_rc_t.rc_family #}\n c_sockaddr_rc_set_bdaddr\n {#set sockaddr_rc_t.rc_channel #}\n c_bind\n in bind' \"bind\" sock\n-- bluetoothBind (MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n-- modifyMVar_ sockStatus $ \\status -> do\n-- when (status \/= NotConnected) . ioError . userError $\n-- \"bind: can't peform bind on socket in status \" ++ show status\n-- let protoEnum = cToEnum proto\n-- btPort <- mkPort protoEnum portNum\n-- case protoEnum of\n-- L2CAP -> callBind {#sizeof sockaddr_l2_t #}\n-- {#set sockaddr_l2_t.l2_family #}\n-- c_sockaddr_l2_set_bdaddr\n-- {#set sockaddr_l2_t.l2_psm #}\n-- (c_htobs $ getPort btPort)\n-- RFCOMM -> callBind {#sizeof sockaddr_rc_t #}\n-- {#set sockaddr_rc_t.rc_family #}\n-- c_sockaddr_rc_set_bdaddr\n-- {#set sockaddr_rc_t.rc_channel #}\n-- (getPort btPort)\n-- return Bound\n-- where\n-- callBind :: (Num s1, Num s2, SockAddrPtr p, Integral i) =>\n-- Int\n-- -> (Ptr p -> s1 -> IO ())\n-- -> (Ptr p -> Ptr BluetoothAddr -> IO ())\n-- -> (Ptr p -> s2 -> IO ())\n-- -> i\n-- -> IO ()\n-- callBind size setter1 setter2 setter3 port' =\n-- allocaBytes size $ \\sockaddrPtr ->\n-- with bdaddr $ \\bdaddrPtr -> do\n-- setFromIntegral setter1 sockaddrPtr $ packFamily AF_BLUETOOTH\n-- setter2 sockaddrPtr bdaddrPtr\n-- setFromIntegral setter3 sockaddrPtr port'\n-- throwErrnoIfMinus1_ \"bind\" $ c_bind fd sockaddrPtr size\n\nbluetoothBindAnyPort :: Socket -> BluetoothAddr -> IO BluetoothPort\nbluetoothBindAnyPort sock@(MkSocket _ _ _ proto _) bdaddr = do\n port <- bindAnyPort (cToEnum proto) bdaddr\n bluetoothBind sock bdaddr $ getPort port\n return port\n\ndata BluetoothPort = RFCOMMPort Word8\n | L2CAPPort Word16\n deriving Eq\n\ninstance Show BluetoothPort where\n show = show . getPort\n\ngetPort :: BluetoothPort -> Int\ngetPort (L2CAPPort p) = fromIntegral p\ngetPort (RFCOMMPort p) = fromIntegral p\n\nmkPort :: BluetoothProtocol -> Int -> IO BluetoothPort\nmkPort RFCOMM port | 1 <= port && port <= 30\n = return . RFCOMMPort $ fromIntegral port\nmkPort RFCOMM _ = ioError $ userError \"RFCOMM ports must be between 1 and 30.\"\nmkPort L2CAP port | odd port && 4097 <= port && port <= 32767\n = return . L2CAPPort $ fromIntegral port\nmkPort L2CAP _ = ioError $ userError \"L2CAP ports must be odd numbers between 4097 and 32,767.\"\n\nbindAnyPort :: BluetoothProtocol -> BluetoothAddr -> IO BluetoothPort\nbindAnyPort proto addr = do\n avails <- flip filterM (portRange proto) $ \\portNum -> do\n sock <- bluetoothSocket proto\n res <- try $ bluetoothBind sock addr portNum\n close sock\n return $ isRight (res :: Either IOError ())\n case avails of\n portNum:_ -> mkPort proto portNum\n _ -> ioError $ userError \"Unable to find any available port\"\n where\n portRange L2CAP = [4097, 4099 .. 32767]\n portRange RFCOMM = [1 .. 30]\n\nbluetoothListen :: Socket -> Int -> IO ()\nbluetoothListen = listen -- TODO: tweak exception handling\n\nbluetoothAccept :: Socket -> IO (Socket, BluetoothAddr)\nbluetoothAccept (MkSocket fd family sockType proto sockStatus) = do\n currentStatus <- readMVar sockStatus\n when (currentStatus \/= Connected && currentStatus \/= Listening) . ioError . userError $\n \"accept: can't perform accept on socket (\" ++ show (family,sockType,proto) ++ \") in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> callAccept {#sizeof sockaddr_l2_t #} c_sockaddr_l2_get_bdaddr\n RFCOMM -> callAccept {#sizeof sockaddr_rc_t #} c_sockaddr_rc_get_bdaddr\n where\n callAccept :: SockAddrPtr p =>\n Int\n -> (Ptr BluetoothAddr -> Ptr p -> IO (Ptr BluetoothAddr))\n -> IO (Socket, BluetoothAddr)\n callAccept size getter =\n allocaBytes size $ \\sockaddrPtr ->\n allocaBytes (sizeOf (undefined :: BluetoothAddr)) $ \\bdaddrPtr -> do\n (newFd,_) <- throwErrnoIf ((== -1) . fst) \"accept\" $ c_accept fd sockaddrPtr size\n _ <- getter bdaddrPtr sockaddrPtr\n bdaddr <- peek bdaddrPtr\n newStatus <- newMVar Connected\n return (MkSocket newFd family sockType proto newStatus, bdaddr)\n\n-- bluetoothConnect :: Socket -> BluetoothAddr -> Int -> IO ()\n-- bluetoothConnect (MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n-- modifyMVar sockStatus $ \\status -> do\n-- when (status \/= NotConnected) . ioError . userError $\n-- \"accept: can't peform connect on socket in status \" ++ show status\n-- let protoEnum = cToEnum proto\n-- btPort <- mkPort protoEnum bdaddr portNum\n-- case protoEnum of\n-- L2CAP -> \n-- RFCOMM -> \n-- where\n-- callConnect :: SockAddrPtr p => Int\n\nbluetoothConnect :: Socket -> BluetoothAddr -> Int -> IO ()\nbluetoothConnect sock@(MkSocket _ _ _ proto _) =\n let connect' = case cToEnum proto of\n L2CAP -> assignSocket {#sizeof sockaddr_l2_t #}\n {#set sockaddr_l2_t.l2_family #}\n c_sockaddr_l2_set_bdaddr\n {#set sockaddr_l2_t.l2_psm #}\n c_connect\n RFCOMM -> assignSocket {#sizeof sockaddr_rc_t #}\n {#set sockaddr_rc_t.rc_family #}\n c_sockaddr_rc_set_bdaddr\n {#set sockaddr_rc_t.rc_channel #}\n c_connect\n in connect' \"connect\" sock \n\ngetSockPort :: Socket -> IO BluetoothPort\ngetSockPort (MkSocket fd _ _ proto status) = do\n currentStatus <- readMVar status\n when (currentStatus == NotConnected || currentStatus == Closed) . ioError . userError $\n \"getsockname: can't get name of socket in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> callGetSockName {#sizeof sockaddr_l2_t #}\n ({#get sockaddr_l2_t.l2_psm #} :: SockAddrL2CAPPtr -> IO CUShort)\n L2CAPPort\n RFCOMM -> callGetSockName {#sizeof sockaddr_rc_t #}\n ({#get sockaddr_rc_t.rc_channel #} :: SockAddrRFCOMMPtr -> IO CUInt8)\n RFCOMMPort\n where\n callGetSockName :: (Integral i, Integral j, SockAddrPtr p) =>\n Int\n -> (Ptr p -> IO i)\n -> (j -> BluetoothPort)\n -> IO BluetoothPort\n callGetSockName size getter portCon = allocaBytes size $ \\sockaddrPtr -> do\n throwErrnoIf_ ((== -1) . fst) \"getsockname\" $ c_getsockname fd sockaddrPtr size\n fmap portCon $ getFromIntegral getter sockaddrPtr \n ","old_contents":"module Network.Bluetooth.Linux.Socket where\n\nimport Control.Concurrent.MVar\nimport Control.Exception\nimport Control.Monad\n\nimport Data.Either\nimport Data.Word\n\nimport Foreign.C.Error\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Network.Bluetooth.Linux.Addr\nimport Network.Bluetooth.Linux.Internal\nimport Network.Bluetooth.Utils\nimport Network.Socket\n\n#include \n#include \"wr_l2cap.h\"\n#include \"wr_rfcomm.h\"\n\nbluetoothSocket :: BluetoothProtocol -> IO Socket\nbluetoothSocket proto = do\n let family = AF_BLUETOOTH\n sockType = case proto of\n L2CAP -> SeqPacket\n RFCOMM -> Stream\n fd <- throwErrnoIfMinus1 \"socket\" $ c_socket family sockType proto\n status <- newMVar NotConnected\n return $ MkSocket fd family sockType (cFromEnum proto) status\n\nbluetoothBind :: Socket -> BluetoothAddr -> Int -> IO ()\nbluetoothBind (MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n modifyMVar_ sockStatus $ \\status -> do\n when (status \/= NotConnected) . ioError . userError $\n \"bind: can't peform bind on socket in status \" ++ show status\n btPort <- mkPort (cToEnum proto) portNum\n case cToEnum proto of\n L2CAP -> callBind {#sizeof sockaddr_l2_t #}\n {#set sockaddr_l2_t.l2_family #}\n c_sockaddr_l2_set_bdaddr\n {#set sockaddr_l2_t.l2_psm #}\n (c_htobs $ getPort btPort)\n RFCOMM -> callBind {#sizeof sockaddr_rc_t #}\n {#set sockaddr_rc_t.rc_family #}\n c_sockaddr_rc_set_bdaddr\n {#set sockaddr_rc_t.rc_channel #}\n (getPort btPort)\n return Bound\n where\n callBind :: (Num s1, Num s2, SockAddrPtr p, Integral i) =>\n Int\n -> (Ptr p -> s1 -> IO ())\n -> (Ptr p -> Ptr BluetoothAddr -> IO ())\n -> (Ptr p -> s2 -> IO ())\n -> i\n -> IO ()\n callBind size setter1 setter2 setter3 port' =\n allocaBytes size $ \\sockaddrPtr ->\n with bdaddr $ \\bdaddrPtr -> do\n setFromIntegral setter1 sockaddrPtr $ packFamily AF_BLUETOOTH\n setter2 sockaddrPtr bdaddrPtr\n setFromIntegral setter3 sockaddrPtr port'\n throwErrnoIfMinus1_ \"bind\" $ c_bind fd sockaddrPtr size\n\nbluetoothBindAnyPort :: Socket -> BluetoothAddr -> IO BluetoothPort\nbluetoothBindAnyPort sock@(MkSocket _ _ _ proto _) bdaddr = do\n port <- bindAnyPort (cToEnum proto) bdaddr\n bluetoothBind sock bdaddr $ getPort port\n return port\n\ndata BluetoothPort = RFCOMMPort Word8\n | L2CAPPort Word16\n deriving Eq\n\ninstance Show BluetoothPort where\n show = show . getPort\n\ngetPort :: BluetoothPort -> Int\ngetPort (L2CAPPort p) = fromIntegral p\ngetPort (RFCOMMPort p) = fromIntegral p\n\nmkPort :: BluetoothProtocol -> Int -> IO BluetoothPort\nmkPort RFCOMM port | 1 <= port && port <= 30\n = return . RFCOMMPort $ fromIntegral port\nmkPort RFCOMM _ = ioError $ userError \"RFCOMM ports must be between 1 and 30.\"\nmkPort L2CAP port | odd port && 4097 <= port && port <= 32767\n = return . L2CAPPort $ fromIntegral port\nmkPort L2CAP _ = ioError $ userError \"L2CAP ports must be odd numbers between 4097 and 32,767.\"\n\nbindAnyPort :: BluetoothProtocol -> BluetoothAddr -> IO BluetoothPort\nbindAnyPort proto addr = do\n avails <- flip filterM (portRange proto) $ \\portNum -> do\n sock <- bluetoothSocket proto\n res <- try $ bluetoothBind sock addr portNum\n close sock\n return $ isRight (res :: Either IOError ())\n case avails of\n portNum:_ -> mkPort proto portNum\n _ -> ioError $ userError \"Unable to find any available port\"\n where\n portRange L2CAP = [4097, 4099 .. 32767]\n portRange RFCOMM = [1 .. 30]\n\nbluetoothListen :: Socket -> Int -> IO ()\nbluetoothListen = listen -- TODO: tweak exception handling\n\nbluetoothAccept :: Socket -> IO (Socket, BluetoothAddr)\nbluetoothAccept (MkSocket fd family sockType proto sockStatus) = do\n currentStatus <- readMVar sockStatus\n when (currentStatus \/= Connected && currentStatus \/= Listening) . ioError . userError $\n \"accept: can't perform accept on socket (\" ++ show (family,sockType,proto) ++ \") in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> callAccept {#sizeof sockaddr_l2_t #} c_sockaddr_l2_get_bdaddr\n RFCOMM -> callAccept {#sizeof sockaddr_rc_t #} c_sockaddr_rc_get_bdaddr\n where\n callAccept :: SockAddrPtr p =>\n Int\n -> (Ptr BluetoothAddr -> Ptr p -> IO (Ptr BluetoothAddr))\n -> IO (Socket, BluetoothAddr)\n callAccept size getter =\n allocaBytes size $ \\sockaddrPtr ->\n allocaBytes (sizeOf (undefined :: BluetoothAddr)) $ \\bdaddrPtr -> do\n (newFd,_) <- throwErrnoIf ((== -1) . fst) \"accept\" $ c_accept fd sockaddrPtr size\n _ <- getter bdaddrPtr sockaddrPtr\n bdaddr <- peek bdaddrPtr\n newStatus <- newMVar Connected\n return (MkSocket newFd family sockType proto newStatus, bdaddr)\n\n-- bluetoothAccept :: Socket -> BluetoothAddr -> Int -> IO ()\n-- bluetoothAccept (MkSocket fd _ _ proto sockStatus) bdaddr portNum = do\n-- modifyMVar sockStatus $ \\status -> do\n-- when (status \/= NotConnected) . ioError . userError $\n-- \"accept: can't peform connect on socket in status \" ++ show status\n-- btPort <- mkPort (cToEnum proto) bdaddr portNum\n\ngetSockPort :: Socket -> IO BluetoothPort\ngetSockPort (MkSocket fd _ _ proto status) = do\n currentStatus <- readMVar status\n when (currentStatus == NotConnected || currentStatus == Closed) . ioError . userError $\n \"getsockname: can't get name of socket in status \" ++ show currentStatus\n case cToEnum proto of\n L2CAP -> callGetSockName {#sizeof sockaddr_l2_t #}\n ({#get sockaddr_l2_t.l2_psm #} :: SockAddrL2CAPPtr -> IO CUShort)\n L2CAPPort\n RFCOMM -> callGetSockName {#sizeof sockaddr_rc_t #}\n ({#get sockaddr_rc_t.rc_channel #} :: SockAddrRFCOMMPtr -> IO CUInt8)\n RFCOMMPort\n where\n callGetSockName :: (Integral i, Integral j, SockAddrPtr p) =>\n Int\n -> (Ptr p -> IO i)\n -> (j -> BluetoothPort)\n -> IO BluetoothPort\n callGetSockName size getter portCon = allocaBytes size $ \\sockaddrPtr -> do\n throwErrnoIf_ ((== -1) . fst) \"getsockname\" $ c_getsockname fd sockaddrPtr size\n fmap portCon $ getFromIntegral getter sockaddrPtr \n ","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ae04fe654da398262a733da6f264d75528d5e15e","subject":"wibble","message":"wibble\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 BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Data.Maybe (mapMaybe)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal as B\n\n#if CUDA_VERSION < 5050\nimport Debug.Trace (trace)\n#endif\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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2012] 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 Management\n Module, JITOption(..), JITTarget(..), JITResult(..),\n\n -- ** Querying module inhabitants\n getFun, getPtr, getTex,\n\n -- ** Loading and unloading modules\n loadFile,\n loadData, loadDataFromPtr,\n loadDataEx, loadDataFromPtrEx,\n unload\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Analysis.Device\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 (throwIO)\nimport Debug.Trace (trace)\nimport Data.Maybe (mapMaybe)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.ByteString.Internal 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 deriving (Eq, Show)\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 !Compute -- ^ compilation target, otherwise determined from context\n | FallbackStrategy !JITFallback -- ^ fallback strategy if matching cubin not found\n | GenerateDebugInfo -- ^ generate debug info (-g) (requires cuda >= 5.5)\n | GenerateLineInfo -- ^ generate line number information (-lineinfo) (requires cuda >= 5.5)\n | Verbose -- ^ verbose log messages (requires cuda >= 5.5)\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 assembly\n jitModule :: !Module -- ^ compilation error log or compiled module\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--\n{-# INLINEABLE getFun #-}\ngetFun :: Module -> String -> IO Fun\ngetFun !mdl !fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{-# INLINE cuModuleGetFunction #-}\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--\n{-# INLINEABLE getPtr #-}\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{-# INLINE cuModuleGetGlobal #-}\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--\n{-# INLINEABLE getTex #-}\ngetTex :: Module -> String -> IO Texture\ngetTex !mdl !name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{-# INLINE cuModuleGetTexRef #-}\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--\n{-# INLINEABLE loadFile #-}\nloadFile :: FilePath -> IO Module\nloadFile !ptx = resultIfOk =<< cuModuleLoad ptx\n\n{-# INLINE cuModuleLoad #-}\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 is (typically) the contents of a cubin or\n-- PTX file.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadData #-}\nloadData :: ByteString -> IO Module\nloadData !img =\n B.useAsCString img (\\p -> loadDataFromPtr (castPtr p))\n\n-- |\n-- As 'loadData', but read the image data from the given pointer. The image is a\n-- NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtr #-}\nloadDataFromPtr :: Ptr Word8 -> IO Module\nloadDataFromPtr !img = resultIfOk =<< cuModuleLoadData img\n\n{-# INLINE cuModuleLoadData #-}\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a module with online compiler\n-- options, and load the module into the current context. The image is\n-- (typically) the contents of a cubin or PTX file. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\n-- Note that the 'ByteString' will be copied into a temporary staging area so\n-- that it can be passed to C.\n--\n{-# INLINEABLE loadDataEx #-}\nloadDataEx :: ByteString -> [JITOption] -> IO JITResult\nloadDataEx !img !options =\n B.useAsCString img (\\p -> loadDataFromPtrEx (castPtr p) options)\n\n-- |\n-- As 'loadDataEx', but read the image data from the given pointer. The image is\n-- a NULL-terminated sequence of bytes.\n--\n{-# INLINEABLE loadDataFromPtrEx #-}\nloadDataFromPtrEx :: Ptr Word8 -> [JITOption] -> IO JITResult\nloadDataFromPtrEx !img !options = do\n fp_ilog <- B.mallocByteString logSize\n\n allocaArray logSize $ \\p_elog -> do\n withForeignPtr fp_ilog $ \\p_ilog -> do\n\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first, this is extracted below\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)) ] ++ mapMaybe unpack options\n\n withArray (map cFromEnum opt) $ \\p_opts -> do\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n\n case s of\n Success -> do\n time <- peek (castPtr p_vals)\n infoLog <- B.fromForeignPtr (castForeignPtr fp_ilog) 0 `fmap` c_strnlen p_ilog logSize\n return $! JITResult time infoLog mdl\n\n _ -> do\n errLog <- peekCString p_elog\n cudaError (unlines [describe s, errLog])\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = Just (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = Just (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = Just (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = Just (JIT_TARGET, jitTargetOfCompute x)\n unpack (FallbackStrategy x) = Just (JIT_FALLBACK_STRATEGY, fromEnum x)\n#if CUDA_VERSION >= 5050\n unpack GenerateDebugInfo = Just (JIT_GENERATE_DEBUG_INFO, fromEnum True)\n unpack GenerateLineInfo = Just (JIT_GENERATE_LINE_INFO, fromEnum True)\n unpack Verbose = Just (JIT_LOG_VERBOSE, fromEnum True)\n#else\n unpack x = trace (\"Warning: JITOption '\" ++ show x ++ \"' requires at least cuda-5.5\") Nothing\n#endif\n\n jitTargetOfCompute (Compute x y)\n = fromEnum\n $ case (x,y) of\n (1,0) -> Compute10\n (1,1) -> Compute11\n (1,2) -> Compute12\n (1,3) -> Compute13\n (2,0) -> Compute20\n (2,1) -> Compute21\n (3,0) -> Compute30\n (3,5) -> Compute35\n _ -> error (\"Unknown JIT Target for Compute \" ++ show (Compute x y))\n\n\n{-# INLINE cuModuleLoadDataEx #-}\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , castPtr `Ptr Word8'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\n{-# INLINEABLE unload #-}\nunload :: Module -> IO ()\nunload !m = nothingIfOk =<< cuModuleUnload m\n\n{-# INLINE cuModuleUnload #-}\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE resultIfFound #-}\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\n{-# INLINE peekMod #-}\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\n{-# INLINE c_strnlen' #-}\nforeign import ccall unsafe \"string.h strnlen\" c_strnlen'\n :: CString -> CSize -> IO CSize\n\n{-# INLINE c_strnlen #-}\nc_strnlen :: CString -> Int -> IO Int\nc_strnlen str maxlen = cIntConv `fmap` c_strnlen' str (cIntConv maxlen)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7d9a083a9b191748283f60573b2841bd571fa017","subject":"gconf: S.G.G.GConfValue: remove -fallow-overlapping-instances (it's handled in the makefile)","message":"gconf: S.G.G.GConfValue: remove -fallow-overlapping-instances (it's handled in the makefile)\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer","old_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_file":"gconf\/System\/Gnome\/GConf\/GConfValue.chs","new_contents":"-- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Control.Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","old_contents":"{-# OPTIONS -fallow-overlapping-instances #-} -- String & [a] overlap\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GConf API\n--\n-- Author : Duncan Coutts\n-- Created: 16 April 2004\n--\n-- Copyright (c) 2004 Duncan Coutts\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-- |\n-- \n-- Module for dealing with the values stored in the GConf system.\n--\n-- GConfValue has its own primitive type system which is represented in\n-- Haskell using type classes. This allows values to be get and set without\n-- needing to perform any dynamic type casting or needing a union type.\n-- \n-- Alternatively, a dynamic\\\/union type is provided for the rare occasions\n-- when that degree of flexability is required. It should only be necessary\n-- if you need to deal with configuration values without statically knowing\n-- their type.\n--\n\nmodule System.Gnome.GConf.GConfValue (\n GConfPrimitiveValueClass,\n GConfValueClass(marshalFromGConfValue, marshalToGConfValue),\n GConfValue(GConfValue),\n GConfValueDyn(..),\n ) where\n\nimport Control.Monad (liftM, when)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList (toGSList, readGSList)\n\n--{# context lib=\"gconf\" prefix =\"gconf_value\" #}\n{# context lib=\"gconf\" #}\n\n{# enum GConfValueType {underscoreToCase} deriving (Eq, Show) #}\n\n{# pointer *GConfValue newtype #}\n\n-- | Class of types which can be kept by GConf\nclass GConfValueClass value where\n --unsafe because assumes non-null pointer and correct type\n unsafeMarshalFromGConfValue :: GConfValue -> IO value\n \n -- safe checked version, may throw exception\n marshalFromGConfValue :: GConfValue -> IO value\n marshalFromGConfValue value = do\n checkForNullAndExpectedType (typeofGConfValue (undefined::value)) value\n unsafeMarshalFromGConfValue value\n\n typeofGConfValue :: value -> GConfValueType\n\n marshalToGConfValue :: value -> IO GConfValue\n\n-- The above methods follow the following memory management rules regarding\n-- GConfValues: marshalFrom reads the value but does not gain ownership and thus\n-- does not deallocate. marshalTo allocates a new value and gives up ownership;\n-- it is not responsible for dellocation (it does not attach a finaliser).\n-- The code that uses marshalTo must ensure that it hands the value off to a\n-- function that is prepared to asume ownership of the value.\n\n-- | Dynamic version for when the type is not known statically.\ndata GConfValueDyn = GConfValueString String\n | GConfValueInt Int\n | GConfValueFloat Double\n | GConfValueBool Bool\n | GConfValueSchema -- ^ Not supported\n | GConfValueList [GConfValueDyn] -- ^ Must all be of same primitive type\n | GConfValuePair (GConfValueDyn, GConfValueDyn) -- ^ Must both be primitive\n\n-- Allow variant using Maybe, where Nothing means the value was not set\n-- Use this variant when you expect the gconf key to not be set somethimes;\n-- otherwise the 'raw' types will raise an exception if you get an unset key.\n-- Just for consistency, setting a key to Nothing will unset the key, however\n-- it is preferable to use gconfClientUnset explicitly.\ninstance GConfValueClass value => GConfValueClass (Maybe value) where\n typeofGConfValue _ = typeofGConfValue (undefined :: value)\n unsafeMarshalFromGConfValue = marshalFromGConfValue\n marshalFromGConfValue value =\n catch (liftM Just $ marshalFromGConfValue value)\n (\\_ -> return Nothing)\n marshalToGConfValue (Just v) = marshalToGConfValue v\n marshalToGConfValue Nothing = return $ GConfValue nullPtr\n\n-- The GConfValue type system says some types are primitive.\n-- Compound types (lists & pairs) may only be constructed from primitive types.\nclass GConfValueClass value => GConfPrimitiveValueClass value\ninstance GConfPrimitiveValueClass Int\ninstance GConfPrimitiveValueClass Bool\ninstance GConfPrimitiveValueClass Double\ninstance GConfPrimitiveValueClass String\n\ninstance GConfValueClass Int where\n typeofGConfValue _ = GconfValueInt\n unsafeMarshalFromGConfValue = liftM fromIntegral . {# call unsafe gconf_value_get_int #}\n marshalToGConfValue n = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueInt)\n {# call unsafe gconf_value_set_int #} (GConfValue value) (fromIntegral n)\n return (GConfValue value)\n\ninstance GConfValueClass Bool where\n typeofGConfValue _ = GconfValueBool\n unsafeMarshalFromGConfValue = liftM toBool . {# call unsafe gconf_value_get_bool #}\n marshalToGConfValue b = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueBool)\n {# call unsafe gconf_value_set_bool #} (GConfValue value) (fromBool b)\n return (GConfValue value)\n\ninstance GConfValueClass Double where\n typeofGConfValue _ = GconfValueFloat\n unsafeMarshalFromGConfValue = liftM realToFrac . {# call unsafe gconf_value_get_float #}\n marshalToGConfValue f = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueFloat)\n {# call unsafe gconf_value_set_float #} (GConfValue value) (realToFrac f)\n return (GConfValue value)\n\n-- Now unfortunately String & [a] overlap, although really they don't since Char\n-- is not an instance of GConfPrimitiveValueClass, however classes are open so\n-- we don't know that Char would never be an instance. I want closed classes!\ninstance GConfValueClass String where\n typeofGConfValue _ = GconfValueString\n\n unsafeMarshalFromGConfValue value = do\n strPtr <- {# call unsafe gconf_value_get_string #} value\n peekUTFString strPtr\n\n marshalToGConfValue s = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueString)\n withCString s $ \\strPtr ->\n {# call unsafe gconf_value_set_string #} (GConfValue value) strPtr\n return (GConfValue value)\n\ninstance (GConfPrimitiveValueClass a, GConfPrimitiveValueClass b) => GConfValueClass (a,b) where\n typeofGConfValue _ = GconfValuePair\n\n unsafeMarshalFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a',b')\n\n marshalToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\n\ninstance GConfPrimitiveValueClass a => GConfValueClass [a] where\n typeofGConfValue _ = GconfValueList\n\n unsafeMarshalFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\n marshalFromGConfValue value = do\n checkForNullAndExpectedType GconfValueList value\n listType <- liftM (toEnum . fromIntegral) $\n {# call unsafe gconf_value_get_list_type #} value\n when (listType \/= typeofGConfValue (undefined :: a))\n (fail \"GConf: key is list with elements of unexpected type\")\n unsafeMarshalFromGConfValue value\n\n marshalToGConfValue list = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) list\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ typeofGConfValue (undefined::a))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\n----------------\n-- For convenience and best practice, an instance for Enum \n-- This conforms to the GConf GTK+\/Gnome convention for storing enum types,\n-- which is to store them as a string using ThisStlyeOfCapitalisation.\n\n-- Note: currently disabled since it requires -fallow-undecidable-instances\n{-\ninstance (Show enum, Read enum, Enum enum, GConfValueClass enum)\n => GConfPrimitiveValueClass enum\ninstance (Show enum, Read enum, Enum enum) => GConfValueClass enum where\n marshalFromGConfValue value = do\n enumStr <- marshalFromGConfValue value\n case reads enumStr of\n [(enum,_)] -> return enum\n _ -> fail \"GCconf: invalid enum value\"\n marshalFromGConfValue' value = do\n maybeEnumStr <- marshalFromGConfValue' value\n case maybeEnumStr of\n Nothing -> return Nothing\n (Just enumStr) -> case reads enumStr of\n [(enum,_)] -> return (Just enum)\n _ -> return Nothing\n marshalToGConfValue enum = marshalToGConfValue (show enum)\n typeofGConfValue _ = GconfValueString\n-}\n\n----------------\n-- Helper funcs\n\ngconfValueGetType :: GConfValue -> IO GConfValueType\n--we mean the following but unfortunately c2hs barfs on 'type'\n--gconfValueGetType (GConfValue valuePtr) = {# get GConfValue->type #} valuePtr\n-- so instead we have the ugly:\ngconfValueGetType (GConfValue valuePtr) =\n liftM (toEnum . fromIntegral) $ peek (castPtr valuePtr :: Ptr CInt)\n--TODO: check that sizeof(GConfValueType) == sizeof(int)\n\n-- returns Nothing if ok, or and error message\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO ()\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n when (valueType \/= expectedType)\n (fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType)\n\n{-\ncheckForNullAndExpectedType :: GConfValueType -> GConfValue -> IO GConfValue\ncheckForNullAndExpectedType expectedType value@(GConfValue ptr)\n | ptr == nullPtr = fail \"GConf: cannot get value of key, key is unset\"\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then fail $ \"GConf: key is of unexpected type, expected: \"\n ++ show expectedType ++ \", got: \" ++ show valueType\n else return value\n\ncheckForNullAndExpectedType' :: GConfValueType -> GConfValue -> IO (Maybe GConfValue)\ncheckForNullAndExpectedType' expectedType value@(GConfValue ptr)\n | ptr == nullPtr = return Nothing\n | otherwise = do valueType <- gconfValueGetType value\n if valueType \/= expectedType\n then return Nothing\n else return (Just value)\n-}\n----------------\n-- GConfValueDyn\n\nunsafeMarshalGConfValueDynListFromGConfValue :: GConfValue -> IO [GConfValueDyn]\nunsafeMarshalGConfValueDynListFromGConfValue value = do\n gsList <- {# call unsafe gconf_value_get_list #} value\n valuesPtrs <- readGSList gsList\n mapM (unsafeMarshalFromGConfValue . GConfValue) valuesPtrs\n\nmarshalGConfValueDynListToGConfValue :: [GConfValueDyn] -> IO GConfValue\nmarshalGConfValueDynListToGConfValue as = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValueList)\n valuesPtrs <- mapM (liftM (\\(GConfValue ptr) -> ptr) . marshalToGConfValue) as\n valuesList <- toGSList valuesPtrs\n {# call unsafe gconf_value_set_list_type #} (GConfValue value)\n (fromIntegral $ fromEnum $ (case as of\n [] -> GconfValueInvalid --unknown type\n (a:_) -> gconfValueDynGetType (head as)))\n {# call unsafe gconf_value_set_list_nocopy #} (GConfValue value) valuesList\n return (GConfValue value)\n\nunsafeMarshalGConfValueDynPairFromGConfValue :: GConfValue -> IO (GConfValueDyn, GConfValueDyn)\nunsafeMarshalGConfValueDynPairFromGConfValue value = do\n a <- {# call unsafe gconf_value_get_car #} value\n b <- {# call unsafe gconf_value_get_cdr #} value\n a' <- marshalFromGConfValue (GConfValue a)\n b' <- marshalFromGConfValue (GConfValue b)\n return (a', b')\n\nmarshalGConfValueDynPairToGConfValue :: (GConfValueDyn, GConfValueDyn) -> IO GConfValue\nmarshalGConfValueDynPairToGConfValue (a,b) = do\n value <- {# call unsafe gconf_value_new #}\n (fromIntegral $ fromEnum GconfValuePair)\n a' <- marshalToGConfValue a\n b' <- marshalToGConfValue b\n {# call unsafe gconf_value_set_car_nocopy #} (GConfValue value) a'\n {# call unsafe gconf_value_set_cdr_nocopy #} (GConfValue value) b'\n return (GConfValue value)\n\ninstance GConfValueClass GConfValueDyn where\n typeofGConfValue _ = undefined -- will never be used\n unsafeMarshalFromGConfValue value = do\n valueType <- gconfValueGetType value\n case valueType of\n GconfValueString -> liftM GConfValueString $ unsafeMarshalFromGConfValue value\n GconfValueInt -> liftM GConfValueInt $ unsafeMarshalFromGConfValue value\n GconfValueFloat -> liftM GConfValueFloat $ unsafeMarshalFromGConfValue value\n GconfValueBool -> liftM GConfValueBool $ unsafeMarshalFromGConfValue value\n GconfValueSchema -> return GConfValueSchema\n GconfValueList -> liftM GConfValueList $ unsafeMarshalGConfValueDynListFromGConfValue value\n GconfValuePair -> liftM GConfValuePair $ unsafeMarshalGConfValueDynPairFromGConfValue value\n \n marshalFromGConfValue value@(GConfValue ptr) = do\n when (ptr == nullPtr) $ fail \"GConf: cannot get value of key, key is unset\"\n unsafeMarshalFromGConfValue value\n \n marshalToGConfValue v = case v of\n (GConfValueString v') -> marshalToGConfValue v'\n (GConfValueInt v') -> marshalToGConfValue v'\n (GConfValueFloat v') -> marshalToGConfValue v'\n (GConfValueBool v') -> marshalToGConfValue v'\n (GConfValueSchema ) -> fail \"GConf: setting schema types not supported\"\n (GConfValueList v') -> marshalGConfValueDynListToGConfValue v'\n (GConfValuePair v') -> marshalGConfValueDynPairToGConfValue v'\n\ngconfValueDynGetType :: GConfValueDyn -> GConfValueType\ngconfValueDynGetType (GConfValueString _) = GconfValueString\ngconfValueDynGetType (GConfValueInt _) = GconfValueInt\ngconfValueDynGetType (GConfValueFloat _) = GconfValueFloat\ngconfValueDynGetType (GConfValueBool _) = GconfValueBool\ngconfValueDynGetType (GConfValueList _) = GconfValueList\ngconfValueDynGetType (GConfValuePair _) = GconfValuePair\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"6cafdab11f4fbfc07c6cc062639f091e0a97f8e7","subject":"gstreamer: fix types for event handlers in Element.chs","message":"gstreamer: fix types for event handlers in Element.chs\n\ndarcs-hash:20070720201151-21862-bdb8a50b8a8467e1d15227d2745e6e69d95b7cf9.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Element.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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (Pad -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" 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-- Version $Revision$ from $Date$\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 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--\nmodule Media.Streaming.GStreamer.Element (\n \n Element,\n ElementClass,\n castToElement,\n toElement,\n fromElement,\n ElementFlags(..),\n State(..),\n StateChange(..),\n StateChangeReturn(..),\n elementAddPad,\n elementGetPad,\n elementGetCompatiblePad,\n elementGetCompatiblePadTemplate,\n elementGetRequestPad,\n elementGetStaticPad,\n elementNoMorePads,\n elementReleaseRequestPad,\n elementRemovePad,\n elementIteratePads,\n elementIterateSinkPads,\n elementIterateSrcPads,\n elementLink,\n elementUnlink,\n elementLinkPads,\n elementUnlinkPads,\n elementLinkPadsFiltered,\n elementLinkFiltered,\n elementSetBaseTime,\n elementGetBaseTime,\n elementSetBus,\n elementGetBus,\n elementGetFactory,\n elementSetIndex,\n elementIsIndexable,\n elementRequiresClock,\n elementSetClock,\n elementGetClock,\n elementProvidesClock,\n elementProvideClock,\n elementSetState,\n elementGetState,\n elementSetLockedState,\n elementIsLockedState,\n elementAbortState,\n elementStateGetName,\n elementStateChangeReturnGetName,\n elementSyncStateWithParent,\n elementGetQueryTypes,\n elementQuery,\n elementQueryConvert,\n elementQueryPosition,\n elementQueryDuration,\n elementSendEvent, \n elementSeekSimple,\n elementSeek,\n onElementNoMorePads,\n afterElementNoMorePads,\n onElementPadAdded,\n afterElementPadAdded,\n onElementPadRemoved,\n afterElementPadRemoved\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString )\n{#import System.Glib.Signals#}\n{#import System.Glib.GObject#}\n{#import Media.Streaming.GStreamer.Types#}\n{#import Media.Streaming.GStreamer.Signals#}\nimport GHC.Base ( unsafeCoerce# )\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nelementAddPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementAddPad element pad =\n liftM toBool $ {# call element_add_pad #} (toElement element) (toPad pad)\n\nelementGetPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetPad element name =\n (withUTFString name $ {# call element_get_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementGetCompatiblePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> Caps\n -> IO (Maybe Pad)\nelementGetCompatiblePad element pad caps =\n {# call element_get_compatible_pad #} (toElement element) (toPad pad) caps >>=\n maybePeek newPad\n\nelementGetCompatiblePadTemplate :: (ElementClass elementT, PadTemplateClass padTemplateT) =>\n elementT\n -> padTemplateT\n -> IO (Maybe PadTemplate)\nelementGetCompatiblePadTemplate element padTemplate =\n {# call element_get_compatible_pad_template #} (toElement element) (toPadTemplate padTemplate) >>=\n maybePeek newPadTemplate\n\n\nelementGetRequestPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetRequestPad element name =\n (withUTFString name $ {# call element_get_request_pad #} (toElement element)) >>=\n maybePeek newPad_ -- no finalizer; use elementReleaseRequestPad\n\nelementGetStaticPad :: ElementClass elementT =>\n elementT\n -> String\n -> IO (Maybe Pad)\nelementGetStaticPad element name =\n (withUTFString name $ {# call element_get_static_pad #} (toElement element)) >>=\n maybePeek newPad\n\nelementNoMorePads :: ElementClass elementT =>\n elementT\n -> IO ()\nelementNoMorePads element =\n {# call element_no_more_pads #} (toElement element)\n\nelementReleaseRequestPad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO ()\nelementReleaseRequestPad element pad =\n {# call element_release_request_pad #} (toElement element) (toPad pad)\n\nelementRemovePad :: (ElementClass elementT, PadClass padT) =>\n elementT\n -> padT\n -> IO Bool\nelementRemovePad element pad =\n liftM toBool $ {# call element_remove_pad #} (toElement element) (toPad pad)\n\nelementIteratePads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIteratePads element =\n {# call element_iterate_pads #} (toElement element) >>= newIterator\n\nelementIterateSinkPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSinkPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementIterateSrcPads :: (ElementClass elementT) =>\n elementT\n -> IO (Iterator Pad)\nelementIterateSrcPads element =\n {# call element_iterate_sink_pads #} (toElement element) >>= newIterator\n\nelementLink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO Bool\nelementLink element1 element2 =\n liftM toBool $ {# call element_link #} (toElement element1) (toElement element2)\n\nelementUnlink :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> IO ()\nelementUnlink element1 element2 =\n {# call element_unlink #} (toElement element1) (toElement element2)\n\nelementLinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO Bool\nelementLinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementUnlinkPads :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> IO ()\nelementUnlinkPads src srcPadName dest destPadName =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n {# call element_unlink_pads #} (toElement src) cSrcPadName (toElement dest) cDestPadName\n\nelementLinkPadsFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> String\n -> elementT2\n -> String\n -> Caps\n -> IO Bool\nelementLinkPadsFiltered src srcPadName dest destPadName filter =\n withUTFString destPadName $ \\cDestPadName ->\n withUTFString srcPadName $ \\cSrcPadName ->\n liftM toBool $ {# call element_link_pads_filtered #} (toElement src) cSrcPadName (toElement dest) cDestPadName filter\n\nelementLinkFiltered :: (ElementClass elementT1, ElementClass elementT2) =>\n elementT1\n -> elementT2\n -> Maybe Caps\n -> IO Bool\nelementLinkFiltered element1 element2 filter =\n liftM toBool $\n {# call element_link_filtered #} (toElement element1) (toElement element2) $\n fromMaybe (Caps nullForeignPtr) filter\n\nelementSetBaseTime :: ElementClass elementT =>\n elementT\n -> ClockTimeDiff\n -> IO ()\nelementSetBaseTime element time =\n {# call element_set_base_time #} (toElement element) $ fromIntegral time\n\nelementGetBaseTime :: ElementClass elementT =>\n elementT\n -> IO ClockTimeDiff\nelementGetBaseTime element =\n liftM fromIntegral $ {# call element_get_base_time #} (toElement element)\n\nelementSetBus :: (ElementClass elementT, BusClass busT) =>\n elementT\n -> busT\n -> IO ()\nelementSetBus element bus =\n {# call element_set_bus #} (toElement element) (toBus bus)\n\nelementGetBus :: ElementClass elementT =>\n elementT\n -> IO Bus\nelementGetBus element =\n {# call element_get_bus #} (toElement element) >>= newBus\n\nelementGetFactory :: ElementClass elementT =>\n elementT\n -> IO ElementFactory\nelementGetFactory element =\n {# call element_get_factory #} (toElement element) >>= newElementFactory_\n\nelementSetIndex :: (ElementClass elementT, IndexClass indexT) =>\n elementT\n -> indexT\n -> IO ()\nelementSetIndex element index =\n {# call element_set_index #} (toElement element) (toIndex index)\n\nelementGetIndex :: ElementClass elementT =>\n elementT\n -> IO (Maybe Index)\nelementGetIndex element =\n {# call element_get_index #} (toElement element) >>= maybePeek newIndex\n\nelementIsIndexable :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsIndexable element =\n liftM toBool $ {# call element_is_indexable #} (toElement element)\n\nelementRequiresClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementRequiresClock element =\n liftM toBool $ {# call element_requires_clock #} (toElement element)\n\nelementSetClock :: (ElementClass elementT, ClockClass clockT) =>\n elementT\n -> clockT\n -> IO Bool\nelementSetClock element clock =\n liftM toBool $ {# call element_set_clock #} (toElement element) (toClock clock)\n\nelementGetClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementGetClock element =\n {# call element_get_clock #} (toElement element) >>= maybePeek newClock\n\nelementProvidesClock :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementProvidesClock element =\n liftM toBool $ {# call element_provides_clock #} $ toElement element\n\nelementProvideClock :: ElementClass elementT =>\n elementT\n -> IO (Maybe Clock)\nelementProvideClock element =\n {# call element_provide_clock #} (toElement element) >>= maybePeek newClock\n\nelementSetState :: ElementClass elementT =>\n elementT\n -> State\n -> IO StateChangeReturn\nelementSetState element state =\n liftM (toEnum . fromIntegral) $ {# call element_set_state #} (toElement element) $\n fromIntegral $ fromEnum state\n\nelementGetState :: ElementClass elementT =>\n elementT\n -> ClockTime\n -> IO (StateChangeReturn, State, State)\nelementGetState element timeout =\n alloca $ \\statePtr ->\n alloca $ \\pendingPtr ->\n do result <- {# call element_get_state #} (toElement element) statePtr pendingPtr $ fromIntegral timeout\n state <- peek statePtr\n pending <- peek pendingPtr\n return (toEnum (fromIntegral result),\n toEnum (fromIntegral state),\n toEnum (fromIntegral pending))\n\nelementSetLockedState :: ElementClass elementT =>\n elementT\n -> Bool\n -> IO Bool\nelementSetLockedState element lockedState =\n liftM toBool $ {# call element_set_locked_state #} (toElement element) $ fromBool lockedState\n\nelementIsLockedState :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementIsLockedState element =\n liftM toBool $ {# call element_is_locked_state #} $ toElement element\n\nelementAbortState :: ElementClass elementT =>\n elementT\n -> IO ()\nelementAbortState element =\n {# call element_abort_state #} $ toElement element\n\nelementStateGetName :: State\n -> String\nelementStateGetName state =\n unsafePerformIO $ ({# call element_state_get_name #} $ fromIntegral $ fromEnum state) >>= peekUTFString\n\nelementStateChangeReturnGetName :: StateChangeReturn\n -> String\nelementStateChangeReturnGetName stateRet =\n unsafePerformIO $ ({# call element_state_change_return_get_name #} $ fromIntegral $ fromEnum stateRet) >>= peekUTFString\n\nelementSyncStateWithParent :: ElementClass elementT =>\n elementT\n -> IO Bool\nelementSyncStateWithParent element =\n liftM toBool $ {# call element_sync_state_with_parent #} $ toElement element\n\nelementGetQueryTypes :: ElementClass element\n => element\n -> IO [QueryType]\nelementGetQueryTypes element =\n liftM (map (toEnum . fromIntegral)) $\n {# call element_get_query_types #} (toElement element) >>=\n peekArray0 0\n\nelementQuery :: (ElementClass element, QueryClass query)\n => element\n -> query\n -> IO (Maybe query)\nelementQuery element query =\n do query' <- {# call mini_object_copy #} (toMiniObject query) >>=\n newForeignPtr_ . castPtr\n success <- {# call element_query #} (toElement element) $ Query query'\n if toBool success\n then liftM (Just . unsafeCoerce#) $ withForeignPtr query' $ newQuery . castPtr\n else return Nothing\n\nelementQueryConvert :: ElementClass element\n => element\n -> Format\n -> Int64\n -> IO (Maybe (Format, Int64))\nelementQueryConvert element srcFormat srcVal =\n alloca $ \\destFormatPtr ->\n alloca $ \\destValPtr ->\n do success <- {# call element_query_convert #} (toElement element)\n (fromIntegral $ fromEnum srcFormat)\n (fromIntegral srcVal)\n destFormatPtr\n destValPtr\n if toBool success\n then do destFormat <- peek destFormatPtr\n destVal <- peek destValPtr\n return $ Just (toEnum $ fromIntegral destFormat,\n fromIntegral destVal)\n else return Nothing\n\nelementQueryPosition :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryPosition element =\n alloca $ \\formatPtr ->\n alloca $ \\curPtr ->\n do success <- {# call element_query_position #} (toElement element) formatPtr curPtr\n if toBool success\n then do format <- peek formatPtr\n cur <- peek curPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral cur)\n else return Nothing\n\nelementQueryDuration :: ElementClass element\n => element\n -> IO (Maybe (Format, Int64))\nelementQueryDuration element =\n alloca $ \\formatPtr ->\n alloca $ \\durationPtr ->\n do success <- {# call element_query_duration #} (toElement element) formatPtr durationPtr\n if toBool success\n then do format <- peek formatPtr\n duration <- peek durationPtr\n return $ Just (toEnum $ fromIntegral format,\n fromIntegral duration)\n else return Nothing\n\nelementSendEvent :: (ElementClass element, EventClass event)\n => element\n -> event\n -> IO Bool\nelementSendEvent element event =\n liftM toBool $\n giveMiniObject (toEvent event) $ {# call element_send_event #} (toElement element)\n\nelementSeekSimple :: ElementClass element\n => element\n -> Format\n -> [SeekFlags]\n -> Int64\n -> IO Bool\nelementSeekSimple element format seekFlags seekPos =\n liftM toBool $\n {# call element_seek_simple #} (toElement element)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags seekFlags)\n (fromIntegral seekPos)\n\nelementSeek :: ElementClass element\n => element\n -> Double\n -> Format\n -> [SeekFlags]\n -> SeekType\n -> Int64\n -> SeekType\n -> Int64\n -> IO Bool\nelementSeek element rate format flags curType cur stopType stop =\n liftM toBool $\n {# call element_seek #} (toElement element)\n (realToFrac rate)\n (fromIntegral $ fromEnum format)\n (fromIntegral $ fromFlags flags)\n (fromIntegral $ fromEnum curType)\n (fromIntegral cur)\n (fromIntegral $ fromEnum stopType)\n (fromIntegral stop)\n\nonElementNoMorePads, afterElementNoMorePads :: (ElementClass element)\n => element\n -> IO ()\n -> IO (ConnectId element)\nonElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" False\nafterElementNoMorePads =\n connect_NONE__NONE \"no-more-pads\" True\n\nonElementPadAdded, afterElementPadAdded :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" False\nafterElementPadAdded =\n connect_OBJECT__NONE \"pad-added\" True\n\nonElementPadRemoved, afterElementPadRemoved :: (ElementClass element)\n => element\n -> (GObject -> IO ())\n -> IO (ConnectId element)\nonElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" False\nafterElementPadRemoved =\n connect_OBJECT__NONE \"pad-removed\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"ad75cc214e1c678f08ad0d6cf64db2badf71bd21","subject":"documentation for device properties","message":"documentation for device properties\n\nIgnore-this: 64c50b87661f8452cf59dd29efc8cd21\n\ndarcs-hash:20090722051746-115f9-a21ec2489c931a60da3f2db9ba2af877e99e03f1.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Device.chs","new_file":"Foreign\/CUDA\/Device.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Device\n (\n ComputeMode,\n DeviceFlags,\n DeviceProperties,\n\n -- ** Device management\n choose,\n get,\n count,\n props,\n set,\n setFlags,\n setOrder\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum cudaComputeMode as ComputeMode { }\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlags { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String, -- ^ Identifier\n computeCapability :: Float, -- ^ Supported compute capability\n totalGlobalMem :: Int64, -- ^ Available global memory on the device in bytes\n totalConstMem :: Int64, -- ^ Available constant memory on the device in bytes\n sharedMemPerBlock :: Int64, -- ^ Available shared memory per block in bytes\n regsPerBlock :: Int, -- ^ 32-bit registers per block\n warpSize :: Int, -- ^ Warp size in threads\n maxThreadsPerBlock :: Int, -- ^ Max number of threads per block\n maxThreadsDim :: (Int,Int,Int), -- ^ Max size of each dimension of a block\n maxGridSize :: (Int,Int,Int), -- ^ Max size of each dimension of a grid\n clockRate :: Int, -- ^ Clock frequency in kilohertz\n multiProcessorCount :: Int, -- ^ Number of multiprocessors on the device\n memPitch :: Int64, -- ^ Max pitch in bytes allowed by memory copies\n textureAlignment :: Int64, -- ^ Alignment requirement for textures\n computeMode :: ComputeMode,\n deviceOverlap :: Bool, -- ^ Device can concurrently copy memory and execute a kernel\n kernelExecTimeoutEnabled :: Bool, -- ^ Whether there is a runtime limit on kernels\n integrated :: Bool, -- ^ As opposed to discrete\n canMapHostMemory :: Bool -- ^ Device can use pinned memory\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\nchoose :: DeviceProperties -> IO (Either String Int)\nchoose dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n-- |\n-- Returns which device is currently being used\n--\nget :: IO (Either String Int)\nget = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Return information about the selected compute device\n--\nprops :: Int -> IO (Either String DeviceProperties)\nprops n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek* ,\n `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set device to be used for GPU execution\n--\nset :: Int -> IO (Maybe String)\nset n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set flags to be used for device executions\n--\nsetFlags :: [DeviceFlags] -> IO (Maybe String)\nsetFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\nsetOrder :: [Int] -> IO (Maybe String)\nsetOrder l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\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-- Device management routines\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Device\n (\n ComputeMode,\n DeviceFlags,\n DeviceProperties,\n\n -- ** Device management\n choose,\n get,\n count,\n props,\n set,\n setFlags,\n setOrder\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Internal.Offsets\n\n#include \"cbits\/stubs.h\"\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n-- |\n-- The compute mode the device is currently in\n--\n{# enum cudaComputeMode as ComputeMode { }\n with prefix=\"cudaComputeMode\" deriving (Eq, Show) #}\n\n-- |\n-- Device execution flags\n--\n{# enum cudaDeviceFlags as DeviceFlags { }\n with prefix=\"cudaDeviceFlag\" deriving (Eq, Show) #}\n\n-- |\n-- The properties of a compute device\n--\ndata DeviceProperties = DeviceProperties\n {\n deviceName :: String,\n computeCapability :: Float,\n totalGlobalMem :: Int64,\n totalConstMem :: Int64,\n sharedMemPerBlock :: Int64,\n regsPerBlock :: Int,\n warpSize :: Int,\n maxThreadsPerBlock :: Int,\n maxThreadsDim :: (Int,Int,Int),\n maxGridSize :: (Int,Int,Int),\n clockRate :: Int,\n multiProcessorCount :: Int,\n memPitch :: Int64,\n textureAlignment :: Int64,\n computeMode :: ComputeMode,\n deviceOverlap :: Bool,\n kernelExecTimeoutEnabled :: Bool,\n integrated :: Bool,\n canMapHostMemory :: Bool\n }\n deriving (Show)\n\n\ninstance Storable DeviceProperties where\n sizeOf _ = {#sizeof cudaDeviceProp#}\n alignment _ = alignment (undefined :: Ptr ())\n\n peek p = do\n gm <- cIntConv `fmap` {#get cudaDeviceProp.totalGlobalMem#} p\n sm <- cIntConv `fmap` {#get cudaDeviceProp.sharedMemPerBlock#} p\n rb <- cIntConv `fmap` {#get cudaDeviceProp.regsPerBlock#} p\n ws <- cIntConv `fmap` {#get cudaDeviceProp.warpSize#} p\n mp <- cIntConv `fmap` {#get cudaDeviceProp.memPitch#} p\n tb <- cIntConv `fmap` {#get cudaDeviceProp.maxThreadsPerBlock#} p\n cl <- cIntConv `fmap` {#get cudaDeviceProp.clockRate#} p\n cm <- cIntConv `fmap` {#get cudaDeviceProp.totalConstMem#} p\n v1 <- fromIntegral `fmap` {#get cudaDeviceProp.major#} p\n v2 <- fromIntegral `fmap` {#get cudaDeviceProp.minor#} p\n ta <- cIntConv `fmap` {#get cudaDeviceProp.textureAlignment#} p\n ov <- cToBool `fmap` {#get cudaDeviceProp.deviceOverlap#} p\n pc <- cIntConv `fmap` {#get cudaDeviceProp.multiProcessorCount#} p\n ke <- cToBool `fmap` {#get cudaDeviceProp.kernelExecTimeoutEnabled#} p\n tg <- cToBool `fmap` {#get cudaDeviceProp.integrated#} p\n hm <- cToBool `fmap` {#get cudaDeviceProp.canMapHostMemory#} p\n md <- cToEnum `fmap` {#get cudaDeviceProp.computeMode#} p\n\n --\n -- C->Haskell returns the wrong type when accessing static arrays in\n -- structs, returning the dereferenced element but with a Ptr type. Work\n -- around this with manual pointer arithmetic...\n --\n n <- peekCString (p `plusPtr` devNameOffset)\n (t1:t2:t3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxThreadDimOffset :: Ptr CInt)\n (g1:g2:g3:_) <- map cIntConv `fmap` peekArray 3 (p `plusPtr` devMaxGridSizeOffset :: Ptr CInt)\n\n return DeviceProperties\n {\n deviceName = n,\n computeCapability = v1 + v2 \/ max 10 (10^ ((ceiling . logBase 10) v2 :: Int)),\n totalGlobalMem = gm,\n totalConstMem = cm,\n sharedMemPerBlock = sm,\n regsPerBlock = rb,\n warpSize = ws,\n maxThreadsPerBlock = tb,\n maxThreadsDim = (t1,t2,t3),\n maxGridSize = (g1,g2,g3),\n clockRate = cl,\n multiProcessorCount = pc,\n memPitch = mp,\n textureAlignment = ta,\n computeMode = md,\n deviceOverlap = ov,\n kernelExecTimeoutEnabled = ke,\n integrated = tg,\n canMapHostMemory = hm\n }\n\n\n--------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Select the compute device which best matches the given criteria\n--\nchoose :: DeviceProperties -> IO (Either String Int)\nchoose dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Status' cToEnum #}\n where\n withDevProp = with\n\n-- |\n-- Returns which device is currently being used\n--\nget :: IO (Either String Int)\nget = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Returns the number of devices available for execution, with compute\n-- capability >= 1.0\n--\ncount :: IO (Either String Int)\ncount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n-- |\n-- Return information about the selected compute device\n--\nprops :: Int -> IO (Either String DeviceProperties)\nprops n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek* ,\n `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set device to be used for GPU execution\n--\nset :: Int -> IO (Maybe String)\nset n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set flags to be used for device executions\n--\nsetFlags :: [DeviceFlags] -> IO (Maybe String)\nsetFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Status' cToEnum #}\n\n-- |\n-- Set list of devices for CUDA execution in priority order\n--\nsetOrder :: [Int] -> IO (Maybe String)\nsetOrder l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Status' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"92a0d786a4a0f5c5930b9d1243b96e0f1e2cc40c","subject":"fixes for 7.8.4","message":"fixes for 7.8.4\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/Algorithms.chs","new_file":"src\/GDAL\/Internal\/Algorithms.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE BangPatterns #-}\n\nmodule GDAL.Internal.Algorithms (\n GenImgProjTransformer (..)\n , GenImgProjTransformer2 (..)\n , GenImgProjTransformer3 (..)\n , SomeTransformer (..)\n\n , Contour (..)\n\n , GridPoint (..)\n , GridAlgorithm (..)\n , GridInverseDistanceToAPower (..)\n , GridMovingAverage (..)\n , GridNearestNeighbor (..)\n , GridDataMetrics (..)\n , MetricType (..)\n\n , GridAlgorithmEnum (..)\n\n , rasterizeLayersBuf\n , createGrid\n , createGridIO\n , computeProximity\n , contourGenerateVector\n , contourGenerateVectorIO\n\n , withTransformerAndArg\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad.Catch (\n Exception(..)\n , bracket\n , mask\n , onException\n , try\n , bracketOnError\n )\nimport Control.Monad (liftM, mapM_, when)\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Default (Default(..))\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types (CDouble(..), CInt(..), CUInt(..), CChar(..))\nimport Foreign.Marshal.Utils (fromBool)\nimport Foreign.ForeignPtr (newForeignPtr)\nimport Foreign.Ptr (\n Ptr\n , FunPtr\n , nullPtr\n , castPtr\n , nullFunPtr\n , plusPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.Types\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLProgress#}\n{#import GDAL.Internal.OGR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.GDAL#}\n\n#include \"gdal_alg.h\"\n#include \"contourwriter.h\"\n\ndata GDALAlgorithmException\n = RasterizeStopped\n | CreateGridStopped\n | ComputeProximityStopped\n | NullTransformer !Text\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALAlgorithmException where\n rnf a = a `seq` ()\n\ninstance Exception GDALAlgorithmException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\nclass Transformer t where\n transformerFun :: t s -> TransformerFun t s\n createTransformerArg :: t s -> IO (Ptr (t s))\n destroyTransformerArg :: Ptr (t s) -> IO ()\n setGeotransform :: Geotransform -> Ptr (t s) -> IO ()\n\n destroyTransformerArg p =\n when (p\/=nullPtr) ({# call unsafe GDALDestroyTransformer as ^#} (castPtr p))\n\ndata SomeTransformer s\n = forall t. Transformer t => SomeTransformer (t s)\n | DefaultTransformer\n\ninstance Default (SomeTransformer s) where\n def = DefaultTransformer\n\nwithTransformerAndArg\n :: SomeTransformer s\n -> Maybe Geotransform\n -> (TransformerFunPtr -> Ptr () -> IO c)\n -> IO c\nwithTransformerAndArg DefaultTransformer _ act = act nullFunPtr nullPtr\nwithTransformerAndArg (SomeTransformer t) mGt act =\n mask $ \\restore -> do\n arg <- createTransformerArg t\n case mGt of\n Just gt -> setGeotransform gt arg\n Nothing -> return ()\n -- Assumes arg will be destroyed by whoever takes it if not errors occur\n restore (act (getTransformerFunPtr (transformerFun t)) (castPtr arg))\n `onException` destroyTransformerArg arg\n\n\nnewtype TransformerFun (t :: * -> *) s\n = TransformerFun {getTransformerFunPtr :: TransformerFunPtr}\n\n{#pointer GDALTransformerFunc as TransformerFunPtr #}\n\n\n\n-- ############################################################################\n-- GenImgProjTransformer\n-- ############################################################################\n\ndata GenImgProjTransformer s =\n GenImgProjTransformer {\n giptSrcDs :: Maybe (RODataset s)\n , giptDstDs :: Maybe (RWDataset s)\n , giptSrcSrs :: Maybe SpatialReference\n , giptDstSrs :: Maybe SpatialReference\n , giptUseGCP :: Bool\n , giptMaxError :: Double\n , giptOrder :: Int\n }\n\ninstance Default (GenImgProjTransformer s) where\n def = GenImgProjTransformer {\n giptSrcDs = Nothing\n , giptDstDs = Nothing\n , giptSrcSrs = Nothing\n , giptDstSrs = Nothing\n , giptUseGCP = True\n , giptMaxError = 1\n , giptOrder = 0\n }\n\ncheckCreateTransformer :: Text -> IO (Ptr ()) -> IO (Ptr ())\ncheckCreateTransformer msg = checkGDALCall checkit\n where\n checkit e p\n | p==nullPtr = Just (NullTransformer (maybe msg gdalErrMsg e))\n | otherwise = Nothing\n\ninstance Transformer GenImgProjTransformer where\n transformerFun _ = c_GDALGenImgProjTransform\n setGeotransform = setGenImgProjTransfomerGeotransform\n createTransformerArg GenImgProjTransformer{..} =\n liftM castPtr $\n checkCreateTransformer \"GenImgProjTransformer\" $\n withMaybeSRAsCString giptSrcSrs $ \\sSr ->\n withMaybeSRAsCString giptDstSrs $ \\dSr ->\n {#call unsafe CreateGenImgProjTransformer as ^#}\n (maybe nullDatasetH unDataset giptSrcDs)\n sSr\n (maybe nullDatasetH unDataset giptDstDs)\n dSr\n (fromBool giptUseGCP)\n (realToFrac giptMaxError)\n (fromIntegral giptOrder)\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform :: TransformerFun GenImgProjTransformer s\n\n\n-- ############################################################################\n-- GenImgProjTransformer2\n-- ############################################################################\n\ndata GenImgProjTransformer2 s =\n GenImgProjTransformer2 {\n gipt2SrcDs :: Maybe (RODataset s)\n , gipt2DstDs :: Maybe (RWDataset s)\n , gipt2Options :: OptionList\n }\n\ninstance Default (GenImgProjTransformer2 s) where\n def = GenImgProjTransformer2 {\n gipt2SrcDs = Nothing\n , gipt2DstDs = Nothing\n , gipt2Options = []\n }\n\ninstance Transformer GenImgProjTransformer2 where\n transformerFun _ = c_GDALGenImgProjTransform2\n setGeotransform = setGenImgProjTransfomerGeotransform\n createTransformerArg GenImgProjTransformer2{..} =\n liftM castPtr $\n checkCreateTransformer \"GenImgProjTransformer2\" $\n withOptionList gipt2Options $ \\opts ->\n {#call unsafe CreateGenImgProjTransformer2 as ^#}\n (maybe nullDatasetH unDataset gipt2SrcDs)\n (maybe nullDatasetH unDataset gipt2DstDs)\n opts\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform2 :: TransformerFun GenImgProjTransformer2 s\n\n-- ############################################################################\n-- GenImgProjTransformer3\n-- ############################################################################\n\ndata GenImgProjTransformer3 s =\n GenImgProjTransformer3 {\n gipt3SrcSrs :: Maybe SpatialReference\n , gipt3DstSrs :: Maybe SpatialReference\n , gipt3SrcGt :: Maybe Geotransform\n , gipt3DstGt :: Maybe Geotransform\n }\n\ninstance Default (GenImgProjTransformer3 s) where\n def = GenImgProjTransformer3 {\n gipt3SrcSrs = Nothing\n , gipt3DstSrs = Nothing\n , gipt3SrcGt = Nothing\n , gipt3DstGt = Nothing\n }\n\ninstance Transformer GenImgProjTransformer3 where\n transformerFun _ = c_GDALGenImgProjTransform3\n setGeotransform = setGenImgProjTransfomerGeotransform\n createTransformerArg GenImgProjTransformer3{..} =\n liftM castPtr $\n checkCreateTransformer \"GenImgProjTransformer3\" $\n withMaybeSRAsCString gipt3SrcSrs $ \\sSr ->\n withMaybeSRAsCString gipt3DstSrs $ \\dSr ->\n withMaybeGeotransformPtr gipt3SrcGt $ \\sGt ->\n withMaybeGeotransformPtr gipt3DstGt $ \\dGt ->\n {#call unsafe CreateGenImgProjTransformer3 as ^#}\n sSr (castPtr sGt) dSr (castPtr dGt)\n\nsetGenImgProjTransfomerGeotransform :: Geotransform -> Ptr a -> IO ()\nsetGenImgProjTransfomerGeotransform geotransform pArg =\n with geotransform $ \\gt ->\n {#call unsafe GDALSetGenImgProjTransformerDstGeoTransform as ^#}\n (castPtr pArg) (castPtr gt)\n\n\nwithMaybeGeotransformPtr\n :: Maybe Geotransform -> (Ptr Geotransform -> IO a) -> IO a\nwithMaybeGeotransformPtr Nothing f = f nullPtr\nwithMaybeGeotransformPtr (Just g) f = alloca $ \\gp -> poke gp g >> f gp\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform3 :: TransformerFun GenImgProjTransformer3 s\n\n-- ############################################################################\n-- GDALRasterizeLayersBuf\n-- ############################################################################\n\nrasterizeLayersBuf\n :: forall s l a b. GDALType a\n => GDAL s [ROLayer s l b]\n -> SomeTransformer s\n -> a\n -> a\n -> OptionList\n -> Maybe ProgressFun\n -> SpatialReference\n -> Size\n -> Geotransform\n -> OGR s l (U.Vector (Value a))\nrasterizeLayersBuf getLayers mTransformer nodataValue\n burnValue options progressFun\n srs size geotransform =\n bracket (liftOGR getLayers) (mapM_ closeLayer) $ \\layers ->\n liftIO $\n withProgressFun RasterizeStopped progressFun $ \\pFun ->\n withArrayLen (map unLayer layers) $ \\len lPtrPtr ->\n withMaybeSRAsCString (Just srs) $ \\srsPtr ->\n withOptionList options $ \\opts ->\n withTransformerAndArg mTransformer (Just geotransform) $ \\trans tArg ->\n with geotransform $ \\gt -> do\n vec <- Stm.replicate (sizeLen size) nodataValue\n Stm.unsafeWith vec $ \\vecPtr ->\n checkCPLError \"RasterizeLayersBuf\" $\n {#call GDALRasterizeLayersBuf as ^#}\n (castPtr vecPtr) nx ny dt 0 0 (fromIntegral len)\n lPtrPtr srsPtr (castPtr gt) trans\n tArg bValue opts pFun nullPtr\n liftM (stToUValue . St.map toValue) (St.unsafeFreeze vec)\n where\n toValue v = if toCDouble v == ndValue then NoData else Value v\n dt = fromEnumC (dataType (Proxy :: Proxy a))\n bValue = toCDouble burnValue\n ndValue = toCDouble nodataValue\n XY nx ny = fmap fromIntegral size\n\n\n-- ############################################################################\n-- GDALCreateGrid\n-- ############################################################################\n\n{# enum GDALGridAlgorithm as GridAlgorithmEnum {}\n deriving (Eq,Read,Show,Bounded) #}\n\n\nclass (Storable a, Typeable a, Default a, Show a) => GridAlgorithm a where\n gridAlgorithm :: a -> GridAlgorithmEnum\n setNodata :: Ptr a -> CDouble -> IO ()\n\ncreateGridIO\n :: forall a opts. (GDALType a, GridAlgorithm opts)\n => opts\n -> a\n -> Maybe ProgressFun\n -> St.Vector (GridPoint a)\n -> EnvelopeReal\n -> Size\n -> IO (U.Vector (Value a))\ncreateGridIO options noDataVal progressFun points envelope size =\n withProgressFun CreateGridStopped progressFun $ \\pFun ->\n withErrorHandler $\n with options $ \\opts -> do\n setNodata opts ndValue\n xs <- St.unsafeThaw (St.unsafeCast (St.map (px . gpXY) points))\n ys <- St.unsafeThaw (St.unsafeCast (St.map (py . gpXY) points))\n zs <- St.unsafeThaw (St.map (toCDouble . gpZ) points)\n out <- Stm.unsafeNew (sizeLen size)\n checkCPLError \"GDALGridCreate\" $\n Stm.unsafeWith xs $ \\pXs ->\n Stm.unsafeWith ys $ \\pYs ->\n Stm.unsafeWith zs $ \\pZs ->\n Stm.unsafeWith out $ \\pOut ->\n {#call GDALGridCreate as ^#}\n (fromEnumC (gridAlgorithm options))\n (castPtr opts)\n (fromIntegral (St.length points))\n pXs\n pYs\n pZs\n x0\n x1\n y0\n y1\n nx\n ny\n gtype\n (castPtr pOut)\n pFun\n nullPtr\n liftM (stToUValue . St.map toValue) (St.unsafeFreeze out)\n where\n toValue v\n | toCDouble v == ndValue = NoData\n | otherwise = Value v\n ndValue = toCDouble noDataVal\n XY nx ny = fmap fromIntegral size\n Envelope (XY x0 y0) (XY x1 y1) = fmap realToFrac envelope\n gtype = fromEnumC (dataType (Proxy :: Proxy a))\n\n\ncreateGrid\n :: forall a opts. (GDALType a, GridAlgorithm opts)\n => opts\n -> a\n -> St.Vector (GridPoint a)\n -> EnvelopeReal\n -> Size\n -> Either GDALException (U.Vector (Value a))\ncreateGrid options noDataVal points envelope =\n unsafePerformIO .\n try .\n createGridIO options noDataVal Nothing points envelope\n\n\ndata GridPoint a =\n GP {\n gpXY :: {-# UNPACK #-} !(XY Double)\n , gpZ :: {-# UNPACK #-} !a\n } deriving (Eq, Show, Read)\n\ninstance Storable a => Storable (GridPoint a) where\n sizeOf _ = sizeOf (undefined::XY Double) + sizeOf (undefined::Double)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined::Double)\n {-# INLINE alignment #-}\n poke ptr (GP xy z) = poke ptr' xy >> poke (castPtr (ptr' `plusPtr` 1)) z\n where ptr' = castPtr ptr\n {-# INLINE poke #-}\n peek ptr = GP <$> peek ptr'\n <*> peek (castPtr (ptr' `plusPtr` 1))\n where ptr' = castPtr ptr\n {-# INLINE peek #-}\n\n-- ############################################################################\n-- GridInverseDistanceToAPower\n-- ############################################################################\n\ndata GridInverseDistanceToAPower =\n GridInverseDistanceToAPower {\n idpPower :: !Double\n , idpSmoothing :: !Double\n , idpAnisotropyRatio :: !Double\n , idpAnisotropyAngle :: !Double\n , idpRadius1 :: !Double\n , idpRadius2 :: !Double\n , idpAngle :: !Double\n , idpMinPoints :: !Int\n , idpMaxPoints :: !Int\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridInverseDistanceToAPower where\n gridAlgorithm = const GGA_InverseDistanceToAPower\n setNodata = {#set GridInverseDistanceToAPowerOptions->dfNoDataValue#}\n\ninstance Default GridInverseDistanceToAPower where\n def = GridInverseDistanceToAPower {\n idpPower = 2\n , idpSmoothing = 0\n , idpAnisotropyRatio = 0\n , idpAnisotropyAngle = 0\n , idpRadius1 = 0\n , idpRadius2 = 0\n , idpAngle = 0\n , idpMinPoints = 0\n , idpMaxPoints = 0\n }\n\ninstance Storable GridInverseDistanceToAPower where\n sizeOf _ = {#sizeof GridInverseDistanceToAPowerOptions#}\n alignment _ = {#alignof GridInverseDistanceToAPowerOptions#}\n peek _ = error \"GridInverseDistanceToAPower: peek not implemented\"\n poke p GridInverseDistanceToAPower{..}= do\n {#set GridInverseDistanceToAPowerOptions->dfPower#} p\n (realToFrac idpPower)\n {#set GridInverseDistanceToAPowerOptions->dfSmoothing#} p\n (realToFrac idpSmoothing)\n {#set GridInverseDistanceToAPowerOptions->dfAnisotropyRatio#} p\n (realToFrac idpAnisotropyRatio)\n {#set GridInverseDistanceToAPowerOptions->dfAnisotropyAngle#} p\n (realToFrac idpAnisotropyAngle)\n {#set GridInverseDistanceToAPowerOptions->dfRadius1#} p\n (realToFrac idpRadius1)\n {#set GridInverseDistanceToAPowerOptions->dfRadius2#} p\n (realToFrac idpRadius2)\n {#set GridInverseDistanceToAPowerOptions->dfAngle#} p\n (realToFrac idpAngle)\n {#set GridInverseDistanceToAPowerOptions->nMinPoints#} p\n (fromIntegral idpMinPoints)\n {#set GridInverseDistanceToAPowerOptions->nMaxPoints#} p\n (fromIntegral idpMaxPoints)\n\n-- ############################################################################\n-- GridMovingAverage\n-- ############################################################################\n\ndata GridMovingAverage =\n GridMovingAverage {\n maRadius1 :: !Double\n , maRadius2 :: !Double\n , maAngle :: !Double\n , maMinPoints :: !Int\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridMovingAverage where\n gridAlgorithm = const GGA_MovingAverage\n setNodata = {#set GridMovingAverageOptions->dfNoDataValue#}\n\ninstance Default GridMovingAverage where\n def = GridMovingAverage {\n maRadius1 = 0\n , maRadius2 = 0\n , maAngle = 0\n , maMinPoints = 0\n }\n\ninstance Storable GridMovingAverage where\n sizeOf _ = {#sizeof GridMovingAverageOptions#}\n alignment _ = {#alignof GridMovingAverageOptions#}\n peek _ = error \"GridMovingAverage: peek not implemented\"\n poke p GridMovingAverage{..}= do\n {#set GridMovingAverageOptions->dfRadius1#} p\n (realToFrac maRadius1)\n {#set GridMovingAverageOptions->dfRadius2#} p\n (realToFrac maRadius2)\n {#set GridMovingAverageOptions->dfAngle#} p\n (realToFrac maAngle)\n {#set GridMovingAverageOptions->nMinPoints#} p\n (fromIntegral maMinPoints)\n\n-- ############################################################################\n-- GridNearestNeighbor\n-- ############################################################################\n\ndata GridNearestNeighbor =\n GridNearestNeighbor {\n nnRadius1 :: !Double\n , nnRadius2 :: !Double\n , nnAngle :: !Double\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridNearestNeighbor where\n gridAlgorithm = const GGA_NearestNeighbor\n setNodata = {#set GridNearestNeighborOptions->dfNoDataValue#}\n\ninstance Default GridNearestNeighbor where\n def = GridNearestNeighbor {\n nnRadius1 = 0\n , nnRadius2 = 0\n , nnAngle = 0\n }\n\ninstance Storable GridNearestNeighbor where\n sizeOf _ = {#sizeof GridNearestNeighborOptions#}\n alignment _ = {#alignof GridNearestNeighborOptions#}\n peek _ = error \"GridNearestNeighbor: peek not implemented\"\n poke p GridNearestNeighbor{..}= do\n {#set GridNearestNeighborOptions->dfRadius1#} p\n (realToFrac nnRadius1)\n {#set GridNearestNeighborOptions->dfRadius2#} p\n (realToFrac nnRadius2)\n {#set GridNearestNeighborOptions->dfAngle#} p\n (realToFrac nnAngle)\n\n-- ############################################################################\n-- GridDataMetrics\n-- ############################################################################\n\ndata MetricType\n = MetricMinimum\n | MetricMaximum\n | MetricRange\n | MetricCount\n | MetricAverageDistance\n | MetricAverageDistancePts\n deriving (Eq, Read, Show, Bounded)\n\n\ninstance Default MetricType where\n def = MetricCount\n\n\ndata GridDataMetrics =\n GridDataMetrics {\n dmRadius1 :: !Double\n , dmRadius2 :: !Double\n , dmAngle :: !Double\n , dmMinPoints :: !Int\n , dmType :: !MetricType\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridDataMetrics where\n gridAlgorithm = mtToGGA . dmType\n where\n mtToGGA MetricMinimum = GGA_MetricMinimum\n mtToGGA MetricMaximum = GGA_MetricMaximum\n mtToGGA MetricRange = GGA_MetricRange\n mtToGGA MetricCount = GGA_MetricCount\n mtToGGA MetricAverageDistance = GGA_MetricAverageDistance\n mtToGGA MetricAverageDistancePts = GGA_MetricAverageDistancePts\n setNodata = {#set GridDataMetricsOptions->dfNoDataValue#}\n\ninstance Default GridDataMetrics where\n def = GridDataMetrics {\n dmRadius1 = 0\n , dmRadius2 = 0\n , dmAngle = 0\n , dmMinPoints = 0\n , dmType = def\n }\n\ninstance Storable GridDataMetrics where\n sizeOf _ = {#sizeof GridDataMetricsOptions#}\n alignment _ = {#alignof GridDataMetricsOptions#}\n peek _ = error \"GridDataMetrics: peek not implemented\"\n poke p GridDataMetrics{..}= do\n {#set GridDataMetricsOptions->dfRadius1#} p\n (realToFrac dmRadius1)\n {#set GridDataMetricsOptions->dfRadius2#} p\n (realToFrac dmRadius2)\n {#set GridDataMetricsOptions->dfAngle#} p\n (realToFrac dmAngle)\n {#set GridDataMetricsOptions->nMinPoints#} p\n (fromIntegral dmMinPoints)\n\n-- ############################################################################\n-- ComputeProximity\n-- ############################################################################\n\ncomputeProximity\n :: Band s t\n -> RWBand s\n -> OptionList\n -> Maybe ProgressFun\n -> GDAL s ()\ncomputeProximity srcBand prxBand options progressFun =\n liftIO $\n withOptionList options $ \\opts ->\n withProgressFun ComputeProximityStopped progressFun $ \\pFun ->\n checkCPLError \"computeProximity\" $\n {#call GDALComputeProximity as ^#}\n (unBand srcBand)\n (unBand prxBand)\n opts\n pFun\n nullPtr\n\n-- ############################################################################\n-- contourVector\n-- ############################################################################\n\ndata Contour =\n Contour {\n cLevel :: {-# UNPACK #-} !Double\n , cPoints :: {-# UNPACK #-} !(St.Vector (XY Double))\n } deriving (Eq, Show)\n\n{#pointer contour_list as ContourList #}\n{#pointer *Contour as CContour #}\n{#pointer *Point->XYDouble #}\n\ntype XYDouble = XY Double\n\ncontourGenerateVectorIO\n :: Double\n -> Double\n -> Maybe Double\n -> Size\n -> (St.Vector Double)\n -> IO [Contour]\ncontourGenerateVectorIO _ _ _ size vector\n | St.length vector \/= sizeLen size =\n throwBindingException (InvalidRasterSize size)\ncontourGenerateVectorIO interval base nodataVal (XY nx ny) vector =\n withErrorHandler $\n with nullPtr $ \\pList ->\n bracket (alloc pList) (free pList) $ \\generator -> do\n St.forM_ (St.enumFromStepN 0 nx (ny-1)) $ \\offset ->\n St.unsafeWith (St.slice offset nx (St.unsafeCast vector)) $\n checkCPLError \"FeedLine\" . {#call unsafe GDAL_CG_FeedLine as ^#} generator\n getContours pList\n where\n alloc pList =\n {#call unsafe GDAL_CG_Create as ^#}\n (fromIntegral nx)\n (fromIntegral ny)\n (fromBool (isJust nodataVal))\n (maybe 0 realToFrac nodataVal)\n (realToFrac interval)\n (realToFrac base)\n c_contourWriter\n (castPtr pList)\n\n free pList gen = do\n freeContourList pList\n {#call unsafe GDAL_CG_Destroy as ^#} gen\n\n getContours pList =\n bracket\n ({#call unsafe pop_contour#} pList)\n {#call unsafe destroy_contour#} $ \\c ->\n if c==nullPtr\n then return []\n else do\n fp <- bracketOnError\n ({#get Contour->points#} c)\n {#call unsafe destroy_points#}\n (newForeignPtr c_destroyPoints)\n nPoints <- liftM fromIntegral ({#get Contour->nPoints#} c)\n contour <- Contour <$> liftM realToFrac ({#get Contour->level#} c)\n <*> pure (St.unsafeFromForeignPtr0 fp nPoints)\n liftM (contour:) (getContours pList)\n\n freeContourList pList = do\n p <- {#call unsafe pop_contour#} pList\n if p==nullPtr\n then return ()\n else do {#get Contour->points#} p >>= {#call unsafe destroy_points#}\n {#call unsafe destroy_contour #} p\n freeContourList pList\n\n\n\ncontourGenerateVector\n :: Double\n -> Double\n -> Maybe Double\n -> Size\n -> (St.Vector Double)\n -> Either GDALException [Contour]\ncontourGenerateVector interval base nodataVal size =\n unsafePerformIO . try . contourGenerateVectorIO interval base nodataVal size\n\ntype CContourWriter =\n CDouble -> CInt -> Ptr CDouble -> Ptr CDouble -> Ptr () -> IO CInt\n\nforeign import ccall \"contourwriter.h &hs_contour_writer\"\n c_contourWriter :: FunPtr CContourWriter\n\nforeign import ccall \"contourwriter.h &destroy_points\"\n c_destroyPoints :: FunPtr (Ptr XYDouble -> IO ())\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ExistentialQuantification #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE BangPatterns #-}\n\nmodule GDAL.Internal.Algorithms (\n GenImgProjTransformer (..)\n , GenImgProjTransformer2 (..)\n , GenImgProjTransformer3 (..)\n , SomeTransformer (..)\n\n , Contour (..)\n\n , GridPoint (..)\n , GridAlgorithm (..)\n , GridInverseDistanceToAPower (..)\n , GridMovingAverage (..)\n , GridNearestNeighbor (..)\n , GridDataMetrics (..)\n , MetricType (..)\n\n , GridAlgorithmEnum (..)\n\n , rasterizeLayersBuf\n , createGrid\n , createGridIO\n , computeProximity\n , contourGenerateVector\n , contourGenerateVectorIO\n\n , withTransformerAndArg\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Monad.Catch (\n Exception(..)\n , bracket\n , mask\n , onException\n , try\n , bracketOnError\n )\nimport Control.Monad (liftM, mapM_, when)\nimport Control.Monad.IO.Class (liftIO)\nimport Data.Default (Default(..))\nimport Data.Maybe (isJust)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Unboxed as U\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\n\nimport Foreign.C.Types (CDouble(..), CInt(..), CUInt(..), CChar(..))\nimport Foreign.Marshal.Utils (fromBool)\nimport Foreign.ForeignPtr (newForeignPtr)\nimport Foreign.Ptr (\n Ptr\n , FunPtr\n , nullPtr\n , castPtr\n , nullFunPtr\n , plusPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Storable (Storable(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Util (fromEnumC)\nimport GDAL.Internal.Types\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLProgress#}\n{#import GDAL.Internal.OGR#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.GDAL#}\n\n#include \"gdal_alg.h\"\n#include \"contourwriter.h\"\n\ndata GDALAlgorithmException\n = RasterizeStopped\n | CreateGridStopped\n | ComputeProximityStopped\n | NullTransformer !Text\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALAlgorithmException where\n rnf a = a `seq` ()\n\ninstance Exception GDALAlgorithmException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\nclass Transformer t where\n transformerFun :: t s -> TransformerFun t s\n createTransformerArg :: t s -> IO (Ptr (t s))\n destroyTransformerArg :: Ptr (t s) -> IO ()\n setGeotransform :: Geotransform -> Ptr (t s) -> IO ()\n\n destroyTransformerArg p =\n when (p\/=nullPtr) ({# call unsafe GDALDestroyTransformer as ^#} (castPtr p))\n\ndata SomeTransformer s\n = forall t. Transformer t => SomeTransformer (t s)\n | DefaultTransformer\n\ninstance Default (SomeTransformer s) where\n def = DefaultTransformer\n\nwithTransformerAndArg\n :: SomeTransformer s\n -> Maybe Geotransform\n -> (TransformerFunPtr -> Ptr () -> IO c)\n -> IO c\nwithTransformerAndArg DefaultTransformer _ act = act nullFunPtr nullPtr\nwithTransformerAndArg (SomeTransformer t) mGt act =\n mask $ \\restore -> do\n arg <- createTransformerArg t\n case mGt of\n Just gt -> setGeotransform gt arg\n Nothing -> return ()\n -- Assumes arg will be destroyed by whoever takes it if not errors occur\n restore (act (getTransformerFunPtr (transformerFun t)) (castPtr arg))\n `onException` destroyTransformerArg arg\n\n\nnewtype TransformerFun (t :: * -> *) s\n = TransformerFun {getTransformerFunPtr :: TransformerFunPtr}\n\n{#pointer GDALTransformerFunc as TransformerFunPtr #}\n\n\n\n-- ############################################################################\n-- GenImgProjTransformer\n-- ############################################################################\n\ndata GenImgProjTransformer s =\n GenImgProjTransformer {\n giptSrcDs :: Maybe (RODataset s)\n , giptDstDs :: Maybe (RWDataset s)\n , giptSrcSrs :: Maybe SpatialReference\n , giptDstSrs :: Maybe SpatialReference\n , giptUseGCP :: Bool\n , giptMaxError :: Double\n , giptOrder :: Int\n }\n\ninstance Default (GenImgProjTransformer s) where\n def = GenImgProjTransformer {\n giptSrcDs = Nothing\n , giptDstDs = Nothing\n , giptSrcSrs = Nothing\n , giptDstSrs = Nothing\n , giptUseGCP = True\n , giptMaxError = 1\n , giptOrder = 0\n }\n\ncheckCreateTransformer :: Text -> IO (Ptr ()) -> IO (Ptr ())\ncheckCreateTransformer msg = checkGDALCall checkit\n where\n checkit e p\n | p==nullPtr = Just (NullTransformer (maybe msg gdalErrMsg e))\n | otherwise = Nothing\n\ninstance Transformer GenImgProjTransformer where\n transformerFun _ = c_GDALGenImgProjTransform\n setGeotransform = setGenImgProjTransfomerGeotransform\n createTransformerArg GenImgProjTransformer{..} =\n liftM castPtr $\n checkCreateTransformer \"GenImgProjTransformer\" $\n withMaybeSRAsCString giptSrcSrs $ \\sSr ->\n withMaybeSRAsCString giptDstSrs $ \\dSr ->\n {#call unsafe CreateGenImgProjTransformer as ^#}\n (maybe nullDatasetH unDataset giptSrcDs)\n sSr\n (maybe nullDatasetH unDataset giptDstDs)\n dSr\n (fromBool giptUseGCP)\n (realToFrac giptMaxError)\n (fromIntegral giptOrder)\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform :: TransformerFun GenImgProjTransformer s\n\n\n-- ############################################################################\n-- GenImgProjTransformer2\n-- ############################################################################\n\ndata GenImgProjTransformer2 s =\n GenImgProjTransformer2 {\n gipt2SrcDs :: Maybe (RODataset s)\n , gipt2DstDs :: Maybe (RWDataset s)\n , gipt2Options :: OptionList\n }\n\ninstance Default (GenImgProjTransformer2 s) where\n def = GenImgProjTransformer2 {\n gipt2SrcDs = Nothing\n , gipt2DstDs = Nothing\n , gipt2Options = []\n }\n\ninstance Transformer GenImgProjTransformer2 where\n transformerFun _ = c_GDALGenImgProjTransform2\n setGeotransform = setGenImgProjTransfomerGeotransform\n createTransformerArg GenImgProjTransformer2{..} =\n liftM castPtr $\n checkCreateTransformer \"GenImgProjTransformer2\" $\n withOptionList gipt2Options $ \\opts ->\n {#call unsafe CreateGenImgProjTransformer2 as ^#}\n (maybe nullDatasetH unDataset gipt2SrcDs)\n (maybe nullDatasetH unDataset gipt2DstDs)\n opts\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform2 :: TransformerFun GenImgProjTransformer2 s\n\n-- ############################################################################\n-- GenImgProjTransformer3\n-- ############################################################################\n\ndata GenImgProjTransformer3 s =\n GenImgProjTransformer3 {\n gipt3SrcSrs :: Maybe SpatialReference\n , gipt3DstSrs :: Maybe SpatialReference\n , gipt3SrcGt :: Maybe Geotransform\n , gipt3DstGt :: Maybe Geotransform\n }\n\ninstance Default (GenImgProjTransformer3 s) where\n def = GenImgProjTransformer3 {\n gipt3SrcSrs = Nothing\n , gipt3DstSrs = Nothing\n , gipt3SrcGt = Nothing\n , gipt3DstGt = Nothing\n }\n\ninstance Transformer GenImgProjTransformer3 where\n transformerFun _ = c_GDALGenImgProjTransform3\n setGeotransform = setGenImgProjTransfomerGeotransform\n createTransformerArg GenImgProjTransformer3{..} =\n liftM castPtr $\n checkCreateTransformer \"GenImgProjTransformer3\" $\n withMaybeSRAsCString gipt3SrcSrs $ \\sSr ->\n withMaybeSRAsCString gipt3DstSrs $ \\dSr ->\n withMaybeGeotransformPtr gipt3SrcGt $ \\sGt ->\n withMaybeGeotransformPtr gipt3DstGt $ \\dGt ->\n {#call unsafe CreateGenImgProjTransformer3 as ^#}\n sSr (castPtr sGt) dSr (castPtr dGt)\n\nsetGenImgProjTransfomerGeotransform :: Geotransform -> Ptr a -> IO ()\nsetGenImgProjTransfomerGeotransform geotransform pArg =\n with geotransform $ \\gt ->\n {#call unsafe GDALSetGenImgProjTransformerDstGeoTransform as ^#}\n (castPtr pArg) (castPtr gt)\n\n\nwithMaybeGeotransformPtr\n :: Maybe Geotransform -> (Ptr Geotransform -> IO a) -> IO a\nwithMaybeGeotransformPtr Nothing f = f nullPtr\nwithMaybeGeotransformPtr (Just g) f = alloca $ \\gp -> poke gp g >> f gp\n\nforeign import ccall \"gdal_alg.h &GDALGenImgProjTransform\"\n c_GDALGenImgProjTransform3 :: TransformerFun GenImgProjTransformer3 s\n\n-- ############################################################################\n-- GDALRasterizeLayersBuf\n-- ############################################################################\n\nrasterizeLayersBuf\n :: forall s l a b. GDALType a\n => GDAL s [ROLayer s l b]\n -> SomeTransformer s\n -> a\n -> a\n -> OptionList\n -> Maybe ProgressFun\n -> SpatialReference\n -> Size\n -> Geotransform\n -> OGR s l (U.Vector (Value a))\nrasterizeLayersBuf getLayers mTransformer nodataValue\n burnValue options progressFun\n srs size geotransform =\n bracket (liftOGR getLayers) (mapM_ closeLayer) $ \\layers ->\n liftIO $\n withProgressFun RasterizeStopped progressFun $ \\pFun ->\n withArrayLen (map unLayer layers) $ \\len lPtrPtr ->\n withMaybeSRAsCString (Just srs) $ \\srsPtr ->\n withOptionList options $ \\opts ->\n withTransformerAndArg mTransformer (Just geotransform) $ \\trans tArg ->\n with geotransform $ \\gt -> do\n vec <- Stm.replicate (sizeLen size) nodataValue\n Stm.unsafeWith vec $ \\vecPtr ->\n checkCPLError \"RasterizeLayersBuf\" $\n {#call GDALRasterizeLayersBuf as ^#}\n (castPtr vecPtr) nx ny dt 0 0 (fromIntegral len)\n lPtrPtr srsPtr (castPtr gt) trans\n tArg bValue opts pFun nullPtr\n liftM (stToUValue . St.map toValue) (St.unsafeFreeze vec)\n where\n toValue v = if toCDouble v == ndValue then NoData else Value v\n dt = fromEnumC (dataType (Proxy :: Proxy a))\n bValue = toCDouble burnValue\n ndValue = toCDouble nodataValue\n XY nx ny = fmap fromIntegral size\n\n\n-- ############################################################################\n-- GDALCreateGrid\n-- ############################################################################\n\n{# enum GDALGridAlgorithm as GridAlgorithmEnum {}\n deriving (Eq,Read,Show,Bounded) #}\n\n\nclass (Storable a, Typeable a, Default a, Show a) => GridAlgorithm a where\n gridAlgorithm :: a -> GridAlgorithmEnum\n setNodata :: Ptr a -> CDouble -> IO ()\n\ncreateGridIO\n :: forall a opts. (GDALType a, GridAlgorithm opts)\n => opts\n -> a\n -> Maybe ProgressFun\n -> St.Vector (GridPoint a)\n -> EnvelopeReal\n -> Size\n -> IO (U.Vector (Value a))\ncreateGridIO options noDataVal progressFun points envelope size =\n withProgressFun CreateGridStopped progressFun $ \\pFun ->\n withErrorHandler $\n with options $ \\opts -> do\n setNodata opts ndValue\n xs <- St.unsafeThaw (St.unsafeCast (St.map (px . gpXY) points))\n ys <- St.unsafeThaw (St.unsafeCast (St.map (py . gpXY) points))\n zs <- St.unsafeThaw (St.map (toCDouble . gpZ) points)\n out <- Stm.unsafeNew (sizeLen size)\n checkCPLError \"GDALGridCreate\" $\n Stm.unsafeWith xs $ \\pXs ->\n Stm.unsafeWith ys $ \\pYs ->\n Stm.unsafeWith zs $ \\pZs ->\n Stm.unsafeWith out $ \\pOut ->\n {#call GDALGridCreate as ^#}\n (fromEnumC (gridAlgorithm options))\n (castPtr opts)\n (fromIntegral (St.length points))\n pXs\n pYs\n pZs\n x0\n x1\n y0\n y1\n nx\n ny\n gtype\n (castPtr pOut)\n pFun\n nullPtr\n liftM (stToUValue . St.map toValue) (St.unsafeFreeze out)\n where\n toValue v\n | toCDouble v == ndValue = NoData\n | otherwise = Value v\n ndValue = toCDouble noDataVal\n XY nx ny = fmap fromIntegral size\n Envelope (XY x0 y0) (XY x1 y1) = fmap realToFrac envelope\n gtype = fromEnumC (dataType (Proxy :: Proxy a))\n\n\ncreateGrid\n :: forall a opts. (GDALType a, GridAlgorithm opts)\n => opts\n -> a\n -> St.Vector (GridPoint a)\n -> EnvelopeReal\n -> Size\n -> Either GDALException (U.Vector (Value a))\ncreateGrid options noDataVal points envelope =\n unsafePerformIO .\n try .\n createGridIO options noDataVal Nothing points envelope\n\n\ndata GridPoint a =\n GP {\n gpXY :: {-# UNPACK #-} !(XY Double)\n , gpZ :: {-# UNPACK #-} !a\n } deriving (Eq, Show, Read)\n\ninstance Storable a => Storable (GridPoint a) where\n sizeOf _ = sizeOf (undefined::XY Double) + sizeOf (undefined::Double)\n {-# INLINE sizeOf #-}\n alignment _ = alignment (undefined::Double)\n {-# INLINE alignment #-}\n poke ptr (GP xy z) = poke ptr' xy >> poke (castPtr (ptr' `plusPtr` 1)) z\n where ptr' = castPtr ptr\n {-# INLINE poke #-}\n peek ptr = GP <$> peek ptr'\n <*> peek (castPtr (ptr' `plusPtr` 1))\n where ptr' = castPtr ptr\n {-# INLINE peek #-}\n\n-- ############################################################################\n-- GridInverseDistanceToAPower\n-- ############################################################################\n\ndata GridInverseDistanceToAPower =\n GridInverseDistanceToAPower {\n idpPower :: !Double\n , idpSmoothing :: !Double\n , idpAnisotropyRatio :: !Double\n , idpAnisotropyAngle :: !Double\n , idpRadius1 :: !Double\n , idpRadius2 :: !Double\n , idpAngle :: !Double\n , idpMinPoints :: !Int\n , idpMaxPoints :: !Int\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridInverseDistanceToAPower where\n gridAlgorithm = const GGA_InverseDistanceToAPower\n setNodata = {#set GridInverseDistanceToAPowerOptions->dfNoDataValue#}\n\ninstance Default GridInverseDistanceToAPower where\n def = GridInverseDistanceToAPower {\n idpPower = 2\n , idpSmoothing = 0\n , idpAnisotropyRatio = 0\n , idpAnisotropyAngle = 0\n , idpRadius1 = 0\n , idpRadius2 = 0\n , idpAngle = 0\n , idpMinPoints = 0\n , idpMaxPoints = 0\n }\n\ninstance Storable GridInverseDistanceToAPower where\n sizeOf _ = {#sizeof GridInverseDistanceToAPowerOptions#}\n alignment _ = {#alignof GridInverseDistanceToAPowerOptions#}\n peek _ = error \"GridInverseDistanceToAPower: peek not implemented\"\n poke p GridInverseDistanceToAPower{..}= do\n {#set GridInverseDistanceToAPowerOptions->dfPower#} p\n (realToFrac idpPower)\n {#set GridInverseDistanceToAPowerOptions->dfSmoothing#} p\n (realToFrac idpSmoothing)\n {#set GridInverseDistanceToAPowerOptions->dfAnisotropyRatio#} p\n (realToFrac idpAnisotropyRatio)\n {#set GridInverseDistanceToAPowerOptions->dfAnisotropyAngle#} p\n (realToFrac idpAnisotropyAngle)\n {#set GridInverseDistanceToAPowerOptions->dfRadius1#} p\n (realToFrac idpRadius1)\n {#set GridInverseDistanceToAPowerOptions->dfRadius2#} p\n (realToFrac idpRadius2)\n {#set GridInverseDistanceToAPowerOptions->dfAngle#} p\n (realToFrac idpAngle)\n {#set GridInverseDistanceToAPowerOptions->nMinPoints#} p\n (fromIntegral idpMinPoints)\n {#set GridInverseDistanceToAPowerOptions->nMaxPoints#} p\n (fromIntegral idpMaxPoints)\n\n-- ############################################################################\n-- GridMovingAverage\n-- ############################################################################\n\ndata GridMovingAverage =\n GridMovingAverage {\n maRadius1 :: !Double\n , maRadius2 :: !Double\n , maAngle :: !Double\n , maMinPoints :: !Int\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridMovingAverage where\n gridAlgorithm = const GGA_MovingAverage\n setNodata = {#set GridMovingAverageOptions->dfNoDataValue#}\n\ninstance Default GridMovingAverage where\n def = GridMovingAverage {\n maRadius1 = 0\n , maRadius2 = 0\n , maAngle = 0\n , maMinPoints = 0\n }\n\ninstance Storable GridMovingAverage where\n sizeOf _ = {#sizeof GridMovingAverageOptions#}\n alignment _ = {#alignof GridMovingAverageOptions#}\n peek _ = error \"GridMovingAverage: peek not implemented\"\n poke p GridMovingAverage{..}= do\n {#set GridMovingAverageOptions->dfRadius1#} p\n (realToFrac maRadius1)\n {#set GridMovingAverageOptions->dfRadius2#} p\n (realToFrac maRadius2)\n {#set GridMovingAverageOptions->dfAngle#} p\n (realToFrac maAngle)\n {#set GridMovingAverageOptions->nMinPoints#} p\n (fromIntegral maMinPoints)\n\n-- ############################################################################\n-- GridNearestNeighbor\n-- ############################################################################\n\ndata GridNearestNeighbor =\n GridNearestNeighbor {\n nnRadius1 :: !Double\n , nnRadius2 :: !Double\n , nnAngle :: !Double\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridNearestNeighbor where\n gridAlgorithm = const GGA_NearestNeighbor\n setNodata = {#set GridNearestNeighborOptions->dfNoDataValue#}\n\ninstance Default GridNearestNeighbor where\n def = GridNearestNeighbor {\n nnRadius1 = 0\n , nnRadius2 = 0\n , nnAngle = 0\n }\n\ninstance Storable GridNearestNeighbor where\n sizeOf _ = {#sizeof GridNearestNeighborOptions#}\n alignment _ = {#alignof GridNearestNeighborOptions#}\n peek _ = error \"GridNearestNeighbor: peek not implemented\"\n poke p GridNearestNeighbor{..}= do\n {#set GridNearestNeighborOptions->dfRadius1#} p\n (realToFrac nnRadius1)\n {#set GridNearestNeighborOptions->dfRadius2#} p\n (realToFrac nnRadius2)\n {#set GridNearestNeighborOptions->dfAngle#} p\n (realToFrac nnAngle)\n\n-- ############################################################################\n-- GridDataMetrics\n-- ############################################################################\n\ndata MetricType\n = MetricMinimum\n | MetricMaximum\n | MetricRange\n | MetricCount\n | MetricAverageDistance\n | MetricAverageDistancePts\n deriving (Eq, Read, Show, Bounded)\n\n\ninstance Default MetricType where\n def = MetricCount\n\n\ndata GridDataMetrics =\n GridDataMetrics {\n dmRadius1 :: !Double\n , dmRadius2 :: !Double\n , dmAngle :: !Double\n , dmMinPoints :: !Int\n , dmType :: !MetricType\n } deriving (Eq, Show, Typeable)\n\ninstance GridAlgorithm GridDataMetrics where\n gridAlgorithm = mtToGGA . dmType\n where\n mtToGGA MetricMinimum = GGA_MetricMinimum\n mtToGGA MetricMaximum = GGA_MetricMaximum\n mtToGGA MetricRange = GGA_MetricRange\n mtToGGA MetricCount = GGA_MetricCount\n mtToGGA MetricAverageDistance = GGA_MetricAverageDistance\n mtToGGA MetricAverageDistancePts = GGA_MetricAverageDistancePts\n setNodata = {#set GridDataMetricsOptions->dfNoDataValue#}\n\ninstance Default GridDataMetrics where\n def = GridDataMetrics {\n dmRadius1 = 0\n , dmRadius2 = 0\n , dmAngle = 0\n , dmMinPoints = 0\n , dmType = def\n }\n\ninstance Storable GridDataMetrics where\n sizeOf _ = {#sizeof GridDataMetricsOptions#}\n alignment _ = {#alignof GridDataMetricsOptions#}\n peek _ = error \"GridDataMetrics: peek not implemented\"\n poke p GridDataMetrics{..}= do\n {#set GridDataMetricsOptions->dfRadius1#} p\n (realToFrac dmRadius1)\n {#set GridDataMetricsOptions->dfRadius2#} p\n (realToFrac dmRadius2)\n {#set GridDataMetricsOptions->dfAngle#} p\n (realToFrac dmAngle)\n {#set GridDataMetricsOptions->nMinPoints#} p\n (fromIntegral dmMinPoints)\n\n-- ############################################################################\n-- ComputeProximity\n-- ############################################################################\n\ncomputeProximity\n :: Band s t\n -> RWBand s\n -> OptionList\n -> Maybe ProgressFun\n -> GDAL s ()\ncomputeProximity srcBand prxBand options progressFun =\n liftIO $\n withOptionList options $ \\opts ->\n withProgressFun ComputeProximityStopped progressFun $ \\pFun ->\n checkCPLError \"computeProximity\" $\n {#call GDALComputeProximity as ^#}\n (unBand srcBand)\n (unBand prxBand)\n opts\n pFun\n nullPtr\n\n-- ############################################################################\n-- contourVector\n-- ############################################################################\n\ndata Contour =\n Contour {\n cLevel :: {-# UNPACK #-} !Double\n , cPoints :: {-# UNPACK #-} !(St.Vector (XY Double))\n } deriving (Eq, Show)\n\n{#pointer contour_list as ContourList #}\n{#pointer *Contour as CContour #}\n{#pointer *Point->XYDouble #}\n\ntype XYDouble = XY Double\n\ncontourGenerateVectorIO\n :: Double\n -> Double\n -> Maybe Double\n -> Size\n -> (St.Vector Double)\n -> IO [Contour]\ncontourGenerateVectorIO _ _ _ size vector\n | St.length vector \/= sizeLen size =\n throwBindingException (InvalidRasterSize size)\ncontourGenerateVectorIO interval base nodataVal (XY nx ny) vector =\n withErrorHandler $\n with nullPtr $ \\pList ->\n bracket (alloc pList) (free pList) $ \\generator -> do\n St.forM_ (St.enumFromStepN 0 nx (ny-1)) $ \\offset ->\n St.unsafeWith (St.slice offset nx (St.unsafeCast vector)) $\n checkCPLError \"FeedLine\" . {#call unsafe GDAL_CG_FeedLine as ^#} generator\n getContours pList\n where\n alloc pList =\n {#call unsafe GDAL_CG_Create as ^#}\n (fromIntegral nx)\n (fromIntegral ny)\n (fromBool (isJust nodataVal))\n (maybe 0 realToFrac nodataVal)\n (realToFrac interval)\n (realToFrac base)\n c_contourWriter\n (castPtr pList)\n\n free pList gen = do\n freeContourList pList\n {#call unsafe GDAL_CG_Destroy as ^#} gen\n\n getContours pList =\n bracket\n ({#call unsafe pop_contour#} pList)\n {#call unsafe destroy_contour#} $ \\c ->\n if c==nullPtr\n then return []\n else do\n fp <- bracketOnError\n ({#get Contour->points#} c)\n {#call unsafe destroy_points#}\n (newForeignPtr c_destroyPoints)\n nPoints <- liftM fromIntegral ({#get Contour->nPoints#} c)\n contour <- Contour <$> liftM realToFrac ({#get Contour->level#} c)\n <*> pure (St.unsafeFromForeignPtr0 fp nPoints)\n liftM (contour:) (getContours pList)\n\n freeContourList pList = do\n p <- {#call unsafe pop_contour#} pList\n if p==nullPtr\n then return ()\n else do {#get Contour->points#} p >>= {#call unsafe destroy_points#}\n {#call unsafe destroy_contour #} p\n freeContourList pList\n\n\n\ncontourGenerateVector\n :: Double\n -> Double\n -> Maybe Double\n -> Size\n -> (St.Vector Double)\n -> Either GDALException [Contour]\ncontourGenerateVector interval base nodataVal size =\n unsafePerformIO . try . contourGenerateVectorIO interval base nodataVal size\n\ntype CContourWriter =\n CDouble -> CInt -> Ptr CDouble -> Ptr CDouble -> Ptr () -> IO CInt\n\nforeign import ccall \"contourwriter.h &hs_contour_writer\"\n c_contourWriter :: FunPtr CContourWriter\n\nforeign import ccall \"contourwriter.h &destroy_points\"\n c_destroyPoints :: FunPtr (Ptr XYDouble -> IO ())\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"63e4ae824d1336ee8c505b7fa4c86080d010e4e6","subject":"Make safe calls to g_object_get_property","message":"Make safe calls to g_object_get_property\n\nThis is too complex a function for use to be confident that it's ok to make an\nunsafe foreign call to it.\nThis probably does not fix Axel's current segfault bug.\n\ndarcs-hash:20060130080710-b4c10-ed5bb73618e2d87b2c0fd77aed19cd3f8081e849.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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 objectSetPropertyGObject,\n objectGetPropertyGObject,\n \n objectSetPropertyInternal,\n objectGetPropertyInternal,\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 newAttrFromMaybeStringProperty,\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 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\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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString 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 objectSetPropertyGObject,\n objectGetPropertyGObject,\n \n objectSetPropertyInternal,\n objectGetPropertyInternal,\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 newAttrFromMaybeStringProperty,\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\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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString 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":"50398c84af235b8f7a95a57391a0315943d7a6d8","subject":"closes #10: add clEnqueueNativeKernel function","message":"closes #10: add clEnqueueNativeKernel function\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.chs","new_file":"src\/Control\/Parallel\/OpenCL\/CommandQueue.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.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), CLMapFlag(..),\n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\n clEnqueueUnmapMemObject,\n -- * Executing Kernels\n clEnqueueNDRangeKernel, clEnqueueTask, clEnqueueNativeKernel, \n clEnqueueMarker, clEnqueueWaitForEvents, clEnqueueBarrier,\n -- * Flush and Finish\n clFlush, clFinish\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\ntype NativeKernelCallback = Ptr () -> IO ()\nforeign import CALLCONV \"wrapper\" wrapNativeKernelCallback :: \n NativeKernelCallback -> IO (FunPtr NativeKernelCallback)\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNativeKernel\" raw_clEnqueueNativeKernel ::\n CLCommandQueue -> FunPtr NativeKernelCallback -> Ptr () -> CSize -> CLuint -> Ptr CLMem -> Ptr (Ptr ()) -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clFinish\" raw_clFinish ::\n CLCommandQueue -> IO CLint\n\n-- -----------------------------------------------------------------------------\nwithMaybeArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b\nwithMaybeArray [] = ($ nullPtr)\nwithMaybeArray xs = withArray xs\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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n \n{-| Enqueues a command to unmap a previously mapped region of a memory object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\nReads or writes from the host using the pointer returned by 'clEnqueueMapBuffer'\nor 'clEnqueueMapImage' are considered to be complete.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' increments the mapped count of the\nmemory object. The initial mapped count value of a memory object is\nzero. Multiple calls to 'clEnqueueMapBuffer' or 'clEnqueueMapImage' on the same\nmemory object will increment this mapped count by appropriate number of\ncalls. 'clEnqueueUnmapMemObject' decrements the mapped count of the memory\nobject.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' act as synchronization points for a\nregion of the memory object being mapped.\n\n'clEnqueueUnmapMemObject' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\n\n * CL_INVALID_COMMAND_QUEUE if command_queue is not a valid command-queue.\n\n * CL_INVALID_MEM_OBJECT if memobj is not a valid memory object.\n\n * CL_INVALID_VALUE if mapped_ptr is not a valid pointer returned by\n'clEnqueueMapBuffer' or 'clEnqueueMapImage' for memobj.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n * CL_INVALID_CONTEXT if the context associated with command_queue and memobj\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n-}\nclEnqueueUnmapMemObject :: CLCommandQueue \n -> CLMem -- ^ A valid memory object. The OpenCL\n -- context associated with command_queue and\n -- memobj must be the same.\n -> Ptr () -- ^ The host address returned by a\n -- previous call to 'clEnqueueMapBuffer' or\n -- 'clEnqueueMapImage' for memobj.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before\n -- 'clEnqueueUnmapMemObject' can be\n -- executed. If event_wait_list is\n -- empty, then 'clEnqueueUnmapMemObject'\n -- does not wait on any event to\n -- complete. The events specified in\n -- event_wait_list act as\n -- synchronization points. The context\n -- associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n\n -> IO CLEvent\nclEnqueueUnmapMemObject cq mem pp = clEnqueue (raw_clEnqueueUnmapMemObject cq mem pp)\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (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. It can throw\nthe following 'CLError' exceptions:\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 CLEvent\nclEnqueueTask cq krn = clEnqueue (raw_clEnqueueTask cq krn)\n \n{-| Enqueues a command to execute a native C\/C++ function not compiled using the\nOpenCL compiler. A native user function can only be executed on a command-queue\ncreated on a device that has 'CL_EXEC_NATIVE_KERNEL' capability set in\n'clGetDeviceExecutionCapabilities'.\n\nThe data pointed to by args and cb_args bytes in size will be copied and a\npointer to this copied region will be passed to user_func. The copy needs to be\ndone because the memory objects ('CLMem' values) that args may contain need to\nbe modified and replaced by appropriate pointers to global memory. When\n'clEnqueueNativeKernel' returns, the memory region pointed to by args can be\nreused by the application.\n\nReturns the evens if the kernel execution was successfully queued. It can throw\nthe following 'CLError' exceptions:\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_CONTEXT' if context associated with command_queue and events in\nevent-wait_list are not the same.\n\n * 'CL_INVALID_VALUE' if args is a NULL value and cb_args is greater than 0, or\nif args is a NULL value and num_mem_objects is greater than 0.\n\n * 'CL_INVALID_VALUE' if args is not NULL and cb_args is 0.\n\n * 'CL_INVALID_OPERATION' if device cannot execute the native kernel.\n\n * 'CL_INVALID_MEM_OBJECT' if one or more memory objects specified in mem_list\nare not valid or are not buffer objects.\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 buffer objects specified as arguments to kernel.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\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-}\nclEnqueueNativeKernel :: CLCommandQueue -> (Ptr () -> IO ()) -> Ptr () -> CSize \n -> [CLMem] -> [Ptr ()] -> [CLEvent] -> IO CLEvent\nclEnqueueNativeKernel cq f dat sz xs ys evs = \n withMaybeArray xs $ \\pmem -> \n withMaybeArray ys $ \\pbuff -> do\n fptr <- wrapNativeKernelCallback f\n clEnqueue (raw_clEnqueueNativeKernel cq fptr dat sz \n (fromIntegral . length $ xs) pmem pbuff) evs\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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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":"{- 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.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), CLMapFlag(..),\n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer, clEnqueueReadImage, \n clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer,\n clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage,\n clEnqueueUnmapMemObject,\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 Control.Parallel.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLMapFlags_, CLMapFlag(..), CLCommandQueue, CLDeviceID, CLContext, \n CLCommandQueueProperty(..), CLEvent, CLMem, CLKernel,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, \n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import CALLCONV \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import CALLCONV \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueReadImage\" raw_clEnqueueReadImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueWriteImage\" raw_clEnqueueWriteImage ::\n CLCommandQueue -> CLMem -> CLbool -> Ptr CSize -> Ptr CSize -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImage\" raw_clEnqueueCopyImage ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyImageToBuffer\" raw_clEnqueueCopyImageToBuffer ::\n CLCommandQueue -> CLMem -> CLMem -> Ptr CSize -> Ptr CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueCopyBufferToImage\" raw_clEnqueueCopyBufferToImage ::\n CLCommandQueue -> CLMem -> CLMem -> CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMapBuffer\" raw_clEnqueueMapBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> CSize -> CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueMapImage\" raw_clEnqueueMapImage ::\n CLCommandQueue -> CLMem -> CLbool -> CLMapFlags_ -> Ptr CSize -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> Ptr CLint -> IO (Ptr ())\nforeign import CALLCONV \"clEnqueueUnmapMemObject\" raw_clEnqueueUnmapMemObject ::\n CLCommandQueue -> CLMem -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import CALLCONV \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import CALLCONV \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import CALLCONV \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import CALLCONV \"clFinish\" raw_clFinish ::\n CLCommandQueue -> IO CLint\n\n-- -----------------------------------------------------------------------------\nwithMaybeArray :: Storable a => [a] -> (Ptr a -> IO b) -> IO b\nwithMaybeArray [] = ($ nullPtr)\nwithMaybeArray xs = withArray xs\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 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_CONTEXT'.\nclGetCommandQueueContext :: CLCommandQueue -> IO CLContext\nclGetCommandQueueContext cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with 'CL_QUEUE_DEVICE'.\nclGetCommandQueueDevice :: CLCommandQueue -> IO CLDeviceID\nclGetCommandQueueDevice cq =\n 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.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_REFERENCE_COUNT'.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO CLuint\nclGetCommandQueueReferenceCount cq =\n 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'.\n--\n-- This function execute OpenCL clGetCommandQueueInfo with\n-- 'CL_QUEUE_PROPERTIES'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO [CLCommandQueueProperty]\nclGetCommandQueueProperties cq =\n 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 [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca \n $ \\(dat :: Ptr CLCommandQueueProperty_) \n -> whenSuccess (f dat)\n $ fmap bitmaskToCommandQueueProperties $ peek dat\n where\n f = raw_clSetCommandQueueProperty cq props (fromBool val)\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO CLEvent\nclEnqueue f [] = alloca $ \\event -> whenSuccess (f 0 nullPtr event)\n $ peek event\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> whenSuccess (f cnevents pevents event)\n $ peek event\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. It can throw the following 'CLError' exceptions:\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 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. It can throw the following 'CLError' exceptions:\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 CLEvent\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueues a command to read from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular read command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking is 'True' i.e. the read command is blocking, 'clEnqueueReadImage'\ndoes not return until the buffer data has been read and copied into memory\npointed to by ptr.\n\nIf blocking_read is 'False' i.e. map operation is non-blocking,\n'clEnqueueReadImage' queues a non-blocking read command and returns. The\ncontents of the buffer that ptr points to cannot be used until the read command\nhas completed. The event argument returns an event object which can be used to\nquery the execution status of the read command. When the read command has\ncompleted, the contents of the buffer that ptr points to can be used by the\napplication.\n\nCalling 'clEnqueueReadImage' to read a region of the image object with the ptr\nargument value set to host_ptr + (origin.z * image slice pitch + origin.y *\nimage row pitch + origin.x * bytes per pixel), where host_ptr is a pointer to\nthe memory region specified when the image 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 image object have finished execution before the\nread command begins execution.\n\n * The row_pitch and slice_pitch argument values in clEnqueueReadImage must be\nset to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the read command has\nfinished execution.\n\n'clEnqueueReadImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by origin and region is\nout of bounds or if ptr is a nullPtr value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueReadImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the read command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the read operations are blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to read. If image is a\n -- 2D image object, the z value given must be\n -- 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- read. If image is a 2D image object, the\n -- depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value must\n -- be greater than or equal to the element size in\n -- bytes * width. If row_pitch is set to 0, the\n -- appropriate row pitch is calculated based on the\n -- size of each element in bytes multiplied by width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being read. This must be 0 if image\n -- is a 2D image. This value must be greater than or\n -- equal to row_pitch * height. If slice_pitch is set\n -- to 0, the appropriate slice pitch is calculated\n -- based on the row_pitch * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be read from.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in the list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueReadImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueReadImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to write from a 2D or 3D image object to host memory.\n\nReturns an event object that identifies this particular write command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nNotes\n\nIf blocking_write is 'True' the OpenCL implementation copies the data referred\nto by ptr and enqueues the write command in the command-queue. The memory\npointed to by ptr can be reused by the application after the\n'clEnqueueWriteImage' call returns.\n\nIf blocking_write is 'False' the OpenCL implementation will use ptr to perform a\nnonblocking write. As the write is non-blocking the implementation can return\nimmediately. The memory pointed to by ptr cannot be reused by the application\nafter the call returns. The event argument returns an event object which can be\nused to query the execution status of the write command. When the write command\nhas completed, the memory pointed to by ptr can then be reused by the\napplication.\n\nCalling 'clEnqueueWriteImage' to update the latest bits in a region of the image\nobject with the ptr argument value set to host_ptr + (origin.z * image slice\npitch + origin.y * image row pitch + origin.x * bytes per pixel), where host_ptr\nis a pointer to the memory region specified when the image object being written\nis created with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region being written contains the latest bits when the\nenqueued write command begins execution.\n\n * The input_row_pitch and input_slice_pitch argument values in\nclEnqueueWriteImage must be set to the image row pitch and slice pitch.\n\n * The image object is not mapped.\n\n * The image object is not used by any command-queue until the write command has\nfinished execution.\n\n'clEnqueueWriteImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the region being write or written specified by origin\nand region is out of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1 or slice_pitch is not equal to 0.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 image.\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-}\nclEnqueueWriteImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the write command will be\n -- queued. command_queue and image must\n -- be created with the same OpenCL\n -- contex\n -> CLMem -- ^ Refers to a valid 2D or 3D image object.\n -> Bool -- ^ Indicates if the write operation is blocking\n -- or non-blocking.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in pixels in\n -- the image from where to write or write. If\n -- image is a 2D image object, the z value\n -- given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle being\n -- write or written. If image is a 2D image\n -- object, the depth value given must be 1.\n -> a -- ^ The length of each row in bytes. This value\n -- must be greater than or equal to the element size\n -- in bytes * width. If input_row_pitch is set to 0,\n -- the appropriate row pitch is calculated based on\n -- the size of each element in bytes multiplied by\n -- width.\n -> a -- ^ Size in bytes of the 2D slice of the 3D region\n -- of a 3D image being written. This must be 0 if\n -- image is a 2D image. This value must be greater\n -- than or equal to row_pitch * height. If\n -- input_slice_pitch is set to 0, the appropriate\n -- slice pitch is calculated based on the row_pitch\n -- * height.\n -> Ptr () -- ^ The pointer to a buffer in host memory\n -- where image data is to be written to.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not\n -- wait on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n -> IO CLEvent\nclEnqueueWriteImage cq mem check (orix,oriy,oriz) (regx,regy,regz) rp sp dat xs = \n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueWriteImage cq mem (fromBool check) pori preg (fromIntegral rp) (fromIntegral sp) dat) xs\n \n{-| Enqueues a command to copy image objects.\n\nNotes \n\nIt is currently a requirement that the src_image and dst_image image memory\nobjects for 'clEnqueueCopyImage' must have the exact same image format (i.e. the\n'CLImageFormat' descriptor specified when src_image and dst_image are created\nmust match).\n\nsrc_image and dst_image can be 2D or 3D image objects allowing us to perform the\nfollowing actions:\n\n * Copy a 2D image object to a 2D image object.\n\n * Copy a 2D image object to a 2D slice of a 3D image object.\n\n * Copy a 2D slice of a 3D image object to a 2D image object.\n\n * Copy a 3D image object to a 3D image object.\n\n'clEnqueueCopyImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT if src_image and dst_image are not valid image\nobjects.\n\n * 'CL_IMAGE_FORMAT_MISMATCH if src_image and dst_image do not use the same\nimage format.\n\n * 'CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the 2D or 3D\nrectangular region specified by dst_origin and dst_origin + region refers to a\nregion outside dst_image.\n\n * 'CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_VALUE if dst_image is a 2D image object and dst_origen.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory\nfor data store associated with src_image or dst_image.\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 * 'CL_MEM_COPY_OVERLAP if src_image and dst_image are the same image object and\nthe source and destination regions overlap.\n\n-}\nclEnqueueCopyImage :: Integral a \n => CLCommandQueue -- ^ Refers to the command-queue in\n -- which the copy command will be\n -- queued. The OpenCL context associated\n -- with command_queue, src_image and\n -- dst_image must be the same.\n -> CLMem -- ^ src\n -> CLMem -- ^ dst\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in src_image from where to start the\n -- data copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the starting (x, y, z) location in\n -- pixels in dst_image from where to start the\n -- data copy. If dst_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth) in\n -- pixels of the 2D or 3D rectangle to copy. If\n -- src_image or dst_image is a 2D image object,\n -- the depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty, then\n -- this particular command does not wait on\n -- any event to complete. \n -> IO CLEvent\nclEnqueueCopyImage cq src dst (src_orix,src_oriy,src_oriz) (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImage cq src dst psrc_ori pdst_ori preg) xs\n\n\n{-| Enqueues a command to copy an image object to a buffer object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyImageToBuffer' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * CL_INVALID_MEM_OBJECT if src_image is not a valid image object and dst_buffer\nis not a valid buffer object.\n\n * CL_INVALID_VALUE if the 2D or 3D rectangular region specified by src_origin\nand src_origin + region refers to a region outside src_image, or if the region\nspecified by dst_offset and dst_offset + dst_cb refers to a region outside\ndst_buffer.\n\n * CL_INVALID_VALUE if src_image is a 2D image object and src_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_MEM_OBJECT_ALLOCATION_FAILURE if there is a failure to allocate memory for\ndata store associated with src_image or dst_buffer.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n-}\nclEnqueueCopyImageToBuffer :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid image object.\n -> CLMem -- ^ dst. A valid buffer object.\n -> (a,a,a) -- ^ Defines the (x, y, z) offset in\n -- pixels in the image from where to\n -- copy. If src_image is a 2D image\n -- object, the z value given must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If src_image is a 2D image\n -- object, the depth value given must\n -- be 1.\n -> a -- ^ The offset where to begin copying data\n -- into dst_buffer. The size in bytes of the\n -- region to be copied referred to as dst_cb\n -- is computed as width * height * depth *\n -- bytes\/image element if src_image is a 3D\n -- image object and is computed as width *\n -- height * bytes\/image element if src_image\n -- is a 2D image object.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyImageToBuffer cq src dst (src_orix,src_oriy,src_oriz) (regx,regy,regz) offset xs =\n withArray (fmap fromIntegral [src_orix,src_oriy,src_oriz]) $ \\psrc_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyImageToBuffer cq src dst psrc_ori preg (fromIntegral offset)) xs\n\n{-| Enqueues a command to copy a buffer object to an image object.\n\nThe size in bytes of the region to be copied from src_buffer referred to as\nsrc_cb is computed as width * height * depth * bytes\/image element if dst_image\nis a 3D image object and is computed as width * height * bytes\/image element if\ndst_image is a 2D image object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\n'clEnqueueCopyBufferToImage' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\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, src_buffer\nand dst_image are not the same or if the context associated with command_queue\nand events in event_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if src_buffer is not a valid buffer object and\ndst_image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if the 2D or 3D rectangular region specified by dst_origin\nand dst_origin + region refers to a region outside dst_origin, or if the region\nspecified by src_offset and src_offset + src_cb refers to a region outside\nsrc_buffer.\n\n * 'CL_INVALID_VALUE' if dst_image is a 2D image object and dst_origin.z is not\nequal to 0 or region.depth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' 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 src_buffer or dst_image.\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-}\nclEnqueueCopyBufferToImage :: Integral a \n => CLCommandQueue -- ^ The OpenCL context\n -- associated with\n -- command_queue, src_image, and\n -- dst_buffer must be the same.\n -> CLMem -- ^ src. A valid buffer object.\n -> CLMem -- ^ dst. A valid image object.\n -> a -- ^ The offset where to begin copying data\n -- from src_buffer.\n -> (a,a,a) -- ^ The (x, y, z) offset in pixels\n -- where to begin copying data to\n -- dst_image. If dst_image is a 2D\n -- image object, the z value given by\n -- must be 0.\n -> (a,a,a) -- ^ Defines the (width, height, depth)\n -- in pixels of the 2D or 3D rectangle\n -- to copy. If dst_image is a 2D image\n -- object, the depth value given by\n -- must be 1.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before this particular\n -- command can be executed. If\n -- event_wait_list is empty, then\n -- this particular command does not\n -- wait on any event to complete. The\n -- events specified in\n -- event_wait_list act as\n -- synchronization points. The\n -- context associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n -> IO CLEvent\nclEnqueueCopyBufferToImage cq src dst offset (dst_orix,dst_oriy,dst_oriz) (regx,regy,regz) xs =\n withArray (fmap fromIntegral [dst_orix,dst_oriy,dst_oriz]) $ \\pdst_ori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n clEnqueue (raw_clEnqueueCopyBufferToImage cq src dst (fromIntegral offset) pdst_ori preg) xs\n\n{-| Enqueues a command to map a region of the buffer object given by buffer into\nthe host address space and returns a pointer to this mapped region.\n\nIf blocking_map is 'True', 'clEnqueueMapBuffer' does not return until the\nspecified region in buffer can be mapped.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapBuffer' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapBuffer'.\n\nReturns an event object that identifies this particular copy command and can be\nused toquery or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapBuffer' will return a pointer to the mapped region if the function\nis executed successfully. A nullPtr pointer is returned otherwise with one of\nthe following exception:\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, src_image\nand dst_buffer are not the same or if the context associated with command_queue\nand events in event_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 region being mapped given by (offset, cb) is out of\nbounds or if values specified in map_flags are not valid\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for buffer objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\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\nThe pointer returned maps a region starting at offset and is atleast cb bytes in\nsize. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapBuffer :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid buffer object. The OpenCL context\n -- associated with command_queue and buffer must\n -- be the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking.\n -> [CLMapFlag] -- ^ Is a list and can be set to\n -- 'CL_MAP_READ' to indicate that the\n -- region specified by (offset, cb) in the\n -- buffer object is being mapped for\n -- reading, and\/or 'CL_MAP_WRITE' to\n -- indicate that the region specified by\n -- (offset, cb) in the buffer object is\n -- being mapped for writing.\n -> a -- ^ The offset in bytes of the region in the buffer\n -- object that is being mapped.\n -> a -- ^ The size in bytes of the region in the buffer\n -- object that is being mapped.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before this particular command can be\n -- executed. If event_wait_list is empty,\n -- then this particular command does not wait\n -- on any event to complete. The events\n -- specified in event_wait_list act as\n -- synchronization points. The context\n -- associated with events in event_wait_list\n -- and command_queue must be the same.\n\n -> IO (CLEvent, Ptr ())\nclEnqueueMapBuffer cq mem check xs offset cb [] = \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) 0 nullPtr pevent perr\n event <- peek pevent\n return (event, val)\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapBuffer cq mem check xs offset cb events = \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapBuffer cq mem (fromBool check) flags (fromIntegral offset) (fromIntegral cb) cnevents pevents pevent perr\n event <- peek pevent\n return (event, val)\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n\n{-| Enqueues a command to map a region of an image object into the host address\nspace and returns a pointer to this mapped region.\n\nIf blocking_map is 'False' i.e. map operation is non-blocking, the pointer to\nthe mapped region returned by 'clEnqueueMapImage' cannot be used until the map\ncommand has completed. The event argument returns an event object which can be\nused to query the execution status of the map command. When the map command is\ncompleted, the application can access the contents of the mapped region using\nthe pointer returned by 'clEnqueueMapImage'.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to complete.\n\nIf the buffer or image object is created with 'CL_MEM_USE_HOST_PTR' set in\nmem_flags, the following will be true:\n\n* The host_ptr specified in 'clCreateBuffer', 'clCreateImage2D', or\n'clCreateImage3D' is guaranteed to contain the latest bits in the region being\nmapped when the 'clEnqueueMapBuffer' or 'clEnqueueMapImage' command has\ncompleted.\n\n * The pointer value returned by 'clEnqueueMapBuffer' or 'clEnqueueMapImage'\nwill be derived from the host_ptr specified when the buffer or image object is\ncreated. \n\nThe contents of the regions of a memory object mapped for writing\n(i.e. 'CL_MAP_WRITE' is set in map_flags argument to 'clEnqueueMapBuffer' or\n'clEnqueueMapImage') are considered to be undefined until this region is\nunmapped. Reads and writes by a kernel executing on a device to a memory\nregion(s) mapped for writing are undefined.\n\nMultiple command-queues can map a region or overlapping regions of a memory\nobject for reading (i.e. map_flags = 'CL_MAP_READ'). The contents of the regions\nof a memory object mapped for reading can also be read by kernels executing on a\ndevice(s). The behavior of writes by a kernel executing on a device to a mapped\nregion of a memory object is undefined. Mapping (and unmapping) overlapped\nregions of a buffer or image memory object for writing is undefined.\n\nThe behavior of OpenCL function calls that enqueue commands that write or copy\nto regions of a memory object that are mapped is undefined.\n\n'clEnqueueMapImage' will return a pointer to the mapped region if the\nfunction is executed successfully also the scan-line (row) pitch in bytes for\nthe mapped region and the size in bytes of each 2D slice for the mapped\nregion. For a 2D image, zero is returned as slice pitch. A nullPtr pointer is\nreturned otherwise with one of the following exception:\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 image\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 image is not a valid image object.\n\n * 'CL_INVALID_VALUE' if region being mapped given by (origin, origin+region) is\nout of bounds or if values specified in map_flags are not valid.\n\n * 'CL_INVALID_VALUE' if image is a 2D image object and z is not equal to 0 or\ndepth is not equal to 1.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MAP_FAILURE' if there is a failure to map the requested region into the\nhost address space. This error cannot occur for image objects created with\n'CL_MEM_USE_HOST_PTR' or 'CL_MEM_ALLOC_HOST_PTR'.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\nThe pointer returned maps a 2D or 3D region starting at origin and is atleast\n(image_row_pitch * y + x) pixels in size for a 2D image, and is atleast\n(image_slice_pitch * z] + image_row_pitch * y + x) pixels in size for a 3D\nimage. The result of a memory access outside this region is undefined.\n\n-}\nclEnqueueMapImage :: Integral a => CLCommandQueue \n -> CLMem -- ^ A valid image object. The OpenCL context\n -- associated with command_queue and image must be\n -- the same.\n -> Bool -- ^ Indicates if the map operation is blocking or\n -- non-blocking. If blocking_map is 'True',\n -- 'clEnqueueMapImage' does not return until the\n -- specified region in image can be mapped.\n -> [CLMapFlag] -- ^ Is a bit-field and can be set to\n -- 'CL_MAP_READ' to indicate that the region\n -- specified by (origin, region) in the\n -- image object is being mapped for reading,\n -- and\/or 'CL_MAP_WRITE' to indicate that the\n -- region specified by (origin, region) in\n -- the image object is being mapped for\n -- writing.\n -> (a,a,a) -- ^ Define the (x, y, z) offset in pixels of\n -- the 2D or 3D rectangle region that is to be\n -- mapped. If image is a 2D image object, the z\n -- value given must be 0.\n -> (a,a,a) -- ^ Define the (width, height, depth) in pixels\n -- of the 2D or 3D rectangle region that is to\n -- be mapped. If image is a 2D image object, the\n -- depth value given must be 1.\n -> [CLEvent] -- ^ Specify events that need to complete\n -- before 'clEnqueueMapImage' can be\n -- executed. If event_wait_list is empty, then\n -- 'clEnqueueMapImage' does not wait on any\n -- event to complete. The events specified in\n -- event_wait_list act as synchronization\n -- points. The context associated with events\n -- in event_wait_list and command_queue must\n -- be the same.\n -> IO (CLEvent, (Ptr (), CSize, CSize))\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) [] = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice 0 nullPtr pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n \n where\n flags = bitmaskFromFlags xs\nclEnqueueMapImage cq mem check xs (orix,oriy,oriz) (regx,regy,regz) events = \n alloca $ \\ppitch -> \n alloca $ \\pslice ->\n withArray (fmap fromIntegral [orix,oriy,oriz]) $ \\pori -> \n withArray (fmap fromIntegral [regx,regy,regz]) $ \\preg -> \n allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\pevent -> do\n val <- wrapPError $ \\perr -> raw_clEnqueueMapImage cq mem (fromBool check) flags pori preg ppitch pslice cnevents pevents pevent perr\n event <- peek pevent\n pitch <- peek ppitch\n slice <- peek pslice\n return (event, (val, pitch, slice))\n\n where\n flags = bitmaskFromFlags xs\n nevents = length events\n cnevents = fromIntegral nevents\n \n{-| Enqueues a command to unmap a previously mapped region of a memory object.\n\nReturns an event object that identifies this particular copy command and can be\nused to query or queue a wait for this particular command to complete. event can\nbe NULL in which case it will not be possible for the application to query the\nstatus of this command or queue a wait for this command to\ncomplete. 'clEnqueueBarrier' can be used instead.\n\nReads or writes from the host using the pointer returned by 'clEnqueueMapBuffer'\nor 'clEnqueueMapImage' are considered to be complete.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' increments the mapped count of the\nmemory object. The initial mapped count value of a memory object is\nzero. Multiple calls to 'clEnqueueMapBuffer' or 'clEnqueueMapImage' on the same\nmemory object will increment this mapped count by appropriate number of\ncalls. 'clEnqueueUnmapMemObject' decrements the mapped count of the memory\nobject.\n\n'clEnqueueMapBuffer' and 'clEnqueueMapImage' act as synchronization points for a\nregion of the memory object being mapped.\n\n'clEnqueueUnmapMemObject' returns the 'CLEvent' if the function is executed\nsuccessfully. It can throw the following 'CLError' exceptions:\n\n * CL_INVALID_COMMAND_QUEUE if command_queue is not a valid command-queue.\n\n * CL_INVALID_MEM_OBJECT if memobj is not a valid memory object.\n\n * CL_INVALID_VALUE if mapped_ptr is not a valid pointer returned by\n'clEnqueueMapBuffer' or 'clEnqueueMapImage' for memobj.\n\n * CL_INVALID_EVENT_WAIT_LIST if event objects in event_wait_list are not valid\nevents.\n\n * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n\n * CL_INVALID_CONTEXT if the context associated with command_queue and memobj\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n-}\nclEnqueueUnmapMemObject :: CLCommandQueue \n -> CLMem -- ^ A valid memory object. The OpenCL\n -- context associated with command_queue and\n -- memobj must be the same.\n -> Ptr () -- ^ The host address returned by a\n -- previous call to 'clEnqueueMapBuffer' or\n -- 'clEnqueueMapImage' for memobj.\n -> [CLEvent] -- ^ Specify events that need to\n -- complete before\n -- 'clEnqueueUnmapMemObject' can be\n -- executed. If event_wait_list is\n -- empty, then 'clEnqueueUnmapMemObject'\n -- does not wait on any event to\n -- complete. The events specified in\n -- event_wait_list act as\n -- synchronization points. The context\n -- associated with events in\n -- event_wait_list and command_queue\n -- must be the same.\n\n -> IO CLEvent\nclEnqueueUnmapMemObject cq mem pp = clEnqueue (raw_clEnqueueUnmapMemObject cq mem pp)\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. It can throw\nthe following 'CLError' exceptions:\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] \n -> [CLEvent] -> IO CLEvent\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withMaybeArray (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. It can throw\nthe following 'CLError' exceptions:\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 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 throw the 'CLError' exception\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- throw '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 CLEvent\nclEnqueueMarker cq = alloca $ \\event \n -> whenSuccess (raw_clEnqueueMarker cq event)\n $ peek event\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\nIt can throw the following 'CLError' exceptions:\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 ()\nclEnqueueWaitForEvents cq [] = whenSuccess \n (raw_clEnqueueWaitForEvents cq 0 nullPtr)\n $ return ()\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n whenSuccess (raw_clEnqueueWaitForEvents cq cnevents pevents)\n $ return ()\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 throws 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and throws\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 ()\nclEnqueueBarrier cq = whenSuccess (raw_clEnqueueBarrier cq) $ return ()\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","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2d8a5de40b5483796492f560e12c3240245cd346","subject":"Export object(Get\/Set)PropertyInternal","message":"Export object(Get\/Set)PropertyInternal\n\nJust to make the old TreeList\/CellRenderer.hs build\nAdded a note to make them private again when TreeList\/* is dropped.\n\ndarcs-hash:20061208210834-b4c10-0a20e8a95eb9a28efcf15e52ab9ba1ee581e6853.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","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\n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\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 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","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"0c72b29c56e00a550d2a9ad4226c0642d0663b9d","subject":"Fix memory leak - missing free","message":"Fix memory leak - missing free\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\n ( hyperGet\n , hyperPut\n , hyperPutIfNotExist\n , hyperDelete \n )\n where\n\n{# import Database.HyperDex.Internal.ReturnCode #}\n{# import Database.HyperDex.Internal.Client #}\n{# import Database.HyperDex.Internal.Attribute #}\nimport Database.HyperDex.Internal.Util\n\n#include \"hyperclient.h\"\n\ndata HyperclientMapAttribute\n{#pointer *hyperclient_map_attribute -> HyperclientMapAttribute nocode #}\n\ndata HyperclientAttributeCheck\n{#pointer *hyperclient_attribute_check -> HyperclientAttributeCheck nocode #}\n\nhyperGet :: Client -> ByteString -> ByteString\n -> IO (IO (HyperclientReturnCode, [Attribute]))\nhyperGet c s k = withClient c (\\hc -> hyperclientGet hc s k)\n\nhyperPut :: Client -> ByteString -> ByteString -> [Attribute]\n -> IO (IO (HyperclientReturnCode))\nhyperPut c s k a = withClient c (\\hc -> hyperclientPut hc s k a)\n\nhyperPutIfNotExist :: Client -> ByteString -> ByteString -> [Attribute]\n -> IO (IO (HyperclientReturnCode))\nhyperPutIfNotExist c s k a = withClient c (\\hc -> hyperclientPutIfNotExist hc s k a)\n\nhyperDelete :: Client -> ByteString -> ByteString\n -> IO (IO (HyperclientReturnCode))\nhyperDelete c s k = withClient c (\\hc -> hyperclientDelete hc s k)\n\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 :: Hyperclient -> ByteString -> ByteString\n -> Result (HyperclientReturnCode, [Attribute]) \nhyperclientGet client s k = do\n returnCodePtr <- malloc\n attributePtrPtr <- malloc\n attributeSizePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n handle <- {# call hyperclient_get #}\n client\n space key (fromIntegral keySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n let result :: IO (HyperclientReturnCode, [Attribute])\n result = do\n print \"Inside get!\"\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n print $ \"Got a returnCode!\" ++ show returnCode\n attributePtr <- peek attributePtrPtr\n attributeSize <- fmap fromIntegral $ peek attributeSizePtr\n attributes <- fromHyperDexAttributeArray attributePtr attributeSize\n free returnCodePtr\n free attributePtrPtr\n free attributeSizePtr\n free space\n free key\n return (returnCode, attributes)\n return (handle, result)\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 :: Hyperclient -> ByteString -> ByteString\n -> [Attribute]\n -> Result (HyperclientReturnCode)\nhyperclientPut client s k attributes = do\n returnCodePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n handle <- {# call hyperclient_put #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n hyperdexFreeAttributes attributePtr attributeSize\n return returnCode\n return (handle, continuation)\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 :: Hyperclient -> ByteString -> ByteString\n -> [Attribute]\n -> Result (HyperclientReturnCode)\nhyperclientPutIfNotExist client s k attributes = do\n returnCodePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n handle <- {# call hyperclient_put_if_not_exist #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n hyperdexFreeAttributes attributePtr attributeSize\n return returnCode\n return (handle, continuation)\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 :: Hyperclient -> ByteString -> ByteString\n -> Result (HyperclientReturnCode)\nhyperclientDelete client s k = do\n returnCodePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n handle <- {# call hyperclient_del #} \n client\n space key (fromIntegral keySize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n return returnCode\n return (handle, continuation)\n","old_contents":"module Database.HyperDex.Internal.Hyperclient\n ( hyperGet\n , hyperPut\n , hyperPutIfNotExist\n , hyperDelete \n )\n where\n\n{# import Database.HyperDex.Internal.ReturnCode #}\n{# import Database.HyperDex.Internal.Client #}\n{# import Database.HyperDex.Internal.Attribute #}\nimport Database.HyperDex.Internal.Util\n\n#include \"hyperclient.h\"\n\ndata HyperclientMapAttribute\n{#pointer *hyperclient_map_attribute -> HyperclientMapAttribute nocode #}\n\ndata HyperclientAttributeCheck\n{#pointer *hyperclient_attribute_check -> HyperclientAttributeCheck nocode #}\n\nhyperGet :: Client -> ByteString -> ByteString\n -> IO (IO (HyperclientReturnCode, [Attribute]))\nhyperGet c s k = withClient c (\\hc -> hyperclientGet hc s k)\n\nhyperPut :: Client -> ByteString -> ByteString -> [Attribute]\n -> IO (IO (HyperclientReturnCode))\nhyperPut c s k a = withClient c (\\hc -> hyperclientPut hc s k a)\n\nhyperPutIfNotExist :: Client -> ByteString -> ByteString -> [Attribute]\n -> IO (IO (HyperclientReturnCode))\nhyperPutIfNotExist c s k a = withClient c (\\hc -> hyperclientPutIfNotExist hc s k a)\n\nhyperDelete :: Client -> ByteString -> ByteString\n -> IO (IO (HyperclientReturnCode))\nhyperDelete c s k = withClient c (\\hc -> hyperclientDelete hc s k)\n\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 :: Hyperclient -> ByteString -> ByteString\n -> Result (HyperclientReturnCode, [Attribute]) \nhyperclientGet client s k = do\n returnCodePtr <- malloc\n attributePtrPtr <- malloc\n attributeSizePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n handle <- {# call hyperclient_get #}\n client\n space key (fromIntegral keySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n let result :: IO (HyperclientReturnCode, [Attribute])\n result = do\n print \"Inside get!\"\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n print $ \"Got a returnCode!\" ++ show returnCode\n attributePtr <- peek attributePtrPtr\n attributeSize <- fmap fromIntegral $ peek attributeSizePtr\n attributes <- fromHyperDexAttributeArray attributePtr attributeSize\n free returnCodePtr\n free attributePtrPtr\n free attributeSizePtr\n free space\n free key\n return (returnCode, attributes)\n return (handle, result)\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 :: Hyperclient -> ByteString -> ByteString\n -> [Attribute]\n -> Result (HyperclientReturnCode)\nhyperclientPut client s k attributes = do\n returnCodePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n handle <- {# call hyperclient_put #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n hyperdexFreeAttributes attributePtr attributeSize\n return returnCode\n return (handle, continuation)\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 :: Hyperclient -> ByteString -> ByteString\n -> [Attribute]\n -> Result (HyperclientReturnCode)\nhyperclientPutIfNotExist client s k attributes = do\n returnCodePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n (attributePtr, attributeSize) <- newHyperDexAttributeArray attributes\n handle <- {# call hyperclient_put_if_not_exist #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n return returnCode\n return (handle, continuation)\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 :: Hyperclient -> ByteString -> ByteString\n -> Result (HyperclientReturnCode)\nhyperclientDelete client s k = do\n returnCodePtr <- malloc\n space <- newCBString s\n (key,keySize) <- newCBStringLen k\n handle <- {# call hyperclient_del #} \n client\n space key (fromIntegral keySize)\n returnCodePtr\n let continuation = do\n returnCode <- fmap (toEnum . fromIntegral) $ peek returnCodePtr\n free returnCodePtr\n free space\n free key\n return returnCode\n return (handle, continuation)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"e496987820a8f636402b70a7f4db62099e4ff62d","subject":"Convert remaining implemented APIs to use ByteString.","message":"Convert remaining implemented APIs to use ByteString.\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":"\nmodule Database.HyperDex.Internal.Hyperclient where\n\nimport Database.HyperDex.Internal.Attribute\nimport Database.HyperDex.Internal.Util\n\nimport Foreign.C.Types\nimport Foreign.Marshal\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.ByteString (ByteString)\nimport Data.Int\n\nimport Control.Applicative ((<$>))\n\n#include \"hyperclient.h\"\n\ndata Hyperclient\n{#pointer *hyperclient as HyperclientPtr -> Hyperclient #}\n\n{# pointer *hyperclient_attribute as AttributePtr -> Attribute #}\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\nnewtype HyperclientHandle = HyperclientHandle { unHyperclientHandle :: Int64 }\n\ntoHyperclientHandle :: CLong -> HyperclientHandle\ntoHyperclientHandle = HyperclientHandle . fromIntegral\n\n-- struct hyperclient*\n-- hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: ByteString -> Int16 -> IO HyperclientPtr\nhyperclientCreate h port = withCBString h $ \\host -> {# call hyperclient_create #} host (fromIntegral port)\n\n-- void\n-- hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: HyperclientPtr -> IO ()\nhyperclientDestroy = {# call hyperclient_destroy #}\n\n-- enum hyperclient_returncode\n-- hyperclient_add_space(struct hyperclient* client, const char* description);\nhyperclientAddSpace :: HyperclientPtr -> ByteString -> IO HyperclientReturnCode\nhyperclientAddSpace client d = withCBString d $ \\description -> do\n toEnum . fromIntegral <$> {#call hyperclient_add_space #} client description\n\n-- enum hyperclient_returncode\n-- hyperclient_rm_space(struct hyperclient* client, const char* space);\nhyperclientRemoveSpace :: HyperclientPtr -> ByteString -> IO HyperclientReturnCode\nhyperclientRemoveSpace client s = withCBString s $ \\space -> do\n toEnum . fromIntegral <$> {#call hyperclient_rm_space #} client space\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 -> ByteString -> ByteString\n -> IO (HyperclientHandle, HyperclientReturnCode, AttributeList) \nhyperclientGet client s k = do\n alloca $ \\returnCodePtr ->\n alloca $ \\attributePtrPtr ->\n alloca $ \\attributeSizePtr ->\n withCBString s $ \\space ->\n withCBStringLen k $ \\(key,keySize) -> do\n result <- {#call hyperclient_get#} \n client\n space key (fromIntegral keySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n attributePtr <- peek attributePtrPtr\n attributeSize <- fromIntegral <$> peek attributeSizePtr \n attributes <- fromHyperDexAttributeList attributePtr attributeSize\n return (toHyperclientHandle result, returnCode, attributes)\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 -> ByteString -> ByteString\n -> AttributeList\n -> IO (HyperclientHandle, HyperclientReturnCode)\nhyperclientPut client s k attributes = do\n alloca $ \\returnCodePtr ->\n withCBString s $ \\space ->\n withCBStringLen k $ \\(key,keySize) -> do\n let attributePtr = attributeListPointer attributes\n attributeSize = attributeListSize attributes\n result <- {# call hyperclient_put #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (toHyperclientHandle 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 -> ByteString -> ByteString\n -> AttributeList\n -> IO (HyperclientHandle, HyperclientReturnCode)\nhyperclientPutIfNotExist client s k attributes = do\n alloca $ \\returnCodePtr ->\n withCBString s $ \\space ->\n withCBStringLen k $ \\(key,keySize) -> do\n let attributePtr = attributeListPointer attributes\n attributeSize = attributeListSize attributes\n result <- {# call hyperclient_put_if_not_exist #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (toHyperclientHandle 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 -> ByteString -> ByteString\n -> IO (HyperclientHandle, HyperclientReturnCode)\nhyperclientDelete client s k = do\n alloca $ \\returnCodePtr -> do\n withCBString s $ \\space ->\n withCBStringLen k $ \\(key,keySize) -> do\n result <- {# call hyperclient_del #} \n client\n space key (fromIntegral keySize)\n returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (toHyperclientHandle result, returnCode)\n","old_contents":"\nmodule Database.HyperDex.Internal.Hyperclient where\n\nimport Database.HyperDex.Internal.Hyperdex\nimport Database.HyperDex.Internal.Attribute\nimport Database.HyperDex.Internal.Util\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.ByteString (ByteString)\nimport Data.Int\n\nimport Control.Applicative ((<$>))\n\n#include \"hyperclient.h\"\n\ndata Hyperclient\n{#pointer *hyperclient as HyperclientPtr -> Hyperclient #}\n\n{# pointer *hyperclient_attribute as AttributePtr -> Attribute #}\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\nnewtype HyperclientHandle = HyperclientHandle { unHyperclientHandle :: Int64 }\n\ntoHyperclientHandle :: CLong -> HyperclientHandle\ntoHyperclientHandle = HyperclientHandle . fromIntegral\n\n-- struct hyperclient*\n-- hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: ByteString -> Int16 -> IO HyperclientPtr\nhyperclientCreate h port = withCBString h $ \\host -> {# call hyperclient_create #} host (fromIntegral port)\n\n-- void\n-- hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: HyperclientPtr -> IO ()\nhyperclientDestroy = {# call hyperclient_destroy #}\n\n-- enum hyperclient_returncode\n-- hyperclient_add_space(struct hyperclient* client, const char* description);\nhyperclientAddSpace :: HyperclientPtr -> ByteString -> IO HyperclientReturnCode\nhyperclientAddSpace client d = withCBString d $ \\description -> do\n toEnum . fromIntegral <$> {#call hyperclient_add_space #} client description\n\n-- enum hyperclient_returncode\n-- hyperclient_rm_space(struct hyperclient* client, const char* space);\nhyperclientRemoveSpace :: HyperclientPtr -> ByteString -> IO HyperclientReturnCode\nhyperclientRemoveSpace client s = withCBString s $ \\space -> do\n toEnum . fromIntegral <$> {#call hyperclient_rm_space #} client space\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 -> CString -> CString -> Int64\n -> IO (HyperclientHandle, HyperclientReturnCode, AttributeList) \nhyperclientGet client space key keySize = do\n alloca $ \\returnCodePtr ->\n alloca $ \\attributePtrPtr ->\n alloca $ \\attributeSizePtr -> do\n result <- {#call hyperclient_get#} \n client\n space key (fromIntegral keySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n attributePtr <- peek attributePtrPtr\n attributeSize <- fromIntegral <$> peek attributeSizePtr \n attributes <- fromHyperDexAttributeList attributePtr attributeSize\n return (toHyperclientHandle result, returnCode, attributes)\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 -> CString -> CString -> Int64\n -> AttributeList\n -> IO (HyperclientHandle, HyperclientReturnCode)\nhyperclientPut client space key keySize attributes = do\n alloca $ \\returnCodePtr -> do\n let attributePtr = attributeListPointer attributes\n attributeSize = attributeListSize attributes\n result <- {# call hyperclient_put #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (toHyperclientHandle 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 -> CString -> CString -> Int64\n -> AttributeList\n -> IO (HyperclientHandle, HyperclientReturnCode)\nhyperclientPutIfNotExist client space key keySize attributes = do\n alloca $ \\returnCodePtr -> do\n let attributePtr = attributeListPointer attributes\n attributeSize = attributeListSize attributes\n result <- {# call hyperclient_put_if_not_exist #} \n client\n space key (fromIntegral keySize)\n attributePtr (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (toHyperclientHandle 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 -> CString -> CString -> Int64 \n -> IO (HyperclientHandle, HyperclientReturnCode)\nhyperclientDelete client space key keySize = do\n alloca $ \\returnCodePtr -> do\n result <- {# call hyperclient_del #} \n client\n space key (fromIntegral keySize)\n returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (toHyperclientHandle result, returnCode)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f4a25c3a946bc4dbce62e4af970e54c88161b277","subject":"gstreamer: M.S.G.Core.Types code cleanups","message":"gstreamer: M.S.G.Core.Types code cleanups\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectM(..),\n liftMiniObjectM,\n marshalMiniObjectModify,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Trans\nimport Data.Bits ( shiftL\n , bit\n , (.|.) )\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM (toFlags . fromIntegral) $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype MiniObjectClass miniObjectT =>\n MiniObjectM miniObjectT a =\n MiniObjectM (MiniObjectMRep miniObjectT a)\ntype MiniObjectMRep miniObjectT a = miniObjectT -> IO a\n\ninstance MiniObjectClass miniObjectT =>\n Monad (MiniObjectM miniObjectT) where\n (MiniObjectM aM) >>= fbM =\n MiniObjectM $ \\miniObject ->\n do a <- aM miniObject\n let MiniObjectM bM = fbM a\n bM miniObject\n return a = MiniObjectM $ const $ return a\ninstance MiniObjectClass miniObjectT =>\n MonadIO (MiniObjectM miniObjectT) where\n liftIO aM = MiniObjectM $ const aM\n\nliftMiniObjectM :: MiniObjectClass miniObjectT\n => (miniObjectT -> a)\n -> MiniObjectM miniObjectT a\nliftMiniObjectM f =\n MiniObjectM $ \\miniObject ->\n return $! f miniObject\n\nrunMiniObjectM :: MiniObjectClass miniObjectT\n => Ptr miniObjectT\n -> (ForeignPtr miniObjectT -> miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO a\nrunMiniObjectM ptr cons (MiniObjectM action) =\n do object <- liftM cons $ newForeignPtr_ ptr\n action object\n\nmarshalMiniObjectModify :: MiniObjectClass miniObjectT\n => IO (Ptr miniObjectT)\n -> MiniObjectM miniObjectT a\n -> IO (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject (MiniObjectM action) =\n do ptr <- mkMiniObject >>= cMiniObjectMakeWritable . castPtr\n object <- liftM MiniObject $ newForeignPtr_ $ castPtr ptr\n result <- action $ unsafeCastMiniObject object\n object' <- takeMiniObject $ castPtr ptr\n return (unsafeCastMiniObject object', result)\nforeign import ccall unsafe \"gst_mini_object_make_writable\"\n cMiniObjectMakeWritable :: Ptr MiniObject\n -> IO (Ptr MiniObject)\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n toFlags $ fromIntegral $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => MiniObjectM miniObjectT [flagsT]\nmkMiniObjectGetFlagsM =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n liftM cToFlags $ cMiniObjectGetFlags cMiniObject\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectSetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectSetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT)\n => [flagsT]\n -> MiniObjectM miniObjectT ()\nmkMiniObjectUnsetFlagsM flags =\n MiniObjectM $ \\miniObject ->\n withMiniObject (toMiniObject miniObject) $ \\cMiniObject ->\n cMiniObjectUnsetFlags cMiniObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (toFlags $ fromIntegral flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"10c1b57cf1fac33bb3b029ed56330879f4533d48","subject":"a convencience function to get everything working nicely :)","message":"a convencience function to get everything working nicely :)\n","repos":"noinia\/hlibrsync","old_file":"src\/Network\/LibRSync\/Internal.chs","new_file":"src\/Network\/LibRSync\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface,\n EmptyDataDecls\n #-}\nmodule Network.LibRSync.Internal where\n\nimport Data.ByteString\nimport Data.Conduit\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\nimport Foreign.Marshal.Alloc\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \"internal.h\"\n\n-- #include \"..\/..\/..\/c_src\/internal.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ndata CInMemoryBuffer = CInMemoryBuffer (Ptr Char) CSize CSize\n\n{#pointer *inMemoryBuffer_t as CInMemoryBufferPtr -> CInMemoryBuffer #}\n\n\ngetData :: CInMemoryBuffer -> IO ByteString\ngetData (CInMemoryBuffer xs _ s) = packCStringLen (xs,s)\n\n\n\n\n-- data CRSFileBuf = CRSFileBuf (Ptr CFile) CSize\n\n-- {#pointer *rs_filebuf_t as CRSFileBufPtr -> CRSFileBuf #}\n\ndata CJob\ndata CBuffers\ndata CRSFileBuf\n\ndata CRSyncSourceState = CRSyncSourceState { f :: Ptr CFile\n , job :: Ptr CJob\n , buf :: Ptr CBuffers\n , inBuf :: Ptr CRSFileBuf\n , outputBuf :: CInMemoryBufferPtr\n }\n\ninstance Storable CRSyncSourceState where\n sizeOf _ = {#sizeof rsyncSourceState_t #}\n alignment = undefined\n peek = undefined\n poke = undefined\n\n\n{#pointer *rsyncSourceState_t as CRSyncSourceStatePtr -> CRSyncSourceState #}\n\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype RSyncSourceState = CRSyncSourceStatePtr\n\ntype Signature = ByteString\n\n\nstartSignature :: FilePath -> IO RSyncSourceState\nstartSignature path = do\n state <- malloc :: IO (Ptr CRSyncSourceState)\n rsres <- cStartSignature path state\n return state\n -- TODO: check what to do with rsres\n -- case rsres of\n -- RsDone ->\n\nendSignature :: RSyncSourceState -> IO ()\nendSignature state = cEndSignature state >> free state\n\nsignatureSource :: MonadResource m => RSyncSourceState -> Source m Signature\nsignatureSource state = undefined -- do\n -- (CInMemoryBuffer xs size inUse) <- {#get inMemorybuffer->outputBuf-> state\n\n\n\n\n\n\n\n{#fun unsafe startSignature as cStartSignature\n { `String' -- FilePath\n , id `CRSyncSourceStatePtr'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe signatureChunk as cSignatureChunk\n { id `CRSyncSourceStatePtr'\n , `Bool'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe endSignature as cEndSignature\n { id `CRSyncSourceStatePtr'\n } -> `()'\n #}\n\n\n-- type Signature = ByteString\n\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface,\n EmptyDataDecls\n #-}\nmodule Network.LibRSync.Internal where\n\nimport Data.ByteString\nimport Data.Conduit\n\nimport System.IO\nimport GHC.IO.Handle\nimport System.Posix.IO\nimport System.Posix.Types\n\nimport Foreign\nimport Foreign.Marshal.Alloc\n-- import Foreign.Ptr\nimport Foreign.C.String\nimport Foreign.C.Types\n-- import Foreign.Storable\n\n#include \"internal.h\"\n\n-- #include \"..\/..\/..\/c_src\/internal.h\"\n\n--------------------------------------------------------------------------------\n-- | The CTypes\n\ndata CInMemoryBuffer = CInMemoryBuffer (Ptr Char) CSize CSize\n\n{#pointer *inMemoryBuffer_t as CInMemoryBufferPtr -> CInMemoryBuffer #}\n\n-- data CRSFileBuf = CRSFileBuf (Ptr CFile) CSize\n\n-- {#pointer *rs_filebuf_t as CRSFileBufPtr -> CRSFileBuf #}\n\ndata CJob\ndata CBuffers\ndata CRSFileBuf\n\ndata CRSyncSourceState = CRSyncSourceState { f :: Ptr CFile\n , job :: Ptr CJob\n , buf :: Ptr CBuffers\n , inBuf :: Ptr CRSFileBuf\n , outputBuf :: CInMemoryBufferPtr\n }\n\ninstance Storable CRSyncSourceState where\n sizeOf _ = {#sizeof rsyncSourceState_t #}\n alignment = undefined\n peek = undefined\n poke = undefined\n\n\n{#pointer *rsyncSourceState_t as CRSyncSourceStatePtr -> CRSyncSourceState #}\n\n\n-- data BlockSig\n-- {#pointer *rs_block_sig_t as BlockSigPtr -> BlockSig #}\n\n\n-- type CSignature = Ptr CFile\n\n-- -- | The Signature type\n-- {#pointer *rs_signature_t as SignaturePtr -> CSignature #}\n\n-- | The results type\n{#enum rs_result as Result {underscoreToCase} deriving (Eq, Show)#}\n\n--------------------------------------------------------------------------------\n-- | Generating Signatures\n\ntype RSyncSourceState = CRSyncSourceStatePtr\n\ntype Signature = ByteString\n\n\nstartSignature :: FilePath -> IO RSyncSourceState\nstartSignature path = do\n state <- malloc :: IO (Ptr CRSyncSourceState)\n rsres <- cStartSignature path state\n return state\n -- TODO: check what to do with rsres\n -- case rsres of\n -- RsDone ->\n\nendSignature :: RSyncSourceState -> IO ()\nendSignature state = cEndSignature state >> free state\n\nsignatureSource :: MonadResource m => RSyncSourceState -> Source m Signature\nsignatureSource state = undefined -- do\n -- (CInMemoryBuffer xs size inUse) <- {#get inMemorybuffer->outputBuf-> state\n\n\n\n\n\n\n\n{#fun unsafe startSignature as cStartSignature\n { `String' -- FilePath\n , id `CRSyncSourceStatePtr'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe signatureChunk as cSignatureChunk\n { id `CRSyncSourceStatePtr'\n , `Bool'\n } -> `Result' cIntToEnum\n #}\n\n{#fun unsafe endSignature as cEndSignature\n { id `CRSyncSourceStatePtr'\n } -> `()'\n #}\n\n\n-- type Signature = ByteString\n\n\n--------------------------------------------------------------------------------\n-- | Delta\n\n\n--------------------------------------------------------------------------------\n-- | Patch\n\n\n--------------------------------------------------------------------------------\n-- | Helper functions\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"a37c208fd6803f5dec5de6a89451fe3066946c10","subject":"Update documentation for 'getMode'.","message":"Update documentation for 'getMode'.\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' ('Modes')\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 (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","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"e9588855fed9d22bb4339d4aa91483e4435a443c","subject":"gnomevfs: add function S.G.V.Volume.volumeUnmount","message":"gnomevfs: add function S.G.V.Volume.volumeUnmount\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/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":"36aa6ead964b6d535b7305380b851bde1c8fe003","subject":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM","message":"gstreamer: M.S.G.Core.Types: export mkCaps & unCaps, document MiniObjectM\n\ndarcs-hash:20080116191424-21862-90cb074dbea43c6e63b14b5a45868565794c3f96.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"098bf741747e2a16ef69fe839986a37addad01a3","subject":"Fix #5 non-deterministic solution (GC).","message":"Fix #5 non-deterministic solution (GC).\n\nThe solution array pointer was being read from the C model and then copied to a\nStorable.Vector in Haskell.\nHowever, if the C model was garbage collected after the array pointer\nwas read, but before the array was copied, the array became invalid, and\ninvalid elements were copied into the Storable.Vector.\nFortunately the solution is simple. We just need to touch the foreign pointer\nafter reading the array, to keep it from being collected.\n","repos":"amosr\/limp-cbc,amosr\/limp-cbc,amosr\/limp-cbc","old_file":"src\/Numeric\/Limp\/Solvers\/Cbc\/Internal\/Foreign.chs","new_file":"src\/Numeric\/Limp\/Solvers\/Cbc\/Internal\/Foreign.chs","new_contents":"{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-do-bind -fno-warn-unused-matches #-}\nmodule Numeric.Limp.Solvers.Cbc.Internal.Foreign where\n\nimport Foreign\nimport Foreign.C\n\nimport Control.Applicative\n\nimport qualified Data.Vector.Storable as V\nimport Data.Vector.Storable (Vector)\n\nimport Unsafe.Coerce\n\n#include \"Cbc.h\"\n\n\nnewtype CbcModel = CbcModel (ForeignPtr CbcModel)\n{#pointer *CbcModel as CbcModelPtr -> CbcModel #}\n\n\nforeign import ccall \"&freeModel\"\n cbcDeleteModel_funptr :: FunPtr (Ptr CbcModel -> IO ())\n\nmkCbcModel :: CbcModelPtr -> IO CbcModel\nmkCbcModel p\n = CbcModel <$> newForeignPtr cbcDeleteModel_funptr p\n\nwithCbcModel :: CbcModel -> (CbcModelPtr -> IO b) -> IO b\nwithCbcModel (CbcModel ptr) f\n = do withForeignPtr ptr f\n\n{#fun newModel as ^\n { } -> `CbcModel' mkCbcModel* #}\n\nwithVecI :: Vector Int -> (Ptr CInt -> IO b) -> IO b\nwithVecI v f\n = V.unsafeWith (V.map fromIntegral v) f\n\nwithVecD :: Vector Double -> (Ptr CDouble -> IO b) -> IO b\nwithVecD v f\n = V.unsafeWith v (f . castPtr)\n\n\n{#fun loadProblem as ^\n { withCbcModel* `CbcModel'\n\n , `Int' -- # rows\n , `Int' -- # columns\n\n , withVecI* `Vector Int' -- starts\n , withVecI* `Vector Int' -- indices\n , withVecD* `Vector Double' -- values\n\n , withVecD* `Vector Double' -- col lower bounds\n , withVecD* `Vector Double' -- col upper bounds\n\n , withVecD* `Vector Double' -- objective coefficients\n , withVecD* `Vector Double' -- row lower bounds\n , withVecD* `Vector Double' -- row upper bounds\n }\n -> `()' #}\n\n\n{#fun setInteger as ^\n { withCbcModel* `CbcModel'\n , `Int' }\n -> `()' #}\n\n\n{#fun branchAndBound as ^\n { withCbcModel* `CbcModel' }\n -> `()' #}\n\n\ngetSolution :: CbcModel -> IO (Vector Double)\ngetSolution m@(CbcModel fp)\n = do ncols <- fromIntegral <$> withCbcModel m {#call getNumCols#}\n vd <- unsafeCoerce <$> withCbcModel m {#call getBestSolution#}\n arr <- V.generateM ncols (peekElemOff vd)\n\n -- The model owns the array, so ensure we keep it around until after we've read the whole array\n touchForeignPtr fp\n return arr\n\n\n{#fun setObjSense as ^\n { withCbcModel* `CbcModel'\n , `Double' }\n -> `()' #}\n\n\n{#fun setLogLevel as ^\n { withCbcModel* `CbcModel'\n , `Int' }\n -> `()' #}\n\n\n{#fun isProvenInfeasible as ^\n { withCbcModel* `CbcModel' }\n -> `Bool' #}\n\n\n{#fun pure getCoinDblMax as ^\n { } -> `Double' #}\n\n","old_contents":"{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-do-bind -fno-warn-unused-matches #-}\nmodule Numeric.Limp.Solvers.Cbc.Internal.Foreign where\n\nimport Foreign\nimport Foreign.C\n\nimport Control.Applicative\n\nimport qualified Data.Vector.Storable as V\nimport Data.Vector.Storable (Vector)\n\nimport Unsafe.Coerce\n\n#include \"Cbc.h\"\n\n\nnewtype CbcModel = CbcModel (ForeignPtr CbcModel)\n{#pointer *CbcModel as CbcModelPtr -> CbcModel #}\n\n\nforeign import ccall \"&freeModel\"\n cbcDeleteModel_funptr :: FunPtr (Ptr CbcModel -> IO ())\n\nmkCbcModel :: CbcModelPtr -> IO CbcModel\nmkCbcModel p\n = CbcModel <$> newForeignPtr cbcDeleteModel_funptr p\n\nwithCbcModel :: CbcModel -> (CbcModelPtr -> IO b) -> IO b\nwithCbcModel (CbcModel ptr) f\n = do withForeignPtr ptr f\n\n{#fun newModel as ^\n { } -> `CbcModel' mkCbcModel* #}\n\nwithVecI :: Vector Int -> (Ptr CInt -> IO b) -> IO b\nwithVecI v f\n = V.unsafeWith (V.map fromIntegral v) f\n\nwithVecD :: Vector Double -> (Ptr CDouble -> IO b) -> IO b\nwithVecD v f\n = V.unsafeWith v (f . castPtr)\n\n\n{#fun loadProblem as ^\n { withCbcModel* `CbcModel'\n\n , `Int' -- # rows\n , `Int' -- # columns\n\n , withVecI* `Vector Int' -- starts\n , withVecI* `Vector Int' -- indices\n , withVecD* `Vector Double' -- values\n\n , withVecD* `Vector Double' -- col lower bounds\n , withVecD* `Vector Double' -- col upper bounds\n\n , withVecD* `Vector Double' -- objective coefficients\n , withVecD* `Vector Double' -- row lower bounds\n , withVecD* `Vector Double' -- row upper bounds\n }\n -> `()' #}\n\n\n{#fun setInteger as ^\n { withCbcModel* `CbcModel'\n , `Int' }\n -> `()' #}\n\n\n{#fun branchAndBound as ^\n { withCbcModel* `CbcModel' }\n -> `()' #}\n\n\ngetSolution :: CbcModel -> IO (Vector Double)\ngetSolution m\n = do ncols <- fromIntegral <$> withCbcModel m {#call getNumCols#}\n vd <- unsafeCoerce <$> withCbcModel m {#call getBestSolution#}\n\n V.generateM ncols (peekElemOff vd)\n\n\n{#fun setObjSense as ^\n { withCbcModel* `CbcModel'\n , `Double' }\n -> `()' #}\n\n\n{#fun setLogLevel as ^\n { withCbcModel* `CbcModel'\n , `Int' }\n -> `()' #}\n\n\n{#fun isProvenInfeasible as ^\n { withCbcModel* `CbcModel' }\n -> `Bool' #}\n\n\n{#fun pure getCoinDblMax as ^\n { } -> `Double' #}\n\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"} {"commit":"4b9808f8c31965ce2857bb4266bc1012af5d0e1e","subject":"Add yet another property for read access.","message":"Add yet another property for read access.\n","repos":"gtk2hs\/gtksourceview,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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n newAttrFromMaybeStringProperty,\n readAttrFromMaybeStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n readAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nreadAttrFromMaybeStringProperty :: GObjectClass gobj => String -> ReadAttr gobj (Maybe String)\nreadAttrFromMaybeStringProperty propName =\n readAttr (objectGetPropertyMaybeString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject gtype propName)\n \nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n\nreadAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> ReadAttr gobj gobj'\nreadAttrFromObjectProperty propName gtype =\n readAttr (objectGetPropertyGObject 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-- 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 objectSetPropertyInt64,\n objectGetPropertyInt64,\n objectSetPropertyUInt64,\n objectGetPropertyUInt64,\n objectSetPropertyChar,\n objectGetPropertyChar,\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 newAttrFromCharProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n readAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n newAttrFromMaybeStringProperty,\n readAttrFromMaybeStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n readAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n newAttrFromMaybeObjectProperty,\n \n -- TODO: do not export these once we dump the old TreeList API:\n objectGetPropertyInternal,\n objectSetPropertyInternal,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags)\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\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\nobjectSetPropertyInt64 :: GObjectClass gobj => String -> gobj -> Int64 -> IO ()\nobjectSetPropertyInt64 = objectSetPropertyInternal GType.int64 valueSetInt64\n\nobjectGetPropertyInt64 :: GObjectClass gobj => String -> gobj -> IO Int64\nobjectGetPropertyInt64 = objectGetPropertyInternal GType.int64 valueGetInt64\n\nobjectSetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> Word64 -> IO ()\nobjectSetPropertyUInt64 = objectSetPropertyInternal GType.uint64 (\\gv v -> valueSetUInt64 gv (fromIntegral v))\n\nobjectGetPropertyUInt64 :: GObjectClass gobj => String -> gobj -> IO Word64\nobjectGetPropertyUInt64 = objectGetPropertyInternal GType.uint64 (\\gv -> liftM fromIntegral $ valueGetUInt64 gv)\n\nobjectSetPropertyChar :: GObjectClass gobj => String -> gobj -> Char -> IO ()\nobjectSetPropertyChar = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral (fromEnum v)))\n\nobjectGetPropertyChar :: GObjectClass gobj => String -> gobj -> IO Char\nobjectGetPropertyChar = objectGetPropertyInternal GType.uint (\\gv -> liftM (toEnum . 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) => GType -> String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags gtype = objectSetPropertyInternal gtype valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => GType -> String -> gobj -> IO [flag]\nobjectGetPropertyFlags gtype = objectGetPropertyInternal gtype 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\nobjectSetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> (Maybe gobj') -> IO ()\nobjectSetPropertyMaybeGObject gtype = objectSetPropertyInternal gtype valueSetMaybeGObject\n\nobjectGetPropertyMaybeGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO (Maybe gobj')\nobjectGetPropertyMaybeGObject gtype = objectGetPropertyInternal gtype valueGetMaybeGObject\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\nnewAttrFromCharProperty :: GObjectClass gobj => String -> Attr gobj Char\nnewAttrFromCharProperty propName =\n newAttr (objectGetPropertyChar propName) (objectSetPropertyChar 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\nreadAttrFromBoolProperty :: GObjectClass gobj => String -> ReadAttr gobj Bool\nreadAttrFromBoolProperty propName =\n readAttr (objectGetPropertyBool 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 -> GType -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName gtype =\n newAttr (objectGetPropertyFlags gtype propName) (objectSetPropertyFlags gtype 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\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nreadAttrFromMaybeStringProperty :: GObjectClass gobj => String -> ReadAttr gobj (Maybe String)\nreadAttrFromMaybeStringProperty propName =\n readAttr (objectGetPropertyMaybeString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (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\nreadAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> String -> GType -> ReadAttr gobj boxed\nreadAttrFromBoxedOpaqueProperty peek propName gtype =\n readAttr (objectGetPropertyBoxedOpaque peek 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\nnewAttrFromMaybeObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj (Maybe gobj') (Maybe gobj'')\nnewAttrFromMaybeObjectProperty propName gtype =\n newAttr (objectGetPropertyMaybeGObject gtype propName) (objectSetPropertyMaybeGObject 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":"85c0b8ebc367f4d043a83bcbd616c5b3d04c0bbd","subject":"gstreamer: M.S.G.Core.Types.chs: staticPadTemplateGet: Control.Monad.>=> not available before ghc 6.8; don't export StaticPadTemplate constructors","message":"gstreamer: M.S.G.Core.Types.chs: staticPadTemplateGet: Control.Monad.>=> not available before ghc 6.8; don't export StaticPadTemplate constructors","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate {-(..)-},\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet staticPadTemplate =\n {# call static_pad_template_get #} staticPadTemplate >>= takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate(..),\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet =\n {# call static_pad_template_get #} >=> takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"6a00379b4aca188aefa7f1302052e6a9ae083e60","subject":"[project @ 2002-10-20 14:29:26 by as49]","message":"[project @ 2002-10-20 14:29:26 by as49]\n\nDocumentation fixes.\n\ndarcs-hash:20021020142926-d90cf-6d42e96a981050c1083f51973c8362bae0441eeb.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/gdk\/Drawable.chs","new_file":"gtk\/gdk\/Drawable.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Drawable@\n--\n-- Author : Axel Simon\n-- Created: 22 September 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/10\/20 14:29:26 $\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-- Drawing primitives.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This module defines drawing primitives that can operate on \n-- @ref data DrawWindow@s, @ref data Pixmap@s and \n-- @ref data Bitmap@s.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if gdk_visuals are implemented, do: get_visual\n-- * if gdk_colormaps are implemented, do: set_colormap, get_colormap\n-- * text drawing functions\n--\nmodule Drawable(\n Drawable,\n DrawableClass,\n castToDrawable,\n drawableGetDepth,\n drawableGetSize,\n drawableGetClipRegion,\n drawableGetVisibleRegion,\n drawPoint,\n drawPoints,\n drawLine,\n drawLines,\n drawSegments,\n drawRectangle,\n drawArc,\n drawPolygon,\n drawDrawable) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport GObject\t(makeNewGObject)\nimport Structs (Point)\n{#import Hierarchy#}\n{#import Region#}\t(Region, makeNewRegion)\n\n{# context lib=\"gtk\" prefix=\"gdk\" #}\n\n-- methods\n\n-- @method drawableGetDepth@ Get the size of pixels.\n--\n-- * Returns the number of bits which are use to store information on each\n-- pixels in this @ref data Drawable@.\n--\ndrawableGetDepth :: DrawableClass d => d -> IO Int\ndrawableGetDepth d = liftM fromIntegral $ \n\t\t {#call unsafe drawable_get_depth#} (toDrawable d)\n\n-- @method drawableGetSize@ Retrieve the size of the @ref type Drawable@.\n--\n-- * The result might not be up-to-date if there are still resizing messages\n-- to be processed.\n--\ndrawableGetSize :: DrawableClass d => d -> IO (Int, Int)\ndrawableGetSize d = alloca $ \\wPtr -> alloca $ \\hPtr -> do\n {#call unsafe drawable_get_size#} (toDrawable d) wPtr hPtr\n (w::{#type gint#}) <- peek wPtr\n (h::{#type gint#}) <- peek hPtr\n return (fromIntegral w, fromIntegral h)\n\n-- @method drawableGetClipRegion@ Determine where not to draw.\n--\n-- * Computes the region of a drawable that potentially can be written\n-- to by drawing primitives. This region will not take into account the\n-- clip region for the GC, and may also not take into account other\n-- factors such as if the window is obscured by other windows, but no\n-- area outside of this region will be affected by drawing primitives.\n--\ndrawableGetClipRegion :: DrawableClass d => d -> IO Region\ndrawableGetClipRegion d = do\n rPtr <- {#call unsafe drawable_get_clip_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawableGetVisibleRegion@ Determine what not to redraw.\n--\n-- * Computes the region of a drawable that is potentially visible.\n-- This does not necessarily take into account if the window is obscured\n-- by other windows, but no area outside of this region is visible.\n--\ndrawableGetVisibleRegion :: DrawableClass d => d -> IO Region\ndrawableGetVisibleRegion d = do\n rPtr <- {#call unsafe drawable_get_visible_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawPoint@ Draw a point into a @ref type Drawable@.\n--\ndrawPoint :: DrawableClass d => d -> GC -> Point -> IO ()\ndrawPoint d gc (x,y) = {#call unsafe draw_point#} (toDrawable d)\n (toGC gc) (fromIntegral x) (fromIntegral y)\n\n\n-- @method drawPoints@ Draw several points into a @ref type Drawable@.\n--\n-- * This function is more efficient than calling @ref method drawPoint@ on\n-- several points.\n--\ndrawPoints :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawPoints d gc points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_points#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawLine@ Draw a line into a @ref type Drawable@.\n--\n-- * The parameters are x1, y1, x2, y2.\n--\n-- * Drawing several separate lines can be done more efficiently by\n-- @ref method drawSegments@.\n--\ndrawLine :: DrawableClass d => d -> GC -> Point -> Point -> IO ()\ndrawLine d gc (x1,y1) (x2,y2) = {#call unsafe draw_line#} (toDrawable d)\n (toGC gc) (fromIntegral x1) (fromIntegral y1) (fromIntegral x2) \n (fromIntegral x2)\n\n-- @method drawLines@ Draw several lines.\n--\n-- * The function uses the current line width, dashing and especially the\n-- joining specification in the graphics context (in contrast to\n-- @ref method drawSegments@.\n--\ndrawLines :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawLines d gc points =\n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_lines#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawSegments@ Draw several unconnected lines.\n--\n-- * This method draws several unrelated lines.\n--\ndrawSegments :: DrawableClass d => d -> GC -> [(Point,Point)] -> IO ()\ndrawSegments d gc pps = withArray (concatMap (\\((x1,y1),(x2,y2)) -> \n [fromIntegral x1, fromIntegral y1, fromIntegral x2, fromIntegral y2])\n pps) $ \\(aPtr :: Ptr {#type gint#}) ->\n {#call unsafe draw_segments#} (toDrawable d) (toGC gc)\n (castPtr aPtr) (fromIntegral (length pps))\n\n-- @method drawRectangle@ Draw a rectangular object.\n--\n-- * Draws a rectangular outline or filled rectangle, using the\n-- foreground color and other attributes of the @ref type GC@.\n--\n-- * A rectangle drawn filled is 1 pixel smaller in both dimensions\n-- than a rectangle outlined. Calling @ref method drawRectangle@ w gc\n-- True 0 0 20 20 results in a filled rectangle 20 pixels wide and 20\n-- pixels high. Calling @ref method drawRectangle@ d gc False 0 0 20 20\n-- results in an outlined rectangle with corners at (0, 0), (0, 20), (20,\n-- 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.\n--\ndrawRectangle :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> IO ()\ndrawRectangle d gc filled x y width height = {#call unsafe draw_rectangle#}\n (toDrawable d) (toGC gc) (fromBool filled) (fromIntegral x)\n (fromIntegral y) (fromIntegral width) (fromIntegral height)\n\n-- @method drawArc@ Draws an arc or a filled 'pie slice'.\n--\n-- * The arc is defined by the bounding rectangle of the entire\n-- ellipse, and the start and end angles of the part of the ellipse to be\n-- drawn.\n--\n-- * The starting angle @ref arg aStart@ is relative to the 3 o'clock\n-- position, counter-clockwise, in 1\/64ths of a degree. @ref arg aEnd@\n-- is measured similarly, but relative to @ref arg aStart@.\n--\ndrawArc :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> Int -> Int -> IO ()\ndrawArc d gc filled x y width height aStart aEnd =\n {#call unsafe draw_arc#} (toDrawable d) (toGC gc) (fromBool filled)\n (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)\n (fromIntegral aStart) (fromIntegral aEnd)\n\n-- @method drawPolygon@ Draws an outlined or filled polygon.\n--\n-- * The polygon is closed automatically, connecting the last point to\n-- the first point if necessary.\n--\ndrawPolygon :: DrawableClass d => d -> GC -> Bool -> [Point] -> IO ()\ndrawPolygon d gc filled points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr::Ptr {#type gint#}) -> {#call unsafe draw_polygon#} (toDrawable d)\n (toGC gc) (fromBool filled) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawDrawable@ Copies another @ref type Drawable@.\n--\n-- * Copies the (width,height) region of the @ref arg src@ at coordinates\n-- (@ref arg xSrc@, @ref arg ySrc@) to coordinates (@ref arg xDest@,\n-- @ref arg yDest@) in the @ref arg dest@. The @ref arg width@ and\/or\n-- @ref arg height@ may be given as -1, in which case the entire source\n-- drawable will be copied.\n--\n-- * Most fields in @ref arg gc@ are not used for this operation, but\n-- notably the clip mask or clip region will be honored. The source and\n-- destination drawables must have the same visual and colormap, or\n-- errors will result. (On X11, failure to match visual\/colormap results\n-- in a BadMatch error from the X server.) A common cause of this\n-- problem is an attempt to draw a bitmap to a color drawable. The way to\n-- draw a bitmap is to set the bitmap as a clip mask on your\n-- @ref type GC@, then use @ref method drawRectangle@ to draw a \n-- rectangle clipped to the bitmap.\n--\ndrawDrawable :: (DrawableClass src, DrawableClass dest) => \n\t\tdest -> GC -> src -> Int -> Int -> Int -> Int -> \n\t\tInt -> Int -> IO ()\ndrawDrawable dest gc src xSrc ySrc xDest yDest width height =\n {#call unsafe draw_drawable#} (toDrawable dest) (toGC gc)\n (toDrawable src)\n (fromIntegral xSrc) (fromIntegral ySrc) (fromIntegral xDest)\n (fromIntegral yDest) (fromIntegral width) (fromIntegral height)\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Drawable@\n--\n-- Author : Axel Simon\n-- Created: 22 September 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2002\/10\/06 16:14:07 $\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-- Drawing primitives.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This module defines drawing primitives that can operate on \n-- @ref object DrawWindow@s, @ref object Pixmap@s and \n-- @ref object Bitmap@s.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if gdk_visuals are implemented, do: get_visual\n-- * if gdk_colormaps are implemented, do: set_colormap, get_colormap\n-- * text drawing functions\n--\nmodule Drawable(\n Drawable,\n DrawableClass,\n castToDrawable,\n drawableGetDepth,\n drawableGetSize,\n drawableGetClipRegion,\n drawableGetVisibleRegion,\n drawPoint,\n drawPoints,\n drawLine,\n drawLines,\n drawSegments,\n drawRectangle,\n drawArc,\n drawPolygon,\n drawDrawable) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport GObject\t(makeNewGObject)\nimport Structs (Point)\n{#import Hierarchy#}\n{#import Region#}\t(Region, makeNewRegion)\n\n{# context lib=\"gtk\" prefix=\"gdk\" #}\n\n-- methods\n\n-- @method drawableGetDepth@ Get the size of pixels.\n--\n-- * Returns the number of bits which are use to store information on each\n-- pixels in this @ref object Drawable@.\n--\ndrawableGetDepth :: DrawableClass d => d -> IO Int\ndrawableGetDepth d = liftM fromIntegral $ \n\t\t {#call unsafe drawable_get_depth#} (toDrawable d)\n\n-- @method drawableGetSize@ Retrieve the size of the @ref type Drawable@.\n--\n-- * The result might not be up-to-date if there are still resizing messages\n-- to be processed.\n--\ndrawableGetSize :: DrawableClass d => d -> IO (Int, Int)\ndrawableGetSize d = alloca $ \\wPtr -> alloca $ \\hPtr -> do\n {#call unsafe drawable_get_size#} (toDrawable d) wPtr hPtr\n (w::{#type gint#}) <- peek wPtr\n (h::{#type gint#}) <- peek hPtr\n return (fromIntegral w, fromIntegral h)\n\n-- @method drawableGetClipRegion@ Determine where not to draw.\n--\n-- * Computes the region of a drawable that potentially can be written\n-- to by drawing primitives. This region will not take into account the\n-- clip region for the GC, and may also not take into account other\n-- factors such as if the window is obscured by other windows, but no\n-- area outside of this region will be affected by drawing primitives.\n--\ndrawableGetClipRegion :: DrawableClass d => d -> IO Region\ndrawableGetClipRegion d = do\n rPtr <- {#call unsafe drawable_get_clip_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawableGetVisibleRegion@ Determine what not to redraw.\n--\n-- * Computes the region of a drawable that is potentially visible.\n-- This does not necessarily take into account if the window is obscured\n-- by other windows, but no area outside of this region is visible.\n--\ndrawableGetVisibleRegion :: DrawableClass d => d -> IO Region\ndrawableGetVisibleRegion d = do\n rPtr <- {#call unsafe drawable_get_visible_region#} (toDrawable d)\n makeNewRegion rPtr\n\n-- @method drawPoint@ Draw a point into a @ref type Drawable@.\n--\ndrawPoint :: DrawableClass d => d -> GC -> Point -> IO ()\ndrawPoint d gc (x,y) = {#call unsafe draw_point#} (toDrawable d)\n (toGC gc) (fromIntegral x) (fromIntegral y)\n\n\n-- @method drawPoints@ Draw several points into a @ref type Drawable@.\n--\n-- * This function is more efficient than calling @ref method drawPoint@ on\n-- several points.\n--\ndrawPoints :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawPoints d gc points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_points#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawLine@ Draw a line into a @ref type Drawable@.\n--\n-- * The parameters are x1, y1, x2, y2.\n--\n-- * Drawing several separate lines can be done more efficiently by\n-- @ref method drawSegments@.\n--\ndrawLine :: DrawableClass d => d -> GC -> Point -> Point -> IO ()\ndrawLine d gc (x1,y1) (x2,y2) = {#call unsafe draw_line#} (toDrawable d)\n (toGC gc) (fromIntegral x1) (fromIntegral y1) (fromIntegral x2) \n (fromIntegral x2)\n\n-- @method drawLines@ Draw several lines.\n--\n-- * The function uses the current line width, dashing and especially the\n-- joining specification in the graphics context (in contrast to\n-- @ref method drawSegments@.\n--\ndrawLines :: DrawableClass d => d -> GC -> [Point] -> IO ()\ndrawLines d gc points =\n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr :: Ptr {#type gint#}) -> {#call unsafe draw_lines#} (toDrawable d)\n (toGC gc) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawSegments@ Draw several unconnected lines.\n--\n-- * This method draws several unrelated lines.\n--\ndrawSegments :: DrawableClass d => d -> GC -> [(Point,Point)] -> IO ()\ndrawSegments d gc pps = withArray (concatMap (\\((x1,y1),(x2,y2)) -> \n [fromIntegral x1, fromIntegral y1, fromIntegral x2, fromIntegral y2])\n pps) $ \\(aPtr :: Ptr {#type gint#}) ->\n {#call unsafe draw_segments#} (toDrawable d) (toGC gc)\n (castPtr aPtr) (fromIntegral (length pps))\n\n-- @method drawRectangle@ Draw a rectangular object.\n--\n-- * Draws a rectangular outline or filled rectangle, using the\n-- foreground color and other attributes of the @ref type GC@.\n--\n-- * A rectangle drawn filled is 1 pixel smaller in both dimensions\n-- than a rectangle outlined. Calling @ref method drawRectangle@ w gc\n-- True 0 0 20 20 results in a filled rectangle 20 pixels wide and 20\n-- pixels high. Calling @ref method drawRectangle@ d gc False 0 0 20 20\n-- results in an outlined rectangle with corners at (0, 0), (0, 20), (20,\n-- 20), and (20, 0), which makes it 21 pixels wide and 21 pixels high.\n--\ndrawRectangle :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> IO ()\ndrawRectangle d gc filled x y width height = {#call unsafe draw_rectangle#}\n (toDrawable d) (toGC gc) (fromBool filled) (fromIntegral x)\n (fromIntegral y) (fromIntegral width) (fromIntegral height)\n\n-- @method drawArc@ Draws an arc or a filled 'pie slice'.\n--\n-- * The arc is defined by the bounding rectangle of the entire\n-- ellipse, and the start and end angles of the part of the ellipse to be\n-- drawn.\n--\n-- * The starting angle @ref arg aStart@ is relative to the 3 o'clock\n-- position, counter-clockwise, in 1\/64ths of a degree. @ref arg aEnd@\n-- is measured similarly, but relative to @ref arg aStart@.\n--\ndrawArc :: DrawableClass d => d -> GC -> Bool -> Int -> Int ->\n\t\t\t\t Int -> Int -> Int -> Int -> IO ()\ndrawArc d gc filled x y width height aStart aEnd =\n {#call unsafe draw_arc#} (toDrawable d) (toGC gc) (fromBool filled)\n (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)\n (fromIntegral aStart) (fromIntegral aEnd)\n\n-- @method drawPolygon@ Draws an outlined or filled polygon.\n--\n-- * The polygon is closed automatically, connecting the last point to\n-- the first point if necessary.\n--\ndrawPolygon :: DrawableClass d => d -> GC -> Bool -> [Point] -> IO ()\ndrawPolygon d gc filled points = \n withArray (concatMap (\\(x,y) -> [fromIntegral x, fromIntegral y]) points) $\n \\(aPtr::Ptr {#type gint#}) -> {#call unsafe draw_polygon#} (toDrawable d)\n (toGC gc) (fromBool filled) (castPtr aPtr) (fromIntegral (length points))\n\n-- @method drawDrawable@ Copies another @ref type Drawable@.\n--\n-- * Copies the (width,height) region of the @ref arg src@ at coordinates\n-- (@ref arg xSrc@, @ref arg ySrc@) to coordinates (@ref arg xDest@, @ref\n-- arg yDest@) in the @ref arg dest@. The @ref arg width@ and\/or @ref arg\n-- height@ may be given as -1, in which case the entire source drawable\n-- will be copied.\n--\n-- * Most fields in @ref arg gc@ are not used for this operation, but\n-- notably the clip mask or clip region will be honored. The source and\n-- destination drawables must have the same visual and colormap, or\n-- errors will result. (On X11, failure to match visual\/colormap results\n-- in a BadMatch error from the X server.) A common cause of this\n-- problem is an attempt to draw a bitmap to a color drawable. The way to\n-- draw a bitmap is to set the bitmap as a clip mask on your\n-- @ref type GC@, then use @ref method drawRectangle@ to draw a \n-- rectangle clipped to the bitmap.\n--\ndrawDrawable :: (DrawableClass src, DrawableClass dest) => \n\t\tdest -> GC -> src -> Int -> Int -> Int -> Int -> \n\t\tInt -> Int -> IO ()\ndrawDrawable dest gc src xSrc ySrc xDest yDest width height =\n {#call unsafe draw_drawable#} (toDrawable dest) (toGC gc)\n (toDrawable src)\n (fromIntegral xSrc) (fromIntegral ySrc) (fromIntegral xDest)\n (fromIntegral yDest) (fromIntegral width) (fromIntegral height)\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"7fed311ed7b030345bcfdd84c63cb19783af733c","subject":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)","message":"gtksourceview2: typo: can-redo -> can-undo (for sourceBufferCanUndo)\n\ndarcs-hash:20090112043017-21862-ca1d5baaa7ad742f2547652f97986bedb4252049.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_file":"gtksourceview2\/Graphics\/UI\/Gtk\/SourceView\/SourceBuffer.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-undo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceBuffer\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) 2003-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.SourceBuffer (\n SourceBuffer,\n SourceBufferClass,\n castToSourceBuffer,\n sourceBufferNew,\n sourceBufferNewWithLanguage,\n sourceBufferSetHighlightSyntax,\n sourceBufferGetHighlightSyntax,\n sourceBufferSetLanguage,\n sourceBufferGetLanguage,\n sourceBufferSetHighlightMatchingBrackets,\n sourceBufferGetHighlightMatchingBrackets,\n sourceBufferSetStyleScheme,\n sourceBufferGetStyleScheme,\n sourceBufferSetMaxUndoLevels,\n sourceBufferGetMaxUndoLevels,\n sourceBufferGetCanUndo,\n sourceBufferGetCanRedo,\n sourceBufferUndo,\n sourceBufferRedo,\n sourceBufferBeginNotUndoableAction,\n sourceBufferEndNotUndoableAction,\n sourceBufferCreateSourceMark,\n sourceBufferEnsureHighlight,\n sourceBufferCanRedo,\n sourceBufferCanUndo,\n sourceBufferHighlightMatchingBrackets,\n sourceBufferHighlightSyntax,\n sourceBufferLanguage,\n sourceBufferSourceStyleScheme,\n sourceBufferHighlightUpdated\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject,\n\t\t\t\t\t makeNewGObject)\n{#import System.Glib.Properties#}\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n\nimport Graphics.UI.Gtk.SourceView.SourceMark\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | Create a new 'SourceBuffer', possibly\n-- taking a 'TextTagTable'.\n--\nsourceBufferNew :: Maybe TextTagTable -> IO SourceBuffer\nsourceBufferNew tt = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new#} \n (fromMaybe (mkTextTagTable nullForeignPtr) tt)\n\n-- | Create a new 'SourceBuffer'\n-- with a 'SourceLanguage'.\n--\nsourceBufferNewWithLanguage :: SourceLanguage -> IO SourceBuffer\nsourceBufferNewWithLanguage lang = constructNewGObject mkSourceBuffer $\n {#call unsafe source_buffer_new_with_language#} lang\n\n-- | \n--\nsourceBufferSetHighlightSyntax :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightSyntax sb newVal =\n {#call unsafe source_buffer_set_highlight_syntax#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightSyntax :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightSyntax sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_syntax#} sb\n\n-- | \n--\nsourceBufferSetLanguage :: SourceBuffer -> SourceLanguage -> IO ()\nsourceBufferSetLanguage sb lang =\n {#call unsafe source_buffer_set_language#} sb lang\n \n-- | \n--\nsourceBufferGetLanguage :: SourceBuffer -> IO SourceLanguage\nsourceBufferGetLanguage sb = makeNewGObject mkSourceLanguage $\n {#call unsafe source_buffer_get_language#} sb\n\n-- | \n--\nsourceBufferSetHighlightMatchingBrackets :: SourceBuffer -> Bool -> IO ()\nsourceBufferSetHighlightMatchingBrackets sb newVal =\n {#call unsafe source_buffer_set_highlight_matching_brackets#} sb (fromBool newVal)\n \n-- | \n--\nsourceBufferGetHighlightMatchingBrackets :: SourceBuffer -> IO Bool \nsourceBufferGetHighlightMatchingBrackets sb = liftM toBool $\n {#call unsafe source_buffer_get_highlight_matching_brackets#} sb\n\n-- |\n-- \nsourceBufferSetStyleScheme :: SourceBuffer -> SourceStyleScheme -> IO ()\nsourceBufferSetStyleScheme sb sss =\n {#call unsafe source_buffer_set_style_scheme#} sb sss\n\n-- |\n-- \nsourceBufferGetStyleScheme :: SourceBuffer -> IO SourceStyleScheme\nsourceBufferGetStyleScheme sb = makeNewGObject mkSourceStyleScheme $\n {#call unsafe source_buffer_get_style_scheme#} sb\n\n-- | \n--\nsourceBufferSetMaxUndoLevels :: SourceBuffer -> Int -> IO ()\nsourceBufferSetMaxUndoLevels sb newVal =\n {#call unsafe source_buffer_set_max_undo_levels#} sb (fromIntegral newVal)\n \n-- | \n--\nsourceBufferGetMaxUndoLevels :: SourceBuffer -> IO Int\nsourceBufferGetMaxUndoLevels sb = liftM fromIntegral $\n {#call unsafe source_buffer_get_max_undo_levels#} sb\n\n-- | \n--\nsourceBufferGetCanUndo :: SourceBuffer -> IO Bool\nsourceBufferGetCanUndo sb = liftM toBool $\n {#call unsafe source_buffer_can_undo#} sb\n \n-- | \n--\nsourceBufferGetCanRedo :: SourceBuffer -> IO Bool\nsourceBufferGetCanRedo sb = liftM toBool $\n {#call unsafe source_buffer_can_redo#} sb\n\n-- | \n--\nsourceBufferUndo :: SourceBuffer -> IO ()\nsourceBufferUndo sb =\n {#call source_buffer_undo#} sb\n \n-- | \n--\nsourceBufferRedo :: SourceBuffer -> IO ()\nsourceBufferRedo sb =\n {#call source_buffer_redo#} sb\n\n-- | \n--\nsourceBufferBeginNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferBeginNotUndoableAction sb =\n {#call source_buffer_begin_not_undoable_action#} sb\n \n-- | \n--\nsourceBufferEndNotUndoableAction :: SourceBuffer -> IO ()\nsourceBufferEndNotUndoableAction sb =\n {#call source_buffer_end_not_undoable_action#} sb\n\n-- | Creates a marker in the buffer of the given type.\n--\n-- * A marker is\n-- semantically very similar to a 'Graphics.UI.Gtk.Multiline.TextMark',\n-- except it has a type\n-- which is used by the 'SourceView' displaying the buffer to show a\n-- pixmap on the left margin, at the line the marker is in. Because\n-- of this, a marker is generally associated to a line and not a\n-- character position. Markers are also accessible through a position\n-- or range in the buffer.\n--\n-- * Markers are implemented using 'Graphics.UI.Gtk.Multiline.TextMark',\n-- so all characteristics\n-- and restrictions to marks apply to markers too. These includes\n-- life cycle issues and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkSet'\n-- and 'Graphics.UI.Gtk.Multiline.TextMark.onMarkDeleted' signal\n-- emissions.\n--\n-- * Like a 'Graphics.UI.Gtk.Multiline.TextMark', a 'SourceMarker'\n-- can be anonymous if the\n-- passed name is @Nothing@. Also, the buffer owns the markers so you\n-- shouldn't unreference it.\n\nsourceBufferCreateSourceMark :: SourceBuffer -- the buffer\n -> Maybe String -- the name of the mark\n -> String -- the category of the mark\n -> TextIter -> IO SourceMark\nsourceBufferCreateSourceMark sb name category iter =\n makeNewGObject mkSourceMark $\n maybeWith withCString name $ \\strPtr1 ->\n withCString category $ \\strPtr2 ->\n {#call source_buffer_create_source_mark#} sb strPtr1 strPtr2 iter\n\n-- |\n-- \nsourceBufferEnsureHighlight :: SourceBuffer -> TextIter -> TextIter -> IO ()\nsourceBufferEnsureHighlight sb start end =\n {#call source_buffer_ensure_highlight#} sb start end\n\n-- |\n-- \nsourceBufferCanRedo :: ReadAttr SourceBuffer Bool\nsourceBufferCanRedo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n-- \nsourceBufferCanUndo :: ReadAttr SourceBuffer Bool\nsourceBufferCanUndo = readAttrFromBoolProperty \"can-redo\"\n\n-- |\n--\nsourceBufferHighlightMatchingBrackets :: Attr SourceBuffer Bool\nsourceBufferHighlightMatchingBrackets = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n--\nsourceBufferHighlightSyntax :: Attr SourceBuffer Bool\nsourceBufferHighlightSyntax = newAttrFromBoolProperty \"highlight-matching-brackets\"\n\n-- |\n-- \nsourceBufferLanguage :: Attr SourceBuffer (Maybe SourceLanguage)\nsourceBufferLanguage = newAttrFromMaybeObjectProperty \"language\" gTypeSourceLanguage\n\n-- |\n--\nsourceBufferMaxUndoLevels :: Attr SourceBuffer Int\nsourceBufferMaxUndoLevels = newAttrFromIntProperty \"max-undo-levels\"\n\n-- |\n-- \nsourceBufferSourceStyleScheme :: Attr SourceBuffer (Maybe SourceStyleScheme)\nsourceBufferSourceStyleScheme = newAttrFromMaybeObjectProperty \"style-scheme\" gTypeSourceStyleScheme\n\n-- |\n--\nsourceBufferHighlightUpdated :: Signal SourceBuffer (TextIter -> TextIter -> IO ())\nsourceBufferHighlightUpdated = Signal $ connect_BOXED_BOXED__NONE \"highlight-updated\" mkTextIterCopy mkTextIterCopy\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"223a5b8ccc6ca52be4cf3c1922f085285ddf98f4","subject":"memory management bindings (1D)","message":"memory management bindings (1D)\n\nIgnore-this: dcf4c03e6463cf774fc87358dbbdc917\n\ndarcs-hash:20090719055819-115f9-c64704cc0c31efefa17d0839d8e0c44d6513ea66.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 chooseDevice,\n getDevice,\n getDeviceCount,\n getDeviceProperties,\n setDevice,\n setDeviceFlags,\n setValidDevices,\n\n --\n -- Memory management\n --\n malloc, mallocPitch,\n memcpy, memcpyAsync,\n memset,\n\n\n --\n -- Stream management\n --\n streamCreate,\n streamDestroy,\n streamQuery,\n streamSynchronize\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--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Select compute device which best matches criteria\n--\nchooseDevice :: DeviceProperties -> IO (Either String Int)\nchooseDevice dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Result' cToEnum #}\n where\n withDevProp = with\n\n--\n-- Returns which device is currently being used\n--\ngetDevice :: IO (Either String Int)\ngetDevice = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Result' cToEnum #}\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-- Set flags to be used for device executions\n--\nsetDeviceFlags :: [DeviceFlags] -> IO (Maybe String)\nsetDeviceFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Result' cToEnum #}\n\n--\n-- Set list of devices for CUDA execution in priority order\n--\nsetValidDevices :: [Int] -> IO (Maybe String)\nsetValidDevices l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Result' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\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--\n-- If the allocation is successful, it is marked to be automatically released\n-- when no longer needed.\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-- Allocate pitched memory on the device\n--\nmallocPitch :: Integer -> Integer -> IO (Either String (DevicePtr,Integer))\nmallocPitch width height = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= \\dp -> return.Right $ (dp,pitch)\n _ -> return.Left $ getErrorString rv\n\n{# fun unsafe cudaMallocPitch\n { alloca- `Ptr ()' peek* ,\n alloca- `Integer' peekIntConv* ,\n cIntConv `Integer' ,\n cIntConv `Integer' } -> `Result' cToEnum #}\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\n--\n-- Copy data between host and device\n--\nmemcpy :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> IO (Maybe String)\nmemcpy dst src bytes dir = nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' } -> `Result' cToEnum #}\n\n--\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: DevicePtr -> DevicePtr -> Integer -> CopyDirection -> Stream -> IO (Maybe String)\nmemcpyAsync dst src bytes dir stream = nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { withDevicePtr* `DevicePtr' ,\n withDevicePtr* `DevicePtr' ,\n cIntConv `Integer' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Result' cToEnum #}\n\n--\n-- Initialize device memory to a given value\n--\nmemset :: DevicePtr -> Integer -> Int -> IO (Maybe String)\nmemset ptr symbol bytes = nothingIfOk `fmap` cudaMemset ptr bytes symbol\n\n{# fun unsafe cudaMemset\n { withDevicePtr* `DevicePtr' ,\n `Int' ,\n cIntConv `Integer' } -> `Result' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\n--\n-- Create an asynchronous stream\n--\nstreamCreate :: IO (Either String Stream)\nstreamCreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peek* } -> `Result' cToEnum #}\n\n--\n-- Destroy and clean up an asynchronous stream\n--\nstreamDestroy :: Stream -> IO (Maybe String)\nstreamDestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { cIntConv `Stream' } -> `Result' cToEnum #}\n\n--\n-- Determine if all operations in a stream have completed\n--\nstreamQuery :: Stream -> IO (Either String Bool)\nstreamQuery s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (getErrorString rv)\n\n{# fun unsafe cudaStreamQuery\n { cIntConv `Stream' } -> `Result' cToEnum #}\n\n--\n-- Block until all operations have been completed\n--\nstreamSynchronize :: Stream -> IO (Maybe String)\nstreamSynchronize s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { cIntConv `Stream' } -> `Result' cToEnum #}\n\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 chooseDevice,\n getDevice,\n getDeviceCount,\n getDeviceProperties,\n setDevice,\n setDeviceFlags,\n setValidDevices,\n\n --\n -- Memory management\n --\n malloc,\n\n --\n -- Stream management\n --\n streamCreate, streamDestroy, streamQuery, streamSynchronize\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--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Select compute device which best matches criteria\n--\nchooseDevice :: DeviceProperties -> IO (Either String Int)\nchooseDevice dev = resultIfOk `fmap` cudaChooseDevice dev\n\n{# fun unsafe cudaChooseDevice\n { alloca- `Int' peekIntConv* ,\n withDevProp* `DeviceProperties' } -> `Result' cToEnum #}\n where\n withDevProp = with\n\n--\n-- Returns which device is currently being used\n--\ngetDevice :: IO (Either String Int)\ngetDevice = resultIfOk `fmap` cudaGetDevice\n\n{# fun unsafe cudaGetDevice\n { alloca- `Int' peekIntConv* } -> `Result' cToEnum #}\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-- Set flags to be used for device executions\n--\nsetDeviceFlags :: [DeviceFlags] -> IO (Maybe String)\nsetDeviceFlags f = nothingIfOk `fmap` cudaSetDeviceFlags (combineBitMasks f)\n\n{# fun unsafe cudaSetDeviceFlags\n { `Int' } -> `Result' cToEnum #}\n\n--\n-- Set list of devices for CUDA execution in priority order\n--\nsetValidDevices :: [Int] -> IO (Maybe String)\nsetValidDevices l = nothingIfOk `fmap` cudaSetValidDevices l (length l)\n\n{# fun unsafe cudaSetValidDevices\n { withArrayIntConv* `[Int]' ,\n `Int' } -> `Result' cToEnum #}\n where\n withArrayIntConv = withArray . map cIntConv\n\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--\n-- If the allocation is successful, it is marked to be automatically released\n-- when no longer needed.\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\n\n--------------------------------------------------------------------------------\n-- Stream Management\n--------------------------------------------------------------------------------\n\n--\n-- Create an asynchronous stream\n--\nstreamCreate :: IO (Either String Stream)\nstreamCreate = resultIfOk `fmap` cudaStreamCreate\n\n{# fun unsafe cudaStreamCreate\n { alloca- `Stream' peek* } -> `Result' cToEnum #}\n\n--\n-- Destroy and clean up an asynchronous stream\n--\nstreamDestroy :: Stream -> IO (Maybe String)\nstreamDestroy s = nothingIfOk `fmap` cudaStreamDestroy s\n\n{# fun unsafe cudaStreamDestroy\n { cIntConv `Stream' } -> `Result' cToEnum #}\n\n--\n-- Determine if all operations in a stream have completed\n--\nstreamQuery :: Stream -> IO (Either String Bool)\nstreamQuery s = cudaStreamQuery s >>= \\rv -> do\n return $ case rv of\n Success -> Right True\n NotReady -> Right False\n _ -> Left (getErrorString rv)\n\n{# fun unsafe cudaStreamQuery\n { cIntConv `Stream' } -> `Result' cToEnum #}\n\n--\n-- Block until all operations have been completed\n--\nstreamSynchronize :: Stream -> IO (Maybe String)\nstreamSynchronize s = nothingIfOk `fmap` cudaStreamSynchronize s\n\n{# fun unsafe cudaStreamSynchronize\n { cIntConv `Stream' } -> `Result' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"6ea37ddddf71fa07c1ec8df277e268dc8f83ce9e","subject":"gstreamer: add StaticPadTemplate to M.S.G.Core.Types","message":"gstreamer: add StaticPadTemplate to M.S.G.Core.Types\n\ndarcs-hash:20080218011120-21862-6790f42e1fda0bc219221c24bb2833ed365073d5.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Types.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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n StaticPadTemplate(..),\n staticPadTemplateGet,\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n{# pointer *GstStaticPadTemplate as StaticPadTemplate #}\nstaticPadTemplateGet :: StaticPadTemplate\n -> IO PadTemplate\nstaticPadTemplateGet =\n {# call static_pad_template_get #} >=> takeObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\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-- #hide\n\n-- | Maintainer : gtk2hs-devel\\@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Types (\n \n module Media.Streaming.GStreamer.Core.Constants,\n module Media.Streaming.GStreamer.Core.Hierarchy,\n module Media.Streaming.GStreamer.Core.HierarchyBase,\n module Media.Streaming.GStreamer.Core.MiniHierarchy,\n module Media.Streaming.GStreamer.Core.MiniHierarchyBase,\n module Media.Streaming.GStreamer.Core.GObjectHierarchy,\n \n cToFlags,\n cFromFlags,\n cToEnum,\n cFromEnum,\n \n FourCC,\n Fraction,\n \n Format(..),\n FormatDefinition(..),\n \n mkObjectGetFlags,\n mkObjectSetFlags,\n mkObjectUnsetFlags,\n \n withObject,\n peekObject,\n takeObject,\n giveObject,\n \n PadDirection(..),\n PadPresence(..),\n PadLinkReturn(..),\n FlowReturn(..),\n ActivateMode(..),\n \n State(..),\n StateChangeReturn(..),\n SeekFlags(..),\n SeekType(..),\n \n PluginFilter,\n PluginFeatureFilter,\n \n BusFunc,\n BusSyncHandler,\n BusSyncReply(..),\n \n ClockTimeDiff,\n ClockReturn(..),\n ClockID(..),\n withClockID,\n takeClockID,\n peekClockID,\n \n IndexCertainty(..),\n IndexEntry(..),\n takeIndexEntry,\n peekIndexEntry,\n IndexEntryType(..),\n \n IndexLookupMethod(..),\n IndexFilter,\n IndexAssociation(..),\n AssocFlags(..),\n \n withMiniObject,\n peekMiniObject,\n takeMiniObject,\n giveMiniObject,\n MiniObjectT(..),\n askMiniObjectPtr,\n runMiniObjectT,\n marshalMiniObjectModify,\n mkMiniObjectGetFlags,\n mkMiniObjectGetFlagsM,\n mkMiniObjectSetFlagsM,\n mkMiniObjectUnsetFlagsM,\n \n QueryType,\n QueryTypeDefinition(..),\n \n EventTypeFlags(..),\n \n PtrIterator(..),\n Iterator(..),\n IteratorItem(..),\n IteratorResult(..),\n Iterable(..),\n IteratorFilter,\n IteratorFoldFunction,\n withIterator,\n takeIterator,\n peekIterator,\n -- giveIterator - not defined - iterators don't have a refcount and\n -- are not copyable\n \n Caps(..),\n mkCaps,\n unCaps,\n withCaps,\n takeCaps,\n peekCaps,\n giveCaps,\n \n Structure(..),\n StructureForeachFunc,\n withStructure,\n takeStructure,\n peekStructure,\n giveStructure,\n StructureM(..),\n StructureMRep,\n \n TagList,\n withTagList,\n takeTagList,\n peekTagList,\n giveTagList,\n Tag,\n TagFlag,\n TagMergeMode,\n \n Segment(..),\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Control.Monad.Reader\nimport Control.Monad.Trans\nimport Data.Ratio ( Ratio )\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import System.Glib.GType#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GValue#}\nimport System.Glib.UTFString\nimport Media.Streaming.GStreamer.Core.Constants\nimport Media.Streaming.GStreamer.Core.HierarchyBase\n{#import Media.Streaming.GStreamer.Core.MiniHierarchyBase#}\n{#import Media.Streaming.GStreamer.Core.Hierarchy#}\n{#import Media.Streaming.GStreamer.Core.MiniHierarchy#}\n{#import Media.Streaming.GStreamer.Core.GObjectHierarchy#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\ntype FourCC = Word32\ntype Fraction = Ratio Int\n\n{# enum GstParseError as ParseError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ncToFlags :: (Integral int, Flags flags)\n => int\n -> [flags]\ncToFlags = toFlags . fromIntegral\ncFromFlags :: (Integral int, Flags flags)\n => [flags]\n -> int\ncFromFlags = fromIntegral . fromFlags\n\ncToEnum :: (Integral int, Enum enum)\n => int\n -> enum\ncToEnum = toEnum . fromIntegral\ncFromEnum :: (Integral int, Enum enum)\n => enum\n -> int\ncFromEnum = fromIntegral . fromEnum\n\n--------------------------------------------------------------------\n\n{# enum GstFormat as Format {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ndata FormatDefinition = FormatDefinition { formatValue :: Format\n , formatNick :: String\n , formatDescription :: String\n , formatQuark :: Quark }\n deriving (Eq, Show)\ninstance Storable FormatDefinition where\n sizeOf = undefined\n alignment = undefined\n peek ptr =\n do value <- liftM cToEnum $ {# get GstFormatDefinition->value #} ptr\n nick <- {# get GstFormatDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstFormatDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstFormatDefinition->quark #} ptr\n return $ FormatDefinition value nick description quark\n poke _ _ = undefined\ninstance Iterable FormatDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\nwithObject :: ObjectClass objectT\n => objectT\n -> (Ptr objectT -> IO a)\n -> IO a\nwithObject object action =\n let objectFPtr = unObject $ toObject object\n in withForeignPtr (castForeignPtr objectFPtr) action\n\npeekObject, takeObject :: ObjectClass obj\n => Ptr obj\n -> IO obj\npeekObject cObject = do\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectRef $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"&gst_object_unref\"\n objectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"gst_object_ref\"\n cObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeObject cObject =\n liftM (unsafeCastGObject . GObject . castForeignPtr) $\n do cObjectUnfloat $ castPtr cObject\n newForeignPtr (castPtr cObject) objectFinalizer\nforeign import ccall unsafe \"_hs_gst_object_unfloat\"\n cObjectUnfloat :: Ptr ()\n -> IO ()\n\nmkObjectGetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> IO [flagsT]\nmkObjectGetFlags object =\n liftM cToFlags $\n withObject (toObject object) cObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_object_flags\"\n cObjectGetFlags :: Ptr Object\n -> IO CUInt\n\nmkObjectSetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectSetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectSetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_set\"\n cObjectSetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\nmkObjectUnsetFlags :: (ObjectClass objectT, Flags flagsT)\n => objectT\n -> [flagsT]\n -> IO ()\nmkObjectUnsetFlags object flags =\n withObject (toObject object) $ \\cObject ->\n cObjectUnsetFlags cObject (fromIntegral $ fromFlags flags)\nforeign import ccall unsafe \"_hs_gst_object_flag_unset\"\n cObjectUnsetFlags :: Ptr Object\n -> CUInt\n -> IO ()\n\n-- | Use 'giveObject' to pass an object to a function that takes\n-- ownership of it.\ngiveObject :: (ObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveObject obj action =\n do liftIO $ withObject (toObject obj) $ {# call gst_object_ref #} . castPtr\n action obj\n\n--------------------------------------------------------------------\n\n{# enum GstPadDirection as PadDirection {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadPresence as PadPresence {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstPadLinkReturn as PadLinkReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstFlowReturn as FlowReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstActivateMode as ActivateMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Pad where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\n{# enum GstPluginError as PluginError {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\n{# enum GstSeekFlags as SeekFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags SeekFlags\n{# enum GstSeekType as SeekType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstState as State {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# enum GstStateChangeReturn as StateChangeReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ninstance Iterable Element where\n peekIterable = peekObject . castPtr\n withIterable = withObject\n\n--------------------------------------------------------------------\n\ntype PluginFilter = Plugin -> IO Bool\ntype PluginFeatureFilter = PluginFeature -> IO Bool\n\n--------------------------------------------------------------------\n\n{# enum GstBusSyncReply as BusSyncReply {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\ntype BusFunc = Bus\n -> Message\n -> IO Bool\ntype BusSyncHandler = Bus\n -> Message\n -> IO BusSyncReply\n\n--------------------------------------------------------------------\n\ntype ClockTimeDiff = Int64\n\n{# enum GstClockReturn as ClockReturn {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstClockID as ClockID foreign newtype #}\nwithClockID :: ClockID\n -> (Ptr ClockID -> IO a)\n -> IO a\nwithClockID (ClockID clockID) = withForeignPtr clockID\ntakeClockID, peekClockID :: Ptr ClockID\n -> IO ClockID\ntakeClockID clockIDPtr =\n liftM ClockID $ newForeignPtr clockIDPtr clockIDFinalizer\npeekClockID clockIDPtr =\n do {# call clock_id_ref #} $ castPtr clockIDPtr\n takeClockID clockIDPtr\n\nforeign import ccall unsafe \"&gst_clock_id_unref\"\n clockIDFinalizer :: FunPtr (Ptr ClockID -> IO ())\n\n--------------------------------------------------------------------\n\n{# enum GstIndexCertainty as IndexCertainty {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexEntryType as IndexEntryType {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIndexLookupMethod as IndexLookupMethod {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n{# pointer *GstIndexEntry as IndexEntry foreign newtype #}\n\ntakeIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\ntakeIndexEntry ptr =\n liftM IndexEntry $ newForeignPtr ptr indexEntryFinalizer\nforeign import ccall unsafe \"&gst_index_entry_free\"\n indexEntryFinalizer :: FunPtr (Ptr IndexEntry -> IO ())\npeekIndexEntry :: Ptr IndexEntry\n -> IO IndexEntry\npeekIndexEntry ptr =\n (liftM IndexEntry $ newForeignPtr_ ptr) >>=\n {# call index_entry_copy #} >>=\n takeIndexEntry\n\ntype IndexFilter = Index\n -> IndexEntry\n -> IO Bool\n\ndata IndexAssociation = IndexAssociation Format Int64\n deriving (Eq, Show)\ninstance Storable IndexAssociation where\n sizeOf _ = {# sizeof GstIndexAssociation #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do format <- {# get GstIndexAssociation->format #} ptr\n value <- {# get GstIndexAssociation->value #} ptr\n return $ IndexAssociation (cToEnum format) (fromIntegral value)\n poke ptr (IndexAssociation format value) =\n do {# set GstIndexAssociation->format #} ptr $ cFromEnum format\n {# set GstIndexAssociation->value #} ptr $ fromIntegral value\n\n{# enum GstAssocFlags as AssocFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags AssocFlags\n\n--------------------------------------------------------------------\n\nwithMiniObject :: MiniObjectClass miniObjectT\n => miniObjectT\n -> (Ptr miniObjectT -> IO a)\n -> IO a\nwithMiniObject miniObject action =\n let miniObjectFPtr = unMiniObject $ toMiniObject miniObject\n in withForeignPtr (castForeignPtr miniObjectFPtr) action\n\ntakeMiniObject, peekMiniObject :: (MiniObjectClass obj)\n => Ptr obj\n -> IO obj\npeekMiniObject cMiniObject =\n do cMiniObjectRef $ castPtr cMiniObject\n takeMiniObject cMiniObject\nforeign import ccall unsafe \"gst_mini_object_ref\"\n cMiniObjectRef :: Ptr ()\n -> IO (Ptr ())\n\ntakeMiniObject cMiniObject =\n do cMiniObjectMakeReadOnly $ castPtr cMiniObject\n object <- newForeignPtr (castPtr cMiniObject) miniObjectFinalizer\n return $ unsafeCastMiniObject $ MiniObject $ castForeignPtr object\nforeign import ccall unsafe \"&gst_mini_object_unref\"\n miniObjectFinalizer :: FunPtr (Ptr () -> IO ())\nforeign import ccall unsafe \"_hs_gst_mini_object_make_read_only\"\n cMiniObjectMakeReadOnly :: Ptr MiniObject\n -> IO ()\n\n-- | Use 'giveMiniObject' to pass an miniObject to a function that takes\n-- ownership of it.\ngiveMiniObject :: (MiniObjectClass obj, MonadIO m)\n => obj\n -> (obj -> m a)\n -> m a\ngiveMiniObject obj action =\n do liftIO $ {# call gst_mini_object_ref #} (toMiniObject obj)\n action obj\n\n-- | A 'Monad' for sequencing modifications to a 'MiniObject'.\nnewtype (MiniObjectClass miniObjectT, Monad m) =>\n MiniObjectT miniObjectT m a =\n MiniObjectT (ReaderT (Ptr miniObjectT) m a)\n deriving (Functor, Monad, MonadTrans)\ninstance (MiniObjectClass miniObjectT, Monad m, MonadIO m) =>\n MonadIO (MiniObjectT miniObjectT m) where\n liftIO = MiniObjectT . liftIO\n\naskMiniObjectPtr :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m (Ptr miniObjectT)\naskMiniObjectPtr = MiniObjectT $ ask\n\nrunMiniObjectT :: (MiniObjectClass miniObjectT, Monad m)\n => MiniObjectT miniObjectT m a\n -> (Ptr miniObjectT)\n -> m a\nrunMiniObjectT (MiniObjectT action) = runReaderT action\n\nmarshalMiniObjectModify :: (MiniObjectClass miniObjectT, MonadIO m)\n => m (Ptr miniObjectT)\n -> MiniObjectT miniObjectT m a\n -> m (miniObjectT, a)\nmarshalMiniObjectModify mkMiniObject action =\n do ptr' <- mkMiniObject\n ptr <- liftIO $ liftM castPtr $ gst_mini_object_make_writable $ castPtr ptr'\n result <- runMiniObjectT action ptr\n object <- liftIO $ takeMiniObject ptr\n return (object, result)\n where _ = {# call mini_object_make_writable #}\n\nmkMiniObjectGetFlags :: (MiniObjectClass miniObjectT, Flags flagsT)\n => miniObjectT\n -> [flagsT]\nmkMiniObjectGetFlags miniObject =\n cToFlags $ unsafePerformIO $\n withMiniObject (toMiniObject miniObject) cMiniObjectGetFlags\nforeign import ccall unsafe \"_hs_gst_mini_object_flags\"\n cMiniObjectGetFlags :: Ptr MiniObject\n -> IO CUInt\n\nmkMiniObjectGetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => MiniObjectT miniObjectT m [flagsT]\nmkMiniObjectGetFlagsM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM cToFlags $ cMiniObjectGetFlags $ castPtr ptr\n\nmkMiniObjectSetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectSetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectSetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_set\"\n cMiniObjectSetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\nmkMiniObjectUnsetFlagsM :: (MiniObjectClass miniObjectT, Flags flagsT, MonadIO m)\n => [flagsT]\n -> MiniObjectT miniObjectT m ()\nmkMiniObjectUnsetFlagsM flags = do\n ptr <- askMiniObjectPtr\n liftIO $ cMiniObjectUnsetFlags (castPtr ptr) $ cFromFlags flags\nforeign import ccall unsafe \"_hs_gst_mini_object_flag_unset\"\n cMiniObjectUnsetFlags :: Ptr MiniObject\n -> CUInt\n -> IO ()\n\n--------------------------------------------------------------------\n\ntype QueryType = {# type GstQueryType #}\ndata QueryTypeDefinition = QueryTypeDefinition {\n queryTypeDefinitionValue :: QueryType,\n queryTypeDefinitionNick :: String,\n queryTypeDefinitionDescription :: String,\n queryTypeDefinitionQuark :: Quark\n } deriving (Eq, Show)\ninstance Storable QueryTypeDefinition where\n sizeOf _ = {# sizeof GstQuery #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do value <- {# get GstQueryTypeDefinition->value #} ptr\n nick <- {# get GstQueryTypeDefinition->nick #} ptr >>= peekUTFString\n description <- {# get GstQueryTypeDefinition->description #} ptr >>= peekUTFString\n quark <- {# get GstQueryTypeDefinition->quark #} ptr\n return $ QueryTypeDefinition value\n nick\n description\n quark\n poke _ _ = undefined\ninstance Iterable QueryTypeDefinition where\n peekIterable = peek . castPtr\n withIterable = with\n\n--------------------------------------------------------------------\n\n{# enum GstEventTypeFlags as EventTypeFlags {underscoreToCase} with prefix = \"GST\" deriving (Eq, Bounded, Show) #}\ninstance Flags EventTypeFlags\n\n--------------------------------------------------------------------\n\n{# pointer *GstIterator as PtrIterator foreign newtype #}\n\nwithPtrIterator :: PtrIterator\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithPtrIterator (PtrIterator cPtrIterator) = withForeignPtr cPtrIterator\n\ntakePtrIterator, peekPtrIterator :: Ptr PtrIterator\n -> IO PtrIterator\ntakePtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr ptrIteratorPtr ptrIteratorFinalizer\npeekPtrIterator ptrIteratorPtr =\n liftM PtrIterator $ newForeignPtr_ ptrIteratorPtr\n\nforeign import ccall unsafe \"&gst_iterator_free\"\n ptrIteratorFinalizer :: FunPtr (Ptr PtrIterator -> IO ())\n\n{# enum GstIteratorItem as IteratorItem {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstIteratorResult as IteratorResult {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\nmkIterator newPtrIterator cPtrIterator =\n do ptrIterator <- newPtrIterator cPtrIterator\n return $ Iterator ptrIterator\n\nnewtype Iterable a => Iterator a = Iterator PtrIterator\n\nwithIterator :: Iterator a\n -> (Ptr PtrIterator -> IO a)\n -> IO a\nwithIterator (Iterator ptrIterator) = withPtrIterator ptrIterator\n\ntakeIterator, peekIterator :: Ptr PtrIterator\n -> IO (Iterator a)\ntakeIterator cPtrIterator = mkIterator takePtrIterator cPtrIterator\npeekIterator cPtrIterator = mkIterator peekPtrIterator cPtrIterator\n\nclass Iterable a where\n peekIterable :: Ptr ()\n -> IO a\n withIterable :: a\n -> (Ptr a -> IO b)\n -> IO b\n\ntype IteratorFilter itemT = itemT\n -> IO Bool\ntype IteratorFoldFunction itemT accumT = itemT\n -> accumT\n -> IO (Bool, accumT)\n\n--------------------------------------------------------------------\n\n{# pointer *GstCaps as Caps foreign newtype #}\nmkCaps :: ForeignPtr Caps -> Caps\nmkCaps = Caps\nunCaps :: Caps -> ForeignPtr Caps\nunCaps (Caps caps) = caps\n\nwithCaps :: Caps -> (Ptr Caps -> IO a) -> IO a\nwithCaps = withForeignPtr . unCaps\n\ntakeCaps, peekCaps :: Ptr Caps\n -> IO Caps\ntakeCaps capsPtr =\n liftM Caps $ newForeignPtr capsPtr capsFinalizer\npeekCaps capsPtr =\n cCapsRef capsPtr >>= takeCaps\nforeign import ccall unsafe \"gst_caps_ref\"\n cCapsRef :: Ptr Caps\n -> IO (Ptr Caps)\n\ngiveCaps :: MonadIO m\n => Caps\n -> (Caps -> m a)\n -> m a\ngiveCaps caps action =\n do liftIO $ {# call caps_ref #} caps\n action caps\n\nforeign import ccall unsafe \"&gst_caps_unref\"\n capsFinalizer :: FunPtr (Ptr Caps -> IO ())\n\n--------------------------------------------------------------------\n\n{# pointer *GstStructure as Structure foreign newtype #}\nmkStructure :: ForeignPtr Structure -> Structure\nmkStructure = Structure\nunStructure :: Structure -> ForeignPtr Structure\nunStructure (Structure structure) = structure\n\nwithStructure :: Structure -> (Ptr Structure -> IO a) -> IO a\nwithStructure = withForeignPtr . unStructure\n\nmkNewStructure :: (Ptr Structure -> IO (ForeignPtr Structure))\n -> Ptr Structure\n -> IO Structure\nmkNewStructure mkFP structurePtr =\n do cStructureMakeImmutable structurePtr\n liftM Structure $ mkFP structurePtr\nforeign import ccall unsafe \"_hs_gst_structure_make_immutable\"\n cStructureMakeImmutable :: Ptr Structure\n -> IO ()\n\ntakeStructure, peekStructure :: Ptr Structure\n -> IO Structure\ntakeStructure =\n mkNewStructure $ flip newForeignPtr structureFinalizer\npeekStructure =\n mkNewStructure $ newForeignPtr_\n\ngiveStructure :: MonadIO m\n => Structure\n -> (Structure -> m a)\n -> m a\ngiveStructure structure action =\n do structure <- liftIO $\n {# call structure_copy #} structure >>=\n peekStructure\n action structure\n\nforeign import ccall unsafe \"&gst_structure_free\"\n structureFinalizer :: FunPtr (Ptr Structure -> IO ())\n\ntype StructureForeachFunc = Quark\n -> GValue\n -> IO Bool\n\nnewtype StructureM a = StructureM (StructureMRep a)\ntype StructureMRep a = (Structure -> IO a)\n\ninstance Monad StructureM where\n (StructureM aM) >>= fbM =\n StructureM $ \\structure ->\n do a <- aM structure\n let StructureM bM = fbM a\n bM structure\n return a = StructureM $ const $ return a\n\n--------------------------------------------------------------------\n\ntype TagList = Structure\nmkTagList = mkStructure\nunTagList = unStructure\nwithTagList = withStructure\ntakeTagList = takeStructure\npeekTagList = takeStructure\ngiveTagList :: MonadIO m\n => TagList\n -> (TagList -> m a)\n -> m a\ngiveTagList = giveStructure\n\ntype Tag = String\n\n{# enum GstTagFlag as TagFlag {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n{# enum GstTagMergeMode as TagMergeMode {underscoreToCase} with prefix = \"GST\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------\n\ndata Segment = Segment { segmentRate :: Double\n , segmentAbsRate :: Double\n , segmentFormat :: Format\n , segmentFlags :: [SeekFlags]\n , segmentStart :: Int64\n , segmentStop :: Int64\n , segmentTime :: Int64\n , segmentAccum :: Int64\n , segmentLastStop :: Int64\n , segmentDuration :: Int64 }\n deriving (Eq, Show)\ninstance Storable Segment where\n sizeOf _ = fromIntegral cSegmentSizeof\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do rate <- {# get GstSegment->rate #} ptr\n absRate <- {# get GstSegment->abs_rate #} ptr\n format <- {# get GstSegment->format #} ptr\n flags <- {# get GstSegment->flags #} ptr\n start <- {# get GstSegment->start #} ptr\n stop <- {# get GstSegment->stop #} ptr\n time <- {# get GstSegment->time #} ptr\n accum <- {# get GstSegment->accum #} ptr\n lastStop <- {# get GstSegment->last_stop #} ptr\n duration <- {# get GstSegment->duration #} ptr\n return $ Segment (realToFrac rate)\n (realToFrac absRate)\n (cToEnum format)\n (cToFlags flags)\n (fromIntegral start)\n (fromIntegral stop)\n (fromIntegral time)\n (fromIntegral accum)\n (fromIntegral lastStop)\n (fromIntegral duration)\n poke ptr (Segment rate\n absRate\n format\n flags\n start\n stop\n time\n accum\n lastStop\n duration) =\n do {# call segment_init #} (castPtr ptr)\n (cFromEnum format)\n {# set GstSegment->rate #} ptr $ realToFrac rate\n {# set GstSegment->abs_rate #} ptr $ realToFrac absRate\n {# set GstSegment->format #} ptr $ cFromEnum format\n {# set GstSegment->flags #} ptr $ fromIntegral $ fromFlags flags\n {# set GstSegment->start #} ptr $ fromIntegral start\n {# set GstSegment->stop #} ptr $ fromIntegral stop\n {# set GstSegment->time #} ptr $ fromIntegral time\n {# set GstSegment->accum #} ptr $ fromIntegral accum\n {# set GstSegment->last_stop #} ptr $ fromIntegral lastStop\n {# set GstSegment->duration #} ptr $ fromIntegral duration\nforeign import ccall unsafe \"_hs_gst_segment_sizeof\"\n cSegmentSizeof :: {# type gsize #}\n\n--------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"a15f604670824b21dcc3a25c0523b1a3ca758550","subject":"add clCreateProgramWithBinary function","message":"add clCreateProgramWithBinary function\n","repos":"Delan90\/opencl,IFCA\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Program.chs","new_file":"src\/System\/GPU\/OpenCL\/Program.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 System.GPU.OpenCL.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clCreateProgramWithBinary, clRetainProgram, \n clReleaseProgram, clUnloadCompiler, clBuildProgram, \n clGetProgramReferenceCount, clGetProgramContext, clGetProgramNumDevices, \n clGetProgramDevices, clGetProgramSource, clGetProgramBinarySizes, \n clGetProgramBinaries, clGetProgramBuildStatus, clGetProgramBuildOptions, \n clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clSetKernelArg, clGetKernelFunctionName, clGetKernelNumArgs, \n clGetKernelReferenceCount, clGetKernelContext, clGetKernelProgram, \n clGetKernelWorkGroupSize, clGetKernelCompileWorkGroupSize, \n clGetKernelLocalMemSize\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM, forM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLulong, CLProgram, CLContext, CLKernel, CLDeviceID, CLError,\n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, \n whenSuccess, wrapPError, wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import CALLCONV \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import CALLCONV \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import CALLCONV \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import CALLCONV \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import CALLCONV \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import CALLCONV \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it throws one of the\nfollowing 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO CLProgram\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n{-| Creates a program object for a context, and loads specified binary data into\nthe program object.\n\nThe program binaries specified by binaries contain the bits that describe the\nprogram executable that will be run on the device(s) associated with\ncontext. The program binary can consist of either or both of device-specific\nexecutable(s), and\/or implementation-specific intermediate representation (IR)\nwhich will be converted to the device-specific executable.\n\nOpenCL allows applications to create a program object using the program\nsource or binary and build appropriate program executables. This allows\napplications to determine whether they want to use the pre-built offline binary\nor load and compile the program source and use the executable compiled\/linked\nonline as the program executable. This can be very useful as it allows\napplications to load and build program executables online on its first instance\nfor appropriate OpenCL devices in the system. These executables can now be\nqueried and cached by the application. Future instances of the application\nlaunching will no longer need to compile and build the program executables. The\ncached executables can be read and loaded by the application, which can help\nsignificantly reduce the application initialization time.\n\nReturns a valid non-zero program object and a list of 'CLError' values whether\nthe program binary for each device specified in device_list was loaded\nsuccessfully or not. It is list of the same length the list of devices with\n'CL_SUCCESS' if binary was successfully loaded for device specified by same\nposition; otherwise returns 'CL_INVALID_VALUE' if length of binary is zero or\n'CL_INVALID_BINARY' if program binary is not a valid binary\nfor the specified device.\n\nThe function can throw on of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context. \n\n * 'CL_INVALID_VALUE' if the device list is empty; or if lengths or binaries are\nempty.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in the device list are not in\nthe list of devices associated with context.\n\n * 'CL_INVALID_BINARY' if an invalid program binary was encountered for any\ndevice.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-} \nclCreateProgramWithBinary :: CLContext -> [CLDeviceID] -> [[Word8]] \n -> IO (CLProgram, [CLError])\nclCreateProgramWithBinary ctx devs bins = wrapPError $ \\perr -> do withArray\ndevs $ \\pdevs -> do withArray lbins $ \\plbins -> do buffs <- forM bins $ \\bs ->\ndo buff <- mallocArray (length bs) :: IO (Ptr Word8) pokeArray buff bs return\nbuff\n\n ret <- withArray buffs $ \\(pbuffs :: Ptr (Ptr Word8)) -> do\n allocaArray ndevs $ \\(perrs :: Ptr CLint) -> do\n prog <- raw_clCreateProgramWithBinary ctx (fromIntegral ndevs) pdevs plbins pbuffs perrs perr\n errs <- peekArray ndevs perrs\n return (prog, map getEnumCL errs)\n \n mapM_ free buffs\n return ret\n \n where\n lbins = map (fromIntegral . length) bins :: [CSize]\n ndevs = length devs\n\n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram can throw the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO ()\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n whenSuccess (raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr)\n $ return ()\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO CSize\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid 0 nullPtr value_size)\n $ peek value_size\n \n-- | Return the program 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 clGetProgramInfo with\n-- 'CL_PROGRAM_REFERENCE_COUNT'.\nclGetProgramReferenceCount :: CLProgram -> IO CLuint\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_CONTEXT'.\nclGetProgramContext :: CLProgram -> IO CLContext\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_NUM_DEVICES'.\nclGetProgramNumDevices :: CLProgram -> IO CLuint\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_DEVICES'.\nclGetProgramDevices :: CLProgram -> IO [CLDeviceID]\nclGetProgramDevices prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_SOURCE'.\nclGetProgramSource :: CLProgram -> IO String\nclGetProgramSource prg = do\n n <- getProgramInfoSize prg infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARY_SIZES'.\nclGetProgramBinarySizes :: CLProgram -> IO [CSize]\nclGetProgramBinarySizes prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n\nThis function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARIES'.\n-}\nclGetProgramBinaries :: CLProgram -> IO [[Word8]]\nclGetProgramBinaries prg = do\n sizes <- clGetProgramBinarySizes prg\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr)\n $ zipWithM peekArray (map fromIntegral sizes) buffers\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO CSize\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid 0 nullPtr val)\n $ peek val\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_STATUS'.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO CLBuildStatus\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_OPTIONS'.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildOptions prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_LOG'.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildLog prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it throws one of the following 'CLError'\nexceptions:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO CLKernel\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, throws 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, throws 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and throws\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO [CLKernel]\nclCreateKernelsInProgram prg = do\n n <- alloca $ \\pn -> do\n whenSuccess (raw_clCreateKernelsInProgram prg 0 nullPtr pn)\n $ peek pn \n allocaArray (fromIntegral n) $ \\pks -> do\n whenSuccess (raw_clCreateKernelsInProgram prg n pks nullPtr)\n $ peekArray (fromIntegral n) pks\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n{-| Used to set the argument value for a specific argument of a kernel.\n\nA kernel object does not update the reference count for objects such as memory,\nsampler objects specified as argument values by 'clSetKernelArg', Users may not\nrely on a kernel object to retain objects specified as argument values to the\nkernel.\n\nImplementations shall not allow 'CLKernel' objects to hold reference counts to\n'CLKernel' arguments, because no mechanism is provided for the user to tell the\nkernel to release that ownership right. If the kernel holds ownership rights on\nkernel args, that would make it impossible for the user to tell with certainty\nwhen he may safely release user allocated resources associated with OpenCL\nobjects such as the CLMem backing store used with 'CL_MEM_USE_HOST_PTR'.\n\n'clSetKernelArg' throws one of the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n \n * 'CL_INVALID_ARG_INDEX' if arg_index is not a valid argument index.\n\n * 'CL_INVALID_ARG_VALUE' if arg_value specified is NULL for an argument that is\nnot declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_MEM_OBJECT' for an argument declared to be a memory object when\nthe specified arg_value is not a valid memory object.\n\n * 'CL_INVALID_SAMPLER' for an argument declared to be of type sampler_t when\nthe specified arg_value is not a valid sampler object.\n\n * 'CL_INVALID_ARG_SIZE' if arg_size does not match the size of the data type\nfor an argument that is not a memory object or if the argument is a memory\nobject and arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is\ndeclared with the __local qualifier or if the argument is a sampler and arg_size\n!= sizeof(cl_sampler). \n-}\nclSetKernelArg :: Storable a => CLKernel -> CLuint -> a -> IO ()\nclSetKernelArg krn idx val = with val $ \\pval -> do\n whenSuccess (raw_clSetKernelArg krn idx (fromIntegral . sizeOf $ val) (castPtr pval))\n $ return ()\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO CSize\ngetKernelInfoSize krn infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid 0 nullPtr val)\n $ peek val\n \n-- | Return the kernel function name.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_FUNCTION_NAME'.\nclGetKernelFunctionName :: CLKernel -> IO String\nclGetKernelFunctionName krn = do\n n <- getKernelInfoSize krn infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_NUM_ARGS'.\nclGetKernelNumArgs :: CLKernel -> IO CLuint\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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 clGetKernelInfo with\n-- 'CL_KERNEL_REFERENCE_COUNT'.\nclGetKernelReferenceCount :: CLKernel -> IO CLuint\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_CONTEXT'.\nclGetKernelContext :: CLKernel -> IO CLContext\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_PROGRAM'.\nclGetKernelProgram :: CLKernel -> IO CLProgram\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n\n#c\nenum CLKernelGroupInfo {\n cL_KERNEL_WORK_GROUP_SIZE=CL_KERNEL_WORK_GROUP_SIZE,\n cL_KERNEL_COMPILE_WORK_GROUP_SIZE=CL_KERNEL_COMPILE_WORK_GROUP_SIZE,\n cL_KERNEL_LOCAL_MEM_SIZE=CL_KERNEL_LOCAL_MEM_SIZE,\n };\n#endc\n{#enum CLKernelGroupInfo {upcaseFirstLetter} #}\n\n-- | This provides a mechanism for the application to query the work-group size\n-- that can be used to execute a kernel on a specific device given by\n-- device. The OpenCL implementation uses the resource requirements of the\n-- kernel (register usage etc.) to determine what this work-group size should\n-- be.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_WORK_GROUP_SIZE'.\nclGetKernelWorkGroupSize :: CLKernel -> CLDeviceID -> IO CSize\nclGetKernelWorkGroupSize krn device = wrapGetInfo (\\(dat :: Ptr CSize)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_WORK_GROUP_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Returns the work-group size specified by the __attribute__((reqd_work_gr\n-- oup_size(X, Y, Z))) qualifier. See Function Qualifiers. If the work-group\n-- size is not specified using the above attribute qualifier (0, 0, 0) is\n-- returned.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_COMPILE_WORK_GROUP_SIZE'.\nclGetKernelCompileWorkGroupSize :: CLKernel -> CLDeviceID -> IO [CSize]\nclGetKernelCompileWorkGroupSize krn device = do\n allocaArray num $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr buff) nullPtr)\n $ peekArray num buff\n where \n infoid = getCLValue CL_KERNEL_COMPILE_WORK_GROUP_SIZE\n num = 3\n elemSize = fromIntegral $ sizeOf (0::CSize)\n size = fromIntegral $ num * elemSize\n\n\n-- | Returns the amount of local memory in bytes being used by a kernel. This\n-- includes local memory that may be needed by an implementation to execute the\n-- kernel, variables declared inside the kernel with the __local address\n-- qualifier and local memory to be allocated for arguments to the kernel\n-- declared as pointers with the __local address qualifier and whose size is\n-- specified with 'clSetKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel declared\n-- with the __local address qualifier, is not specified, its size is assumed to\n-- be 0.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_LOCAL_MEM_SIZE'.\nclGetKernelLocalMemSize :: CLKernel -> CLDeviceID -> IO CLulong\nclGetKernelLocalMemSize krn device = wrapGetInfo (\\(dat :: Ptr CLulong)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_LOCAL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CLulong)\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 System.GPU.OpenCL.Program( \n -- * Types\n CLProgram, CLBuildStatus(..), CLKernel,\n -- * Program Functions\n clCreateProgramWithSource, clRetainProgram, clReleaseProgram, \n clUnloadCompiler, clBuildProgram, clGetProgramReferenceCount, \n clGetProgramContext, clGetProgramNumDevices, clGetProgramDevices,\n clGetProgramSource, clGetProgramBinarySizes, clGetProgramBinaries, \n clGetProgramBuildStatus, clGetProgramBuildOptions, clGetProgramBuildLog,\n -- * Kernel Functions\n clCreateKernel, clCreateKernelsInProgram, clRetainKernel, clReleaseKernel, \n clSetKernelArg, clGetKernelFunctionName, clGetKernelNumArgs, \n clGetKernelReferenceCount, clGetKernelContext, clGetKernelProgram, \n clGetKernelWorkGroupSize, clGetKernelCompileWorkGroupSize, \n clGetKernelLocalMemSize\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Control.Monad( zipWithM )\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String( CString, withCString, newCString, peekCString )\nimport System.GPU.OpenCL.Types( \n CLint, CLuint, CLulong, CLProgram, CLContext, CLKernel, CLDeviceID, \n CLProgramInfo_, CLBuildStatus(..), CLBuildStatus_, CLProgramBuildInfo_, \n CLKernelInfo_, CLKernelWorkGroupInfo_, wrapCheckSuccess, \n whenSuccess, wrapPError, wrapGetInfo, getCLValue, getEnumCL )\n\n#include \n\n-- -----------------------------------------------------------------------------\ntype BuildCallback = CLProgram -> Ptr () -> IO ()\nforeign import CALLCONV \"clCreateProgramWithSource\" raw_clCreateProgramWithSource :: \n CLContext -> CLuint -> Ptr CString -> Ptr CSize -> Ptr CLint -> IO CLProgram\n--foreign import CALLCONV \"clCreateProgramWithBinary\" raw_clCreateProgramWithBinary :: \n-- CLContext -> CLuint -> Ptr CLDeviceID -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr CLint -> Ptr CLint -> IO CLProgram\nforeign import CALLCONV \"clRetainProgram\" raw_clRetainProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clReleaseProgram\" raw_clReleaseProgram :: \n CLProgram -> IO CLint\nforeign import CALLCONV \"clBuildProgram\" raw_clBuildProgram :: \n CLProgram -> CLuint -> Ptr CLDeviceID -> CString -> FunPtr BuildCallback -> Ptr () -> IO CLint\nforeign import CALLCONV \"clUnloadCompiler\" raw_clUnloadCompiler :: \n IO CLint\nforeign import CALLCONV \"clGetProgramInfo\" raw_clGetProgramInfo :: \n CLProgram -> CLProgramInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetProgramBuildInfo\" raw_clGetProgramBuildInfo :: \n CLProgram -> CLDeviceID -> CLProgramBuildInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateKernel\" raw_clCreateKernel :: \n CLProgram -> CString -> Ptr CLint -> IO CLKernel \nforeign import CALLCONV \"clCreateKernelsInProgram\" raw_clCreateKernelsInProgram :: \n CLProgram -> CLuint -> Ptr CLKernel -> Ptr CLuint -> IO CLint \nforeign import CALLCONV \"clRetainKernel\" raw_clRetainKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clReleaseKernel\" raw_clReleaseKernel :: \n CLKernel -> IO CLint \nforeign import CALLCONV \"clSetKernelArg\" raw_clSetKernelArg :: \n CLKernel -> CLuint -> CSize -> Ptr () -> IO CLint\nforeign import CALLCONV \"clGetKernelInfo\" raw_clGetKernelInfo :: \n CLKernel -> CLKernelInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetKernelWorkGroupInfo\" raw_clGetKernelWorkGroupInfo :: \n CLKernel -> CLDeviceID -> CLKernelWorkGroupInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a program object for a context, and loads the source code specified\nby the text strings in the strings array into the program object. The devices\nassociated with the program object are the devices associated with context.\n\nOpenCL allows applications to create a program object using the program source\nor binary and build appropriate program executables. This allows applications to\ndetermine whether they want to use the pre-built offline binary or load and\ncompile the program source and use the executable compiled\/linked online as the\nprogram executable. This can be very useful as it allows applications to load\nand build program executables online on its first instance for appropriate\nOpenCL devices in the system. These executables can now be queried and cached by\nthe application. Future instances of the application launching will no longer\nneed to compile and build the program executables. The cached executables can be\nread and loaded by the application, which can help significantly reduce the\napplication initialization time.\n\nAn OpenCL program consists of a set of kernels that are identified as functions\ndeclared with the __kernel qualifier in the program source. OpenCL programs may\nalso contain auxiliary functions and constant data that can be used by __kernel\nfunctions. The program executable can be generated online or offline by the\nOpenCL compiler for the appropriate target device(s).\n\n'clCreateProgramWithSource' returns a valid non-zero program object if the\nprogram object is created successfully. Otherwise, it throws one of the\nfollowing 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateProgramWithSource :: CLContext -> String -> IO CLProgram\nclCreateProgramWithSource ctx source = wrapPError $ \\perr -> do\n let strings = lines source\n count = fromIntegral $ length strings\n cstrings <- mapM newCString strings\n prog <- withArray cstrings $ \\srcArray -> do\n raw_clCreateProgramWithSource ctx count srcArray nullPtr perr\n mapM_ free cstrings\n return prog\n \n-- | Increments the program reference count. 'clRetainProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclRetainProgram :: CLProgram -> IO Bool\nclRetainProgram prg = wrapCheckSuccess $ raw_clRetainProgram prg\n\n-- | Decrements the program reference count. The program object is deleted after \n-- all kernel objects associated with program have been deleted and the program \n-- reference count becomes zero. 'clReleseProgram' returns 'True' if \n-- the function is executed successfully. It returns 'False' if program is not a \n-- valid program object.\nclReleaseProgram :: CLProgram -> IO Bool\nclReleaseProgram prg = wrapCheckSuccess $ raw_clReleaseProgram prg\n\n-- | Allows the implementation to release the resources allocated by the OpenCL\n-- compiler. This is a hint from the application and does not guarantee that the\n-- compiler will not be used in the future or that the compiler will actually be\n-- unloaded by the implementation. Calls to 'clBuildProgram' after\n-- 'clUnloadCompiler' will reload the compiler, if necessary, to build the\n-- appropriate program executable.\nclUnloadCompiler :: IO ()\nclUnloadCompiler = raw_clUnloadCompiler >> return ()\n\n{-| Builds (compiles and links) a program executable from the program source or\nbinary. OpenCL allows program executables to be built using the source or the\nbinary. The build options are categorized as pre-processor options, options for\nmath intrinsics, options that control optimization and miscellaneous\noptions. This specification defines a standard set of options that must be\nsupported by an OpenCL compiler when building program executables online or\noffline. These may be extended by a set of vendor- or platform-specific options.\n\n * Preprocessor Options\n\nThese options control the OpenCL preprocessor which is run on each program\nsource before actual compilation. -D options are processed in the order they are\ngiven in the options argument to clBuildProgram.\n\n [-D name] Predefine name as a macro, with definition 1.\n\n [-D name=definition] The contents of definition are tokenized and processed as\nif they appeared during translation phase three in a `#define' directive. In\nparticular, the definition will be truncated by embedded newline characters.\n\n [-I dir] Add the directory dir to the list of directories to be searched for\nheader files.\n\n * Math Intrinsics Options\n\nThese options control compiler behavior regarding floating-point\narithmetic. These options trade off between speed and correctness.\n\n [-cl-single-precision-constant] Treat double precision floating-point constant\nas single precision constant.\n\n [-cl-denorms-are-zero] This option controls how single precision and double\nprecision denormalized numbers are handled. If specified as a build option, the\nsingle precision denormalized numbers may be flushed to zero and if the optional\nextension for double precision is supported, double precision denormalized\nnumbers may also be flushed to zero. This is intended to be a performance hint\nand the OpenCL compiler can choose not to flush denorms to zero if the device\nsupports single precision (or double precision) denormalized numbers.\n\nThis option is ignored for single precision numbers if the device does not\nsupport single precision denormalized numbers i.e. 'CL_FP_DENORM' bit is not set\nin 'clGetDeviceSingleFPConfig'.\n\nThis option is ignored for double precision numbers if the device does not\nsupport double precision or if it does support double precison but\n'CL_FP_DENORM' bit is not set in 'clGetDeviceDoubleFPConfig'.\n\nThis flag only applies for scalar and vector single precision floating-point\nvariables and computations on these floating-point variables inside a\nprogram. It does not apply to reading from or writing to image objects.\n\n * Optimization Options\n\nThese options control various sorts of optimizations. Turning on optimization\nflags makes the compiler attempt to improve the performance and\/or code size at\nthe expense of compilation time and possibly the ability to debug the program.\n\n [-cl-opt-disable] This option disables all optimizations. The default is\noptimizations are enabled.\n\n [-cl-strict-aliasing] This option allows the compiler to assume the strictest\naliasing rules.\n\nThe following options control compiler behavior regarding floating-point\narithmetic. These options trade off between performance and correctness and must\nbe specifically enabled. These options are not turned on by default since it can\nresult in incorrect output for programs which depend on an exact implementation\nof IEEE 754 rules\/specifications for math functions.\n\n [-cl-mad-enable] Allow a * b + c to be replaced by a mad. The mad computes a *\nb + c with reduced accuracy. For example, some OpenCL devices implement mad as\ntruncate the result of a * b before adding it to c.\n\n [-cl-no-signed-zeros] Allow optimizations for floating-point arithmetic that\nignore the signedness of zero. IEEE 754 arithmetic specifies the behavior of\ndistinct +0.0 and -0.0 values, which then prohibits simplification of\nexpressions such as x+0.0 or 0.0*x (even with -clfinite-math only). This option\nimplies that the sign of a zero result isn't significant.\n\n [-cl-unsafe-math-optimizations] Allow optimizations for floating-point\narithmetic that (a) assume that arguments and results are valid, (b) may violate\nIEEE 754 standard and (c) may violate the OpenCL numerical compliance\nrequirements as defined in section 7.4 for single-precision floating-point,\nsection 9.3.9 for double-precision floating-point, and edge case behavior in\nsection 7.5. This option includes the -cl-no-signed-zeros and -cl-mad-enable\noptions.\n\n [-cl-finite-math-only] Allow optimizations for floating-point arithmetic that\nassume that arguments and results are not NaNs or \u00b1\u221e. This option may violate\nthe OpenCL numerical compliance requirements defined in in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5.\n\n [-cl-fast-relaxed-math] Sets the optimization options -cl-finite-math-only and\n-cl-unsafe-math-optimizations. This allows optimizations for floating-point\narithmetic that may violate the IEEE 754 standard and the OpenCL numerical\ncompliance requirements defined in the specification in section 7.4 for\nsingle-precision floating-point, section 9.3.9 for double-precision\nfloating-point, and edge case behavior in section 7.5. This option causes the\npreprocessor macro __FAST_RELAXED_MATH__ to be defined in the OpenCL program.\n\n * Options to Request or Suppress Warnings\n\nWarnings are diagnostic messages that report constructions which are not\ninherently erroneous but which are risky or suggest there may have been an\nerror. The following languageindependent options do not enable specific warnings\nbut control the kinds of diagnostics produced by the OpenCL compiler.\n\n [-w] Inhibit all warning messages.\n \n [-Werror] Make all warnings into errors.\n\nclBuildProgram can throw the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_DEVICE' if OpenCL devices listed in device_list are not in the\nlist of devices associated with program.\n\n * 'CL_INVALID_BINARY' if program is created with\n'clCreateWithProgramWithBinary' and devices listed in device_list do not have a\nvalid program binary loaded.\n\n * 'CL_INVALID_BUILD_OPTIONS' if the build options specified by options are\ninvalid.\n\n * 'CL_INVALID_OPERATION' if the build of a program executable for any of the\ndevices listed in device_list by a previous call to 'clBuildProgram' for program\nhas not completed.\n\n * 'CL_COMPILER_NOT_AVAILABLE' if program is created with\n'clCreateProgramWithSource' and a compiler is not available\ni.e. 'clGetDeviceCompilerAvailable' is set to 'False'.\n\n * 'CL_BUILD_PROGRAM_FAILURE' if there is a failure to build the program\nexecutable. This error will be returned if 'clBuildProgram' does not return\nuntil the build has completed.\n\n * 'CL_INVALID_OPERATION' if there are kernel objects attached to program.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclBuildProgram :: CLProgram -> [CLDeviceID] -> String -> IO ()\nclBuildProgram prg devs opts = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n withCString opts $ \\copts -> do\n whenSuccess (raw_clBuildProgram prg cndevs pdevs copts nullFunPtr nullPtr)\n $ return ()\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n#c\nenum CLProgramInfo {\n cL_PROGRAM_REFERENCE_COUNT=CL_PROGRAM_REFERENCE_COUNT,\n cL_PROGRAM_CONTEXT=CL_PROGRAM_CONTEXT,\n cL_PROGRAM_NUM_DEVICES=CL_PROGRAM_NUM_DEVICES,\n cL_PROGRAM_DEVICES=CL_PROGRAM_DEVICES,\n cL_PROGRAM_SOURCE=CL_PROGRAM_SOURCE,\n cL_PROGRAM_BINARY_SIZES=CL_PROGRAM_BINARY_SIZES,\n cL_PROGRAM_BINARIES=CL_PROGRAM_BINARIES,\n };\n#endc\n{#enum CLProgramInfo {upcaseFirstLetter} #}\n\ngetProgramInfoSize :: CLProgram -> CLProgramInfo_ -> IO CSize\ngetProgramInfoSize prg infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid 0 nullPtr value_size)\n $ peek value_size\n \n-- | Return the program 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 clGetProgramInfo with\n-- 'CL_PROGRAM_REFERENCE_COUNT'.\nclGetProgramReferenceCount :: CLProgram -> IO CLuint\nclGetProgramReferenceCount prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context specified when the program object is created.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_CONTEXT'.\nclGetProgramContext :: CLProgram -> IO CLContext\nclGetProgramContext prg = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the number of devices associated with program.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_NUM_DEVICES'.\nclGetProgramNumDevices :: CLProgram -> IO CLuint\nclGetProgramNumDevices prg = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetProgramInfo prg infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_PROGRAM_NUM_DEVICES\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices associated with the program object. This can be\n-- the devices associated with context on which the program object has been\n-- created or can be a subset of devices that are specified when a progam object\n-- is created using 'clCreateProgramWithBinary'.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_DEVICES'.\nclGetProgramDevices :: CLProgram -> IO [CLDeviceID]\nclGetProgramDevices prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_DEVICES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the program source code specified by\n-- 'clCreateProgramWithSource'. The source string returned is a concatenation of\n-- all source strings specified to 'clCreateProgramWithSource' with a null\n-- terminator. The concatenation strips any nulls in the original source\n-- strings. The actual number of characters that represents the program source\n-- code including the null terminator is returned in param_value_size_ret.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_SOURCE'.\nclGetProgramSource :: CLProgram -> IO String\nclGetProgramSource prg = do\n n <- getProgramInfoSize prg infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_SOURCE\n \n-- | Returns an array that contains the size in bytes of the program binary for\n-- each device associated with program. The size of the array is the number of\n-- devices associated with program. If a binary is not available for a\n-- device(s), a size of zero is returned.\n--\n-- This function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARY_SIZES'.\nclGetProgramBinarySizes :: CLProgram -> IO [CSize]\nclGetProgramBinarySizes prg = do\n size <- getProgramInfoSize prg infoid\n allocaArray (numElems size) $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr buff) nullPtr)\n $ peekArray (numElems size) buff\n where \n infoid = getCLValue CL_PROGRAM_BINARY_SIZES\n numElems s = (fromIntegral s) `div` elemSize\n elemSize = sizeOf (0::CSize)\n\n{-| Return the program binaries for all devices associated with program. For\neach device in program, the binary returned can be the binary specified for the\ndevice when program is created with 'clCreateProgramWithBinary' or it can be the\nexecutable binary generated by 'clBuildProgram'. If program is created with\n'clCreateProgramWithSource', the binary returned is the binary generated by\n'clBuildProgram'. The bits returned can be an implementation-specific\nintermediate representation (a.k.a. IR) or device specific executable bits or\nboth. The decision on which information is returned in the binary is up to the\nOpenCL implementation.\n\nTo find out which device the program binary in the array refers to, use the\n'clGetProgramDevices' query to get the list of devices. There is a one-to-one\ncorrespondence between the array of data returned by 'clGetProgramBinaries' and\narray of devices returned by 'clGetProgramDevices'. \n\nThis function execute OpenCL clGetProgramInfo with 'CL_PROGRAM_BINARIES'.\n-}\nclGetProgramBinaries :: CLProgram -> IO [[Word8]]\nclGetProgramBinaries prg = do\n sizes <- clGetProgramBinarySizes prg\n let numElems = length sizes\n size = fromIntegral $ numElems * elemSize\n buffers <- (mapM (mallocArray.fromIntegral) sizes) :: IO [Ptr Word8]\n ret <- withArray buffers $ \\(parray :: Ptr (Ptr Word8)) -> do\n whenSuccess (raw_clGetProgramInfo prg infoid size (castPtr parray) nullPtr)\n $ zipWithM peekArray (map fromIntegral sizes) buffers\n mapM_ free buffers\n return ret\n where \n infoid = getCLValue CL_PROGRAM_BINARIES\n elemSize = sizeOf (nullPtr::Ptr Word8)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLProgramBuildInfo {\n cL_PROGRAM_BUILD_STATUS=CL_PROGRAM_BUILD_STATUS,\n cL_PROGRAM_BUILD_OPTIONS=CL_PROGRAM_BUILD_OPTIONS,\n cL_PROGRAM_BUILD_LOG=CL_PROGRAM_BUILD_LOG,\n };\n#endc\n{#enum CLProgramBuildInfo {upcaseFirstLetter} #}\n\ngetProgramBuildInfoSize :: CLProgram -> CLDeviceID -> CLProgramInfo_ -> IO CSize\ngetProgramBuildInfoSize prg device infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid 0 nullPtr val)\n $ peek val\n \n-- | Returns the build status of program for a specific device as given by\n-- device.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_STATUS'.\nclGetProgramBuildStatus :: CLProgram -> CLDeviceID -> IO CLBuildStatus\nclGetProgramBuildStatus prg device = wrapGetInfo (\\(dat :: Ptr CLBuildStatus_) \n -> raw_clGetProgramBuildInfo prg device infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_PROGRAM_BUILD_STATUS\n size = fromIntegral $ sizeOf (0::CLBuildStatus_)\n\n-- | Return the build options specified by the options argument in\n-- clBuildProgram for device. If build status of program for device is\n-- 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_OPTIONS'.\nclGetProgramBuildOptions :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildOptions prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_OPTIONS\n \n-- | Return the build log when 'clBuildProgram' was called for device. If build\n-- status of program for device is 'CL_BUILD_NONE', an empty string is returned.\n--\n-- This function execute OpenCL clGetProgramBuildInfo with\n-- 'CL_PROGRAM_BUILD_LOG'.\nclGetProgramBuildLog :: CLProgram -> CLDeviceID -> IO String\nclGetProgramBuildLog prg device = do\n n <- getProgramBuildInfoSize prg device infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetProgramBuildInfo prg device infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_PROGRAM_BUILD_LOG\n \n-- -----------------------------------------------------------------------------\n{-| Creates a kernal object. A kernel is a function declared in a program. A\nkernel is identified by the __kernel qualifier applied to any function in a\nprogram. A kernel object encapsulates the specific __kernel function declared in\na program and the argument values to be used when executing this __kernel\nfunction.\n\n'clCreateKernel' returns a valid non-zero kernel object if the kernel object is\ncreated successfully. Otherwise, it throws one of the following 'CLError'\nexceptions:\n\n * 'CL_INVALID_PROGRAM' if program is not a valid program object.\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built executable\n for program.\n\n * 'CL_INVALID_KERNEL_NAME' if kernel_name is not found in program.\n\n * 'CL_INVALID_KERNEL_DEFINITION' if the function definition for __kernel\nfunction given by kernel_name such as the number of arguments, the argument\ntypes are not the same for all devices for which the program executable has been\nbuilt.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host. \n-}\nclCreateKernel :: CLProgram -> String -> IO CLKernel\nclCreateKernel prg name = withCString name $ \\cname -> wrapPError $ \\perr -> do\n raw_clCreateKernel prg cname perr\n\n{-| Creates kernel objects for all kernel functions in a program object. Kernel\nobjects are not created for any __kernel functions in program that do not have\nthe same function definition across all devices for which a program executable\nhas been successfully built.\n\nKernel objects can only be created once you have a program object with a valid\nprogram source or binary loaded into the program object and the program\nexecutable has been successfully built for one or more devices associated with\nprogram. No changes to the program executable are allowed while there are kernel\nobjects associated with a program object. This means that calls to\n'clBuildProgram' return 'CL_INVALID_OPERATION' if there are kernel objects\nattached to a program object. The OpenCL context associated with program will be\nthe context associated with kernel. The list of devices associated with program\nare the devices associated with kernel. Devices associated with a program object\nfor which a valid program executable has been built can be used to execute\nkernels declared in the program object.\n\n'clCreateKernelsInProgram' will return the kernel objects if the kernel objects\nwere successfully allocated, throws 'CL_INVALID_PROGRAM' if program is not a\nvalid program object, throws 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no\nsuccessfully built executable for any device in program and throws\n'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclCreateKernelsInProgram :: CLProgram -> IO [CLKernel]\nclCreateKernelsInProgram prg = do\n n <- alloca $ \\pn -> do\n whenSuccess (raw_clCreateKernelsInProgram prg 0 nullPtr pn)\n $ peek pn \n allocaArray (fromIntegral n) $ \\pks -> do\n whenSuccess (raw_clCreateKernelsInProgram prg n pks nullPtr)\n $ peekArray (fromIntegral n) pks\n\n-- | Increments the program program reference count. 'clRetainKernel' returns\n-- 'True' if the function is executed successfully. 'clCreateKernel' or\n-- 'clCreateKernelsInProgram' do an implicit retain.\nclRetainKernel :: CLKernel -> IO Bool\nclRetainKernel krn = wrapCheckSuccess $ raw_clRetainKernel krn\n\n-- | Decrements the kernel reference count. The kernel object is deleted once\n-- the number of instances that are retained to kernel become zero and the\n-- kernel object is no longer needed by any enqueued commands that use\n-- kernel. 'clReleaseKernel' returns 'True' if the function is executed\n-- successfully.\nclReleaseKernel :: CLKernel -> IO Bool\nclReleaseKernel krn = wrapCheckSuccess $ raw_clReleaseKernel krn\n\n{-| Used to set the argument value for a specific argument of a kernel.\n\nA kernel object does not update the reference count for objects such as memory,\nsampler objects specified as argument values by 'clSetKernelArg', Users may not\nrely on a kernel object to retain objects specified as argument values to the\nkernel.\n\nImplementations shall not allow 'CLKernel' objects to hold reference counts to\n'CLKernel' arguments, because no mechanism is provided for the user to tell the\nkernel to release that ownership right. If the kernel holds ownership rights on\nkernel args, that would make it impossible for the user to tell with certainty\nwhen he may safely release user allocated resources associated with OpenCL\nobjects such as the CLMem backing store used with 'CL_MEM_USE_HOST_PTR'.\n\n'clSetKernelArg' throws one of the following 'CLError' exceptions when fails:\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n \n * 'CL_INVALID_ARG_INDEX' if arg_index is not a valid argument index.\n\n * 'CL_INVALID_ARG_VALUE' if arg_value specified is NULL for an argument that is\nnot declared with the __local qualifier or vice-versa.\n\n * 'CL_INVALID_MEM_OBJECT' for an argument declared to be a memory object when\nthe specified arg_value is not a valid memory object.\n\n * 'CL_INVALID_SAMPLER' for an argument declared to be of type sampler_t when\nthe specified arg_value is not a valid sampler object.\n\n * 'CL_INVALID_ARG_SIZE' if arg_size does not match the size of the data type\nfor an argument that is not a memory object or if the argument is a memory\nobject and arg_size != sizeof(cl_mem) or if arg_size is zero and the argument is\ndeclared with the __local qualifier or if the argument is a sampler and arg_size\n!= sizeof(cl_sampler). \n-}\nclSetKernelArg :: Storable a => CLKernel -> CLuint -> a -> IO ()\nclSetKernelArg krn idx val = with val $ \\pval -> do\n whenSuccess (raw_clSetKernelArg krn idx (fromIntegral . sizeOf $ val) (castPtr pval))\n $ return ()\n\n#c\nenum CLKernelInfo {\n cL_KERNEL_FUNCTION_NAME=CL_KERNEL_FUNCTION_NAME,\n cL_KERNEL_NUM_ARGS=CL_KERNEL_NUM_ARGS,\n cL_KERNEL_REFERENCE_COUNT=CL_KERNEL_REFERENCE_COUNT,\n cL_KERNEL_CONTEXT=CL_KERNEL_CONTEXT,\n cL_KERNEL_PROGRAM=CL_KERNEL_PROGRAM\n };\n#endc\n{#enum CLKernelInfo {upcaseFirstLetter} #}\n\ngetKernelInfoSize :: CLKernel -> CLKernelInfo_ -> IO CSize\ngetKernelInfoSize krn infoid = alloca $ \\(val :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid 0 nullPtr val)\n $ peek val\n \n-- | Return the kernel function name.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_FUNCTION_NAME'.\nclGetKernelFunctionName :: CLKernel -> IO String\nclGetKernelFunctionName krn = do\n n <- getKernelInfoSize krn infoid\n allocaArray (fromIntegral n) $ \\(buff :: CString) -> do\n whenSuccess (raw_clGetKernelInfo krn infoid n (castPtr buff) nullPtr)\n $ peekCString buff\n where \n infoid = getCLValue CL_KERNEL_FUNCTION_NAME\n\n-- | Return the number of arguments to kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_NUM_ARGS'.\nclGetKernelNumArgs :: CLKernel -> IO CLuint\nclGetKernelNumArgs krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_NUM_ARGS\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the kernel 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 clGetKernelInfo with\n-- 'CL_KERNEL_REFERENCE_COUNT'.\nclGetKernelReferenceCount :: CLKernel -> IO CLuint\nclGetKernelReferenceCount krn = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the context associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_CONTEXT'.\nclGetKernelContext :: CLKernel -> IO CLContext\nclGetKernelContext krn = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the program object associated with kernel.\n--\n-- This function execute OpenCL clGetKernelInfo with 'CL_KERNEL_PROGRAM'.\nclGetKernelProgram :: CLKernel -> IO CLProgram\nclGetKernelProgram krn = wrapGetInfo (\\(dat :: Ptr CLProgram) \n -> raw_clGetKernelInfo krn infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_KERNEL_PROGRAM\n size = fromIntegral $ sizeOf (nullPtr::CLProgram)\n\n\n#c\nenum CLKernelGroupInfo {\n cL_KERNEL_WORK_GROUP_SIZE=CL_KERNEL_WORK_GROUP_SIZE,\n cL_KERNEL_COMPILE_WORK_GROUP_SIZE=CL_KERNEL_COMPILE_WORK_GROUP_SIZE,\n cL_KERNEL_LOCAL_MEM_SIZE=CL_KERNEL_LOCAL_MEM_SIZE,\n };\n#endc\n{#enum CLKernelGroupInfo {upcaseFirstLetter} #}\n\n-- | This provides a mechanism for the application to query the work-group size\n-- that can be used to execute a kernel on a specific device given by\n-- device. The OpenCL implementation uses the resource requirements of the\n-- kernel (register usage etc.) to determine what this work-group size should\n-- be.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_WORK_GROUP_SIZE'.\nclGetKernelWorkGroupSize :: CLKernel -> CLDeviceID -> IO CSize\nclGetKernelWorkGroupSize krn device = wrapGetInfo (\\(dat :: Ptr CSize)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_WORK_GROUP_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Returns the work-group size specified by the __attribute__((reqd_work_gr\n-- oup_size(X, Y, Z))) qualifier. See Function Qualifiers. If the work-group\n-- size is not specified using the above attribute qualifier (0, 0, 0) is\n-- returned.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_COMPILE_WORK_GROUP_SIZE'.\nclGetKernelCompileWorkGroupSize :: CLKernel -> CLDeviceID -> IO [CSize]\nclGetKernelCompileWorkGroupSize krn device = do\n allocaArray num $ \\(buff :: Ptr CSize) -> do\n whenSuccess (raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr buff) nullPtr)\n $ peekArray num buff\n where \n infoid = getCLValue CL_KERNEL_COMPILE_WORK_GROUP_SIZE\n num = 3\n elemSize = fromIntegral $ sizeOf (0::CSize)\n size = fromIntegral $ num * elemSize\n\n\n-- | Returns the amount of local memory in bytes being used by a kernel. This\n-- includes local memory that may be needed by an implementation to execute the\n-- kernel, variables declared inside the kernel with the __local address\n-- qualifier and local memory to be allocated for arguments to the kernel\n-- declared as pointers with the __local address qualifier and whose size is\n-- specified with 'clSetKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel declared\n-- with the __local address qualifier, is not specified, its size is assumed to\n-- be 0.\n--\n-- This function execute OpenCL clGetKernelWorkGroupInfo with\n-- 'CL_KERNEL_LOCAL_MEM_SIZE'.\nclGetKernelLocalMemSize :: CLKernel -> CLDeviceID -> IO CLulong\nclGetKernelLocalMemSize krn device = wrapGetInfo (\\(dat :: Ptr CLulong)\n -> raw_clGetKernelWorkGroupInfo krn device infoid size (castPtr dat)) id\n where\n infoid = getCLValue CL_KERNEL_LOCAL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CLulong)\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ceab468243a7f60713af981912f161aa6be00cf2","subject":"Forgot to add the file with helper functions for tree DND.","message":"Forgot to add the file with helper functions for tree DND.\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/gtk2hs\/vte.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"408ff7a883ee4361a3e246614458e5e0d51cbbd2","subject":"[project @ 2004-07-16 15:14:47 by duncan_coutts]","message":"[project @ 2004-07-16 15:14:47 by duncan_coutts]\n\nnew module for dealing with GErrors\n(oops this should have been comitted before the other patches)\n\ndarcs-hash:20040716151447-d6ff7-dba961151778ae0a7100d256a1ce884de9c9a580.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/glib\/GError.chs","new_file":"gtk\/glib\/GError.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/thiagoarrais\/gtk2hs.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"52d9ec7eaed810edd4b75ee36aac3d4a431be4b8","subject":"CuddHook","message":"CuddHook\n","repos":"maweki\/haskell_cudd,adamwalker\/haskell_cudd","old_file":"CuddHook.chs","new_file":"CuddHook.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/adamwalker\/haskell_cudd.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"d83dec09b211ad55e9080d1a7f4be8195f35cf7b","subject":"Binding to Errhandler","message":"Binding to Errhandler\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Errhandler.chs","new_file":"src\/Control\/Parallel\/MPI\/Errhandler.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/bjpop\/haskell-mpi.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"c795671138c3c7b02550ef48c2e093c4767da1b6","subject":"[project @ 2002-12-03 13:42:35 by as49] Added a file.","message":"[project @ 2002-12-03 13:42:35 by as49]\nAdded a file.\n","repos":"vincenthz\/webkit","old_file":"gtk\/treeList\/TreeModelSort.chs","new_file":"gtk\/treeList\/TreeModelSort.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TreeModelSort@\n--\n-- Author : Axel Simon\n-- \n-- Created: 9 July 2002\n--\n-- Version $Revision: 1.1 $ from $Date: 2002\/12\/03 13:42:35 $\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-- * @ref type TreeModelSort@ is an aggregated class to @ref type TreeModel@.\n-- It turns any object derived from @ref type TreeModel@ into a store that\n-- is sorted.\n--\n--- DOCU ----------------------------------------------------------------------\n--\n--- TODO ----------------------------------------------------------------------\nmodule TreeModelSort(\n TreeModelSort,\n TreeModelSortClass\n\n ) where\n\nimport Monad\t(liftM, when)\nimport Foreign\nimport UTFCForeign\n{#import Hierarchy#}\nimport Signal\t \n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n","old_contents":"","returncode":1,"stderr":"error: pathspec 'gtk\/treeList\/TreeModelSort.chs' did not match any file(s) known to git\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"4fd6a266b03fda05d828a07f9ca83fd55027145e","subject":"No pattern splices in 7.6.x","message":"No pattern splices in 7.6.x\n","repos":"DanielG\/bindings-libsoup","old_file":"src\/Network\/LibSoup\/Util.chs","new_file":"src\/Network\/LibSoup\/Util.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"remote: Support for password authentication was removed on August 13, 2021.\nremote: Please see https:\/\/docs.github.com\/en\/get-started\/getting-started-with-git\/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.\nfatal: Authentication failed for 'https:\/\/github.com\/DanielG\/bindings-libsoup.git\/'\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"2750054048ea67461be954072d19df8c5ecd9822","subject":"Initial experimentation","message":"Initial experimentation\n","repos":"iu-parfunc\/haskell-hpx,iu-parfunc\/haskell-hpx","old_file":"Hpx.chs","new_file":"Hpx.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/iu-parfunc\/haskell-hpx.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"26a340735696d2011a4798679d479462a5e7978a","subject":"Minor changes","message":"Minor changes\n","repos":"kaizhang\/igraph,giorgidze\/igraph","old_file":"Data\/IGraph\/Internal\/Constants.chs","new_file":"Data\/IGraph\/Internal\/Constants.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/kaizhang\/igraph.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"01f476ae6ea901682c2b8d3876c3c59fecde6ac7","subject":"beginnings of c2hs project","message":"beginnings of c2hs project\n","repos":"fffej\/haskellprojects,fffej\/haskellprojects","old_file":"kepler\/Kepler.chs","new_file":"kepler\/Kepler.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/fffej\/haskellprojects.git\/': The requested URL returned error: 403\n","license":"bsd-2-clause","lang":"C2hs Haskell"} {"commit":"6720ed676635f2e79d1938a975381456ca0b23a0","subject":"Renaming of import","message":"Renaming of import\n","repos":"HIPERFIT\/hopencl,HIPERFIT\/hopencl","old_file":"Foreign\/OpenCL\/Bindings\/Finalizers.chs","new_file":"Foreign\/OpenCL\/Bindings\/Finalizers.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/HIPERFIT\/hopencl.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bd2ab96a67edfe78ed1267e3471201235e7ea10d","subject":"[project @ 2004-07-16 15:14:47 by duncan_coutts] new module for dealing with GErrors (oops this should have been comitted before the other patches)","message":"[project @ 2004-07-16 15:14:47 by duncan_coutts]\nnew module for dealing with GErrors\n(oops this should have been comitted before the other patches)\n\n","repos":"gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/glib\/GError.chs","new_file":"gtk\/glib\/GError.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/gtk2hs\/vte.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"6618c4d3d4eccc6d60ca76e4b20252ee07df9297","subject":"[project @ 2002-12-03 13:42:35 by as49] Added a file.","message":"[project @ 2002-12-03 13:42:35 by as49]\nAdded a file.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit","old_file":"gtk\/treeList\/TreeModelSort.chs","new_file":"gtk\/treeList\/TreeModelSort.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/gtk2hs\/vte.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f68a93dde1b14e9e6a9f64c765115ceeeeaff823","subject":"FFI bindings all in one","message":"FFI bindings all in one\n\nIgnore-this: e99de74483766e085299e43972eeb22\n\ndarcs-hash:20090917092053-9241b-b985a29e4949e85b70269098f4f1a718351a52db.gz\n","repos":"tmcdonell\/hfx,tmcdonell\/hfx,tmcdonell\/hfx","old_file":"src\/Kernels.chs","new_file":"src\/Kernels.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/tmcdonell\/hfx.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"be5c447daa0790852c05fd3064b0c77155e94b4c","subject":"Check for null pointers","message":"Check for null pointers\n","repos":"Berengal\/SFML---Haskell-bindings","old_file":"SFML\/Audio\/Internal\/Music.chs","new_file":"SFML\/Audio\/Internal\/Music.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/Berengal\/SFML---Haskell-bindings.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"ecf317f154dff6ca7215185bb0e9d5fabb28f73e","subject":"Test: wrapper for multi-dimensional arrays?","message":"Test: wrapper for multi-dimensional arrays?\n\nIgnore-this: 14384c9fc8b21ef047637788ae610da7\n\ndarcs-hash:20090722052425-115f9-ace441443e3c4e5ff5f5f9578a0097dc461590a7.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Array.chs","new_file":"Foreign\/CUDA\/Array.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/mwu-tow\/cuda.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8d5f603e43b8160561f5c26b7f036200d9b653b6","subject":"[project @ 2004-07-16 15:14:47 by duncan_coutts] new module for dealing with GErrors (oops this should have been comitted before the other patches)","message":"[project @ 2004-07-16 15:14:47 by duncan_coutts]\nnew module for dealing with GErrors\n(oops this should have been comitted before the other patches)\n","repos":"vincenthz\/webkit","old_file":"gtk\/glib\/GError.chs","new_file":"gtk\/glib\/GError.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/vincenthz\/webkit.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"f2c14006ad57547ab3edac266b8169056b5b229b","subject":"Added Request opaque type.","message":"Added Request opaque type.\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Bindings\/MPI\/Request.chs","new_file":"src\/Bindings\/MPI\/Request.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/bjpop\/haskell-mpi.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"7f8d6c43f09f4c2adf2dabeccf93ea23dc919465","subject":"[project @ 2002-12-03 13:42:35 by as49]","message":"[project @ 2002-12-03 13:42:35 by as49]\n\nAdded a file.\n\ndarcs-hash:20021203134235-d90cf-36ceeef6af79f47fd9579ae212809511fc4b6cf2.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/treeList\/TreeModelSort.chs","new_file":"gtk\/treeList\/TreeModelSort.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/thiagoarrais\/gtk2hs.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b3ee4320203a55b9653f6ce03c0ea35102cc181c","subject":"Forgot to add the file with helper functions for tree DND.","message":"Forgot to add the file with helper functions for tree DND.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/vincenthz\/webkit.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"b2e1577a51339336508137f84a500502c65fb5fa","subject":"Reflog","message":"Reflog\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Reflog.chs","new_file":"src\/haskell\/Data\/HGit2\/Reflog.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/norm2782\/hgit2.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"0eff97db4ba9fcbfb0a98390a3e6229889f72892","subject":"Added cloneTo64F","message":"Added cloneTo64F\n","repos":"aleator\/CV,aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/aleator\/CV.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f69f755a3f1333fb1e50ca9de7803b315b975781","subject":"Vector is a chs file too","message":"Vector is a chs file too\n","repos":"haraldsteinlechner\/assimp,joelburget\/assimp,haraldsteinlechner\/assimp,joelburget\/assimp","old_file":"Graphics\/Formats\/Assimp\/Vector.chs","new_file":"Graphics\/Formats\/Assimp\/Vector.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/joelburget\/assimp.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"f5a72c913d3036af90f4d6e91cd3191ecff48dfb","subject":"add forgotten .Init","message":"add forgotten .Init\n","repos":"abbradar\/MySDL","old_file":"src\/Graphics\/UI\/SDL\/Init.chs","new_file":"src\/Graphics\/UI\/SDL\/Init.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/abbradar\/MySDL.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"cfdf313c887b2eca326e4c84371b851ec0bb92fe","subject":"Forgot to add the file with helper functions for tree DND.","message":"Forgot to add the file with helper functions for tree DND.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/gtk2hs\/gtksourceview.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"d53cdc6f51860c05a908f45f52b20b18b98310a5","subject":"add missing file","message":"add missing file\n","repos":"adamwalker\/haskell_cudd,maweki\/haskell_cudd","old_file":"CuddInternal.chs","new_file":"CuddInternal.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/maweki\/haskell_cudd.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"34308e4ac6ef1a531d241864e09e2a4b4ef624d9","subject":"Missing file","message":"Missing file\n","repos":"aleator\/CV,BeautifulDestinations\/CV,TomMD\/CV,aleator\/CV","old_file":"CV\/Calibration.chs","new_file":"CV\/Calibration.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/aleator\/CV.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"8c49c0eb26d31c3c4371e06bfdee4fba25e15043","subject":"Actually add src\/haskell\/Data\/HGit2\/ODBBackend.chs","message":"Actually add src\/haskell\/Data\/HGit2\/ODBBackend.chs\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/ODBBackend.chs","new_file":"src\/haskell\/Data\/HGit2\/ODBBackend.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/norm2782\/hgit2.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"5fa7e69b0b1df6b28cf6bf7f27c989fdfeac4f66","subject":"Forgot to add the file with helper functions for tree DND.","message":"Forgot to add the file with helper functions for tree DND.\n\ndarcs-hash:20071209081148-e1dd6-d0ff82be3ecc7a6b8c51729e6b33fc771150b6d2.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeDrag.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/thiagoarrais\/gtk2hs.git\/': The requested URL returned error: 403\n","license":"lgpl-2.1","lang":"C2hs Haskell"} {"commit":"ffeb3bb2768375dd358f70b12152c569a9639d23","subject":"Fixed wrong module path for module SFML.Window.Internal","message":"Fixed wrong module path for module SFML.Window.Internal\n","repos":"Berengal\/SFML---Haskell-bindings","old_file":"SFML\/Window\/Internal.chs","new_file":"SFML\/Window\/Internal.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/Berengal\/SFML---Haskell-bindings.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"} {"commit":"bdc8c8935698b1463d346de5ca48adf630b665e9","subject":"Actually include PerfCounter module","message":"Actually include PerfCounter module\n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/PerfCounter.chs","new_file":"src\/Database\/HyperDex\/Internal\/PerfCounter.chs","new_contents":"","old_contents":"","returncode":128,"stderr":"fatal: unable to access 'https:\/\/github.com\/AaronFriel\/hyhac.git\/': The requested URL returned error: 403\n","license":"bsd-3-clause","lang":"C2hs Haskell"}